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 "CheckExprLifetime.h" |
14 | #include "TreeTransform.h" |
15 | #include "UsedDeclVisitor.h" |
16 | #include "clang/AST/ASTConsumer.h" |
17 | #include "clang/AST/ASTContext.h" |
18 | #include "clang/AST/ASTLambda.h" |
19 | #include "clang/AST/ASTMutationListener.h" |
20 | #include "clang/AST/CXXInheritance.h" |
21 | #include "clang/AST/DeclObjC.h" |
22 | #include "clang/AST/DeclTemplate.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/Basic/TypeTraits.h" |
40 | #include "clang/Lex/LiteralSupport.h" |
41 | #include "clang/Lex/Preprocessor.h" |
42 | #include "clang/Sema/AnalysisBasedWarnings.h" |
43 | #include "clang/Sema/DeclSpec.h" |
44 | #include "clang/Sema/DelayedDiagnostic.h" |
45 | #include "clang/Sema/Designator.h" |
46 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
47 | #include "clang/Sema/Initialization.h" |
48 | #include "clang/Sema/Lookup.h" |
49 | #include "clang/Sema/Overload.h" |
50 | #include "clang/Sema/ParsedTemplate.h" |
51 | #include "clang/Sema/Scope.h" |
52 | #include "clang/Sema/ScopeInfo.h" |
53 | #include "clang/Sema/SemaCUDA.h" |
54 | #include "clang/Sema/SemaFixItUtils.h" |
55 | #include "clang/Sema/SemaInternal.h" |
56 | #include "clang/Sema/SemaObjC.h" |
57 | #include "clang/Sema/SemaOpenMP.h" |
58 | #include "clang/Sema/SemaPseudoObject.h" |
59 | #include "clang/Sema/Template.h" |
60 | #include "llvm/ADT/STLExtras.h" |
61 | #include "llvm/ADT/STLForwardCompat.h" |
62 | #include "llvm/ADT/StringExtras.h" |
63 | #include "llvm/Support/Casting.h" |
64 | #include "llvm/Support/ConvertUTF.h" |
65 | #include "llvm/Support/SaveAndRestore.h" |
66 | #include "llvm/Support/TypeSize.h" |
67 | #include <optional> |
68 | |
69 | using namespace clang; |
70 | using namespace sema; |
71 | |
72 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { |
73 | // See if this is an auto-typed variable whose initializer we are parsing. |
74 | if (ParsingInitForAutoVars.count(Ptr: D)) |
75 | return false; |
76 | |
77 | // See if this is a deleted function. |
78 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
79 | if (FD->isDeleted()) |
80 | return false; |
81 | |
82 | // If the function has a deduced return type, and we can't deduce it, |
83 | // then we can't use it either. |
84 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
85 | DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false)) |
86 | return false; |
87 | |
88 | // See if this is an aligned allocation/deallocation function that is |
89 | // unavailable. |
90 | if (TreatUnavailableAsInvalid && |
91 | isUnavailableAlignedAllocationFunction(FD: *FD)) |
92 | return false; |
93 | } |
94 | |
95 | // See if this function is unavailable. |
96 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && |
97 | cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable) |
98 | return false; |
99 | |
100 | if (isa<UnresolvedUsingIfExistsDecl>(Val: D)) |
101 | return false; |
102 | |
103 | return true; |
104 | } |
105 | |
106 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { |
107 | // Warn if this is used but marked unused. |
108 | if (const auto *A = D->getAttr<UnusedAttr>()) { |
109 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) |
110 | // should diagnose them. |
111 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && |
112 | A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) { |
113 | const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext()); |
114 | if (DC && !DC->hasAttr<UnusedAttr>()) |
115 | S.Diag(Loc, DiagID: diag::warn_used_but_marked_unused) << D; |
116 | } |
117 | } |
118 | } |
119 | |
120 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { |
121 | assert(Decl && Decl->isDeleted()); |
122 | |
123 | if (Decl->isDefaulted()) { |
124 | // If the method was explicitly defaulted, point at that declaration. |
125 | if (!Decl->isImplicit()) |
126 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_implicitly_deleted); |
127 | |
128 | // Try to diagnose why this special member function was implicitly |
129 | // deleted. This might fail, if that reason no longer applies. |
130 | DiagnoseDeletedDefaultedFunction(FD: Decl); |
131 | return; |
132 | } |
133 | |
134 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl); |
135 | if (Ctor && Ctor->isInheritingConstructor()) |
136 | return NoteDeletedInheritingConstructor(CD: Ctor); |
137 | |
138 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_availability_specified_here) |
139 | << Decl << 1; |
140 | } |
141 | |
142 | /// Determine whether a FunctionDecl was ever declared with an |
143 | /// explicit storage class. |
144 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { |
145 | for (auto *I : D->redecls()) { |
146 | if (I->getStorageClass() != SC_None) |
147 | return true; |
148 | } |
149 | return false; |
150 | } |
151 | |
152 | /// Check whether we're in an extern inline function and referring to a |
153 | /// variable or function with internal linkage (C11 6.7.4p3). |
154 | /// |
155 | /// This is only a warning because we used to silently accept this code, but |
156 | /// in many cases it will not behave correctly. This is not enabled in C++ mode |
157 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) |
158 | /// and so while there may still be user mistakes, most of the time we can't |
159 | /// prove that there are errors. |
160 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, |
161 | const NamedDecl *D, |
162 | SourceLocation Loc) { |
163 | // This is disabled under C++; there are too many ways for this to fire in |
164 | // contexts where the warning is a false positive, or where it is technically |
165 | // correct but benign. |
166 | if (S.getLangOpts().CPlusPlus) |
167 | return; |
168 | |
169 | // Check if this is an inlined function or method. |
170 | FunctionDecl *Current = S.getCurFunctionDecl(); |
171 | if (!Current) |
172 | return; |
173 | if (!Current->isInlined()) |
174 | return; |
175 | if (!Current->isExternallyVisible()) |
176 | return; |
177 | |
178 | // Check if the decl has internal linkage. |
179 | if (D->getFormalLinkage() != Linkage::Internal) |
180 | return; |
181 | |
182 | // Downgrade from ExtWarn to Extension if |
183 | // (1) the supposedly external inline function is in the main file, |
184 | // and probably won't be included anywhere else. |
185 | // (2) the thing we're referencing is a pure function. |
186 | // (3) the thing we're referencing is another inline function. |
187 | // This last can give us false negatives, but it's better than warning on |
188 | // wrappers for simple C library functions. |
189 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D); |
190 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); |
191 | if (!DowngradeWarning && UsedFn) |
192 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); |
193 | |
194 | S.Diag(Loc, DiagID: DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet |
195 | : diag::ext_internal_in_extern_inline) |
196 | << /*IsVar=*/!UsedFn << D; |
197 | |
198 | S.MaybeSuggestAddingStaticToDecl(D: Current); |
199 | |
200 | S.Diag(Loc: D->getCanonicalDecl()->getLocation(), DiagID: diag::note_entity_declared_at) |
201 | << D; |
202 | } |
203 | |
204 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { |
205 | const FunctionDecl *First = Cur->getFirstDecl(); |
206 | |
207 | // Suggest "static" on the function, if possible. |
208 | if (!hasAnyExplicitStorageClass(D: First)) { |
209 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); |
210 | Diag(Loc: DeclBegin, DiagID: diag::note_convert_inline_to_static) |
211 | << Cur << FixItHint::CreateInsertion(InsertionLoc: DeclBegin, Code: "static " ); |
212 | } |
213 | } |
214 | |
215 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
216 | const ObjCInterfaceDecl *UnknownObjCClass, |
217 | bool ObjCPropertyAccess, |
218 | bool AvoidPartialAvailabilityChecks, |
219 | ObjCInterfaceDecl *ClassReceiver, |
220 | bool SkipTrailingRequiresClause) { |
221 | SourceLocation Loc = Locs.front(); |
222 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) { |
223 | // If there were any diagnostics suppressed by template argument deduction, |
224 | // emit them now. |
225 | auto Pos = SuppressedDiagnostics.find(Val: D->getCanonicalDecl()); |
226 | if (Pos != SuppressedDiagnostics.end()) { |
227 | for (const PartialDiagnosticAt &Suppressed : Pos->second) |
228 | Diag(Loc: Suppressed.first, PD: Suppressed.second); |
229 | |
230 | // Clear out the list of suppressed diagnostics, so that we don't emit |
231 | // them again for this specialization. However, we don't obsolete this |
232 | // entry from the table, because we want to avoid ever emitting these |
233 | // diagnostics again. |
234 | Pos->second.clear(); |
235 | } |
236 | |
237 | // C++ [basic.start.main]p3: |
238 | // The function 'main' shall not be used within a program. |
239 | if (cast<FunctionDecl>(Val: D)->isMain()) |
240 | Diag(Loc, DiagID: diag::ext_main_used); |
241 | |
242 | diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc); |
243 | } |
244 | |
245 | // See if this is an auto-typed variable whose initializer we are parsing. |
246 | if (ParsingInitForAutoVars.count(Ptr: D)) { |
247 | if (isa<BindingDecl>(Val: D)) { |
248 | Diag(Loc, DiagID: diag::err_binding_cannot_appear_in_own_initializer) |
249 | << D->getDeclName(); |
250 | } else { |
251 | Diag(Loc, DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer) |
252 | << D->getDeclName() << cast<VarDecl>(Val: D)->getType(); |
253 | } |
254 | return true; |
255 | } |
256 | |
257 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
258 | // See if this is a deleted function. |
259 | if (FD->isDeleted()) { |
260 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD); |
261 | if (Ctor && Ctor->isInheritingConstructor()) |
262 | Diag(Loc, DiagID: diag::err_deleted_inherited_ctor_use) |
263 | << Ctor->getParent() |
264 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); |
265 | else { |
266 | StringLiteral *Msg = FD->getDeletedMessage(); |
267 | Diag(Loc, DiagID: diag::err_deleted_function_use) |
268 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
269 | } |
270 | NoteDeletedFunction(Decl: FD); |
271 | return true; |
272 | } |
273 | |
274 | // [expr.prim.id]p4 |
275 | // A program that refers explicitly or implicitly to a function with a |
276 | // trailing requires-clause whose constraint-expression is not satisfied, |
277 | // other than to declare it, is ill-formed. [...] |
278 | // |
279 | // See if this is a function with constraints that need to be satisfied. |
280 | // Check this before deducing the return type, as it might instantiate the |
281 | // definition. |
282 | if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { |
283 | ConstraintSatisfaction Satisfaction; |
284 | if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc, |
285 | /*ForOverloadResolution*/ true)) |
286 | // A diagnostic will have already been generated (non-constant |
287 | // constraint expression, for example) |
288 | return true; |
289 | if (!Satisfaction.IsSatisfied) { |
290 | Diag(Loc, |
291 | DiagID: diag::err_reference_to_function_with_unsatisfied_constraints) |
292 | << D; |
293 | DiagnoseUnsatisfiedConstraint(Satisfaction); |
294 | return true; |
295 | } |
296 | } |
297 | |
298 | // If the function has a deduced return type, and we can't deduce it, |
299 | // then we can't use it either. |
300 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
301 | DeduceReturnType(FD, Loc)) |
302 | return true; |
303 | |
304 | if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD)) |
305 | return true; |
306 | |
307 | } |
308 | |
309 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) { |
310 | // Lambdas are only default-constructible or assignable in C++2a onwards. |
311 | if (MD->getParent()->isLambda() && |
312 | ((isa<CXXConstructorDecl>(Val: MD) && |
313 | cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) || |
314 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { |
315 | Diag(Loc, DiagID: diag::warn_cxx17_compat_lambda_def_ctor_assign) |
316 | << !isa<CXXConstructorDecl>(Val: MD); |
317 | } |
318 | } |
319 | |
320 | auto getReferencedObjCProp = [](const NamedDecl *D) -> |
321 | const ObjCPropertyDecl * { |
322 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) |
323 | return MD->findPropertyDecl(); |
324 | return nullptr; |
325 | }; |
326 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { |
327 | if (diagnoseArgIndependentDiagnoseIfAttrs(ND: ObjCPDecl, Loc)) |
328 | return true; |
329 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) { |
330 | return true; |
331 | } |
332 | |
333 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions |
334 | // Only the variables omp_in and omp_out are allowed in the combiner. |
335 | // Only the variables omp_priv and omp_orig are allowed in the |
336 | // initializer-clause. |
337 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext); |
338 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && |
339 | isa<VarDecl>(Val: D)) { |
340 | Diag(Loc, DiagID: diag::err_omp_wrong_var_in_declare_reduction) |
341 | << getCurFunction()->HasOMPDeclareReductionCombiner; |
342 | Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D; |
343 | return true; |
344 | } |
345 | |
346 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions |
347 | // List-items in map clauses on this construct may only refer to the declared |
348 | // variable var and entities that could be referenced by a procedure defined |
349 | // at the same location. |
350 | // [OpenMP 5.2] Also allow iterator declared variables. |
351 | if (LangOpts.OpenMP && isa<VarDecl>(Val: D) && |
352 | !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) { |
353 | Diag(Loc, DiagID: diag::err_omp_declare_mapper_wrong_var) |
354 | << OpenMP().getOpenMPDeclareMapperVarName(); |
355 | Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D; |
356 | return true; |
357 | } |
358 | |
359 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) { |
360 | Diag(Loc, DiagID: diag::err_use_of_empty_using_if_exists); |
361 | Diag(Loc: EmptyD->getLocation(), DiagID: diag::note_empty_using_if_exists_here); |
362 | return true; |
363 | } |
364 | |
365 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, |
366 | AvoidPartialAvailabilityChecks, ClassReceiver); |
367 | |
368 | DiagnoseUnusedOfDecl(S&: *this, D, Loc); |
369 | |
370 | diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc); |
371 | |
372 | if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) { |
373 | if (getLangOpts().getFPEvalMethod() != |
374 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine && |
375 | PP.getLastFPEvalPragmaLocation().isValid() && |
376 | PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod()) |
377 | Diag(Loc: D->getLocation(), |
378 | DiagID: diag::err_type_available_only_in_default_eval_method) |
379 | << D->getName(); |
380 | } |
381 | |
382 | if (auto *VD = dyn_cast<ValueDecl>(Val: D)) |
383 | checkTypeSupport(Ty: VD->getType(), Loc, D: VD); |
384 | |
385 | if (LangOpts.SYCLIsDevice || |
386 | (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) { |
387 | if (!Context.getTargetInfo().isTLSSupported()) |
388 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
389 | if (VD->getTLSKind() != VarDecl::TLS_None) |
390 | targetDiag(Loc: *Locs.begin(), DiagID: diag::err_thread_unsupported); |
391 | } |
392 | |
393 | if (isa<ParmVarDecl>(Val: D) && isa<RequiresExprBodyDecl>(Val: D->getDeclContext()) && |
394 | !isUnevaluatedContext()) { |
395 | // C++ [expr.prim.req.nested] p3 |
396 | // A local parameter shall only appear as an unevaluated operand |
397 | // (Clause 8) within the constraint-expression. |
398 | Diag(Loc, DiagID: diag::err_requires_expr_parameter_referenced_in_evaluated_context) |
399 | << D; |
400 | Diag(Loc: D->getLocation(), DiagID: diag::note_entity_declared_at) << D; |
401 | return true; |
402 | } |
403 | |
404 | return false; |
405 | } |
406 | |
407 | void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, |
408 | ArrayRef<Expr *> Args) { |
409 | const SentinelAttr *Attr = D->getAttr<SentinelAttr>(); |
410 | if (!Attr) |
411 | return; |
412 | |
413 | // The number of formal parameters of the declaration. |
414 | unsigned NumFormalParams; |
415 | |
416 | // The kind of declaration. This is also an index into a %select in |
417 | // the diagnostic. |
418 | enum { CK_Function, CK_Method, CK_Block } CalleeKind; |
419 | |
420 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
421 | NumFormalParams = MD->param_size(); |
422 | CalleeKind = CK_Method; |
423 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
424 | NumFormalParams = FD->param_size(); |
425 | CalleeKind = CK_Function; |
426 | } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
427 | QualType Ty = VD->getType(); |
428 | const FunctionType *Fn = nullptr; |
429 | if (const auto *PtrTy = Ty->getAs<PointerType>()) { |
430 | Fn = PtrTy->getPointeeType()->getAs<FunctionType>(); |
431 | if (!Fn) |
432 | return; |
433 | CalleeKind = CK_Function; |
434 | } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) { |
435 | Fn = PtrTy->getPointeeType()->castAs<FunctionType>(); |
436 | CalleeKind = CK_Block; |
437 | } else { |
438 | return; |
439 | } |
440 | |
441 | if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn)) |
442 | NumFormalParams = proto->getNumParams(); |
443 | else |
444 | NumFormalParams = 0; |
445 | } else { |
446 | return; |
447 | } |
448 | |
449 | // "NullPos" is the number of formal parameters at the end which |
450 | // effectively count as part of the variadic arguments. This is |
451 | // useful if you would prefer to not have *any* formal parameters, |
452 | // but the language forces you to have at least one. |
453 | unsigned NullPos = Attr->getNullPos(); |
454 | assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel" ); |
455 | NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos); |
456 | |
457 | // The number of arguments which should follow the sentinel. |
458 | unsigned NumArgsAfterSentinel = Attr->getSentinel(); |
459 | |
460 | // If there aren't enough arguments for all the formal parameters, |
461 | // the sentinel, and the args after the sentinel, complain. |
462 | if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) { |
463 | Diag(Loc, DiagID: diag::warn_not_enough_argument) << D->getDeclName(); |
464 | Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) << int(CalleeKind); |
465 | return; |
466 | } |
467 | |
468 | // Otherwise, find the sentinel expression. |
469 | const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1]; |
470 | if (!SentinelExpr) |
471 | return; |
472 | if (SentinelExpr->isValueDependent()) |
473 | return; |
474 | if (Context.isSentinelNullExpr(E: SentinelExpr)) |
475 | return; |
476 | |
477 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', |
478 | // or 'NULL' if those are actually defined in the context. Only use |
479 | // 'nil' for ObjC methods, where it's much more likely that the |
480 | // variadic arguments form a list of object pointers. |
481 | SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc()); |
482 | std::string NullValue; |
483 | if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil" )) |
484 | NullValue = "nil" ; |
485 | else if (getLangOpts().CPlusPlus11) |
486 | NullValue = "nullptr" ; |
487 | else if (PP.isMacroDefined(Id: "NULL" )) |
488 | NullValue = "NULL" ; |
489 | else |
490 | NullValue = "(void*) 0" ; |
491 | |
492 | if (MissingNilLoc.isInvalid()) |
493 | Diag(Loc, DiagID: diag::warn_missing_sentinel) << int(CalleeKind); |
494 | else |
495 | Diag(Loc: MissingNilLoc, DiagID: diag::warn_missing_sentinel) |
496 | << int(CalleeKind) |
497 | << FixItHint::CreateInsertion(InsertionLoc: MissingNilLoc, Code: ", " + NullValue); |
498 | Diag(Loc: D->getLocation(), DiagID: diag::note_sentinel_here) |
499 | << int(CalleeKind) << Attr->getRange(); |
500 | } |
501 | |
502 | SourceRange Sema::getExprRange(Expr *E) const { |
503 | return E ? E->getSourceRange() : SourceRange(); |
504 | } |
505 | |
506 | //===----------------------------------------------------------------------===// |
507 | // Standard Promotions and Conversions |
508 | //===----------------------------------------------------------------------===// |
509 | |
510 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). |
511 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { |
512 | // Handle any placeholder expressions which made it here. |
513 | if (E->hasPlaceholderType()) { |
514 | ExprResult result = CheckPlaceholderExpr(E); |
515 | if (result.isInvalid()) return ExprError(); |
516 | E = result.get(); |
517 | } |
518 | |
519 | QualType Ty = E->getType(); |
520 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ); |
521 | |
522 | if (Ty->isFunctionType()) { |
523 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts())) |
524 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) |
525 | if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc())) |
526 | return ExprError(); |
527 | |
528 | E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
529 | CK: CK_FunctionToPointerDecay).get(); |
530 | } else if (Ty->isArrayType()) { |
531 | // In C90 mode, arrays only promote to pointers if the array expression is |
532 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has |
533 | // type 'array of type' is converted to an expression that has type 'pointer |
534 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression |
535 | // that has type 'array of type' ...". The relevant change is "an lvalue" |
536 | // (C90) to "an expression" (C99). |
537 | // |
538 | // C++ 4.2p1: |
539 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of |
540 | // T" can be converted to an rvalue of type "pointer to T". |
541 | // |
542 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { |
543 | ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty), |
544 | CK: CK_ArrayToPointerDecay); |
545 | if (Res.isInvalid()) |
546 | return ExprError(); |
547 | E = Res.get(); |
548 | } |
549 | } |
550 | return E; |
551 | } |
552 | |
553 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { |
554 | // Check to see if we are dereferencing a null pointer. If so, |
555 | // and if not volatile-qualified, this is undefined behavior that the |
556 | // optimizer will delete, so warn about it. People sometimes try to use this |
557 | // to get a deterministic trap and are surprised by clang's behavior. This |
558 | // only handles the pattern "*null", which is a very syntactic check. |
559 | const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()); |
560 | if (UO && UO->getOpcode() == UO_Deref && |
561 | UO->getSubExpr()->getType()->isPointerType()) { |
562 | const LangAS AS = |
563 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); |
564 | if ((!isTargetAddressSpace(AS) || |
565 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && |
566 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( |
567 | Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) && |
568 | !UO->getType().isVolatileQualified()) { |
569 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
570 | PD: S.PDiag(DiagID: diag::warn_indirection_through_null) |
571 | << UO->getSubExpr()->getSourceRange()); |
572 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
573 | PD: S.PDiag(DiagID: diag::note_indirection_through_null)); |
574 | } |
575 | } |
576 | } |
577 | |
578 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, |
579 | SourceLocation AssignLoc, |
580 | const Expr* RHS) { |
581 | const ObjCIvarDecl *IV = OIRE->getDecl(); |
582 | if (!IV) |
583 | return; |
584 | |
585 | DeclarationName MemberName = IV->getDeclName(); |
586 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); |
587 | if (!Member || !Member->isStr(Str: "isa" )) |
588 | return; |
589 | |
590 | const Expr *Base = OIRE->getBase(); |
591 | QualType BaseType = Base->getType(); |
592 | if (OIRE->isArrow()) |
593 | BaseType = BaseType->getPointeeType(); |
594 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) |
595 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { |
596 | ObjCInterfaceDecl *ClassDeclared = nullptr; |
597 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared); |
598 | if (!ClassDeclared->getSuperClass() |
599 | && (*ClassDeclared->ivar_begin()) == IV) { |
600 | if (RHS) { |
601 | NamedDecl *ObjectSetClass = |
602 | S.LookupSingleName(S: S.TUScope, |
603 | Name: &S.Context.Idents.get(Name: "object_setClass" ), |
604 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
605 | if (ObjectSetClass) { |
606 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc()); |
607 | S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_assign) |
608 | << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(), |
609 | Code: "object_setClass(" ) |
610 | << FixItHint::CreateReplacement( |
611 | RemoveRange: SourceRange(OIRE->getOpLoc(), AssignLoc), Code: "," ) |
612 | << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")" ); |
613 | } |
614 | else |
615 | S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_assign); |
616 | } else { |
617 | NamedDecl *ObjectGetClass = |
618 | S.LookupSingleName(S: S.TUScope, |
619 | Name: &S.Context.Idents.get(Name: "object_getClass" ), |
620 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
621 | if (ObjectGetClass) |
622 | S.Diag(Loc: OIRE->getExprLoc(), DiagID: diag::warn_objc_isa_use) |
623 | << FixItHint::CreateInsertion(InsertionLoc: OIRE->getBeginLoc(), |
624 | Code: "object_getClass(" ) |
625 | << FixItHint::CreateReplacement( |
626 | RemoveRange: SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), Code: ")" ); |
627 | else |
628 | S.Diag(Loc: OIRE->getLocation(), DiagID: diag::warn_objc_isa_use); |
629 | } |
630 | S.Diag(Loc: IV->getLocation(), DiagID: diag::note_ivar_decl); |
631 | } |
632 | } |
633 | } |
634 | |
635 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { |
636 | // Handle any placeholder expressions which made it here. |
637 | if (E->hasPlaceholderType()) { |
638 | ExprResult result = CheckPlaceholderExpr(E); |
639 | if (result.isInvalid()) return ExprError(); |
640 | E = result.get(); |
641 | } |
642 | |
643 | // C++ [conv.lval]p1: |
644 | // A glvalue of a non-function, non-array type T can be |
645 | // converted to a prvalue. |
646 | if (!E->isGLValue()) return E; |
647 | |
648 | QualType T = E->getType(); |
649 | assert(!T.isNull() && "r-value conversion on typeless expression?" ); |
650 | |
651 | // lvalue-to-rvalue conversion cannot be applied to types that decay to |
652 | // pointers (i.e. function or array types). |
653 | if (T->canDecayToPointerType()) |
654 | return E; |
655 | |
656 | // We don't want to throw lvalue-to-rvalue casts on top of |
657 | // expressions of certain types in C++. |
658 | if (getLangOpts().CPlusPlus) { |
659 | if (T == Context.OverloadTy || T->isRecordType() || |
660 | (T->isDependentType() && !T->isAnyPointerType() && |
661 | !T->isMemberPointerType())) |
662 | return E; |
663 | } |
664 | |
665 | // The C standard is actually really unclear on this point, and |
666 | // DR106 tells us what the result should be but not why. It's |
667 | // generally best to say that void types just doesn't undergo |
668 | // lvalue-to-rvalue at all. Note that expressions of unqualified |
669 | // 'void' type are never l-values, but qualified void can be. |
670 | if (T->isVoidType()) |
671 | return E; |
672 | |
673 | // OpenCL usually rejects direct accesses to values of 'half' type. |
674 | if (getLangOpts().OpenCL && |
675 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts()) && |
676 | T->isHalfType()) { |
677 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_half_load_store) |
678 | << 0 << T; |
679 | return ExprError(); |
680 | } |
681 | |
682 | CheckForNullPointerDereference(S&: *this, E); |
683 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) { |
684 | NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope, |
685 | Name: &Context.Idents.get(Name: "object_getClass" ), |
686 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
687 | if (ObjectGetClass) |
688 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use) |
689 | << FixItHint::CreateInsertion(InsertionLoc: OISA->getBeginLoc(), Code: "object_getClass(" ) |
690 | << FixItHint::CreateReplacement( |
691 | RemoveRange: SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), Code: ")" ); |
692 | else |
693 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_objc_isa_use); |
694 | } |
695 | else if (const ObjCIvarRefExpr *OIRE = |
696 | dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts())) |
697 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr); |
698 | |
699 | // C++ [conv.lval]p1: |
700 | // [...] If T is a non-class type, the type of the prvalue is the |
701 | // cv-unqualified version of T. Otherwise, the type of the |
702 | // rvalue is T. |
703 | // |
704 | // C99 6.3.2.1p2: |
705 | // If the lvalue has qualified type, the value has the unqualified |
706 | // version of the type of the lvalue; otherwise, the value has the |
707 | // type of the lvalue. |
708 | if (T.hasQualifiers()) |
709 | T = T.getUnqualifiedType(); |
710 | |
711 | // Under the MS ABI, lock down the inheritance model now. |
712 | if (T->isMemberPointerType() && |
713 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
714 | (void)isCompleteType(Loc: E->getExprLoc(), T); |
715 | |
716 | ExprResult Res = CheckLValueToRValueConversionOperand(E); |
717 | if (Res.isInvalid()) |
718 | return Res; |
719 | E = Res.get(); |
720 | |
721 | // Loading a __weak object implicitly retains the value, so we need a cleanup to |
722 | // balance that. |
723 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
724 | Cleanup.setExprNeedsCleanups(true); |
725 | |
726 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
727 | Cleanup.setExprNeedsCleanups(true); |
728 | |
729 | // C++ [conv.lval]p3: |
730 | // If T is cv std::nullptr_t, the result is a null pointer constant. |
731 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; |
732 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue, |
733 | FPO: CurFPFeatureOverrides()); |
734 | |
735 | // C11 6.3.2.1p2: |
736 | // ... if the lvalue has atomic type, the value has the non-atomic version |
737 | // of the type of the lvalue ... |
738 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { |
739 | T = Atomic->getValueType().getUnqualifiedType(); |
740 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(), |
741 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
742 | } |
743 | |
744 | return Res; |
745 | } |
746 | |
747 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { |
748 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); |
749 | if (Res.isInvalid()) |
750 | return ExprError(); |
751 | Res = DefaultLvalueConversion(E: Res.get()); |
752 | if (Res.isInvalid()) |
753 | return ExprError(); |
754 | return Res; |
755 | } |
756 | |
757 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { |
758 | QualType Ty = E->getType(); |
759 | ExprResult Res = E; |
760 | // Only do implicit cast for a function type, but not for a pointer |
761 | // to function type. |
762 | if (Ty->isFunctionType()) { |
763 | Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
764 | CK: CK_FunctionToPointerDecay); |
765 | if (Res.isInvalid()) |
766 | return ExprError(); |
767 | } |
768 | Res = DefaultLvalueConversion(E: Res.get()); |
769 | if (Res.isInvalid()) |
770 | return ExprError(); |
771 | return Res.get(); |
772 | } |
773 | |
774 | /// UsualUnaryConversions - Performs various conversions that are common to most |
775 | /// operators (C99 6.3). The conversions of array and function types are |
776 | /// sometimes suppressed. For example, the array->pointer conversion doesn't |
777 | /// apply if the array is an argument to the sizeof or address (&) operators. |
778 | /// In these instances, this routine should *not* be called. |
779 | ExprResult Sema::UsualUnaryConversions(Expr *E) { |
780 | // First, convert to an r-value. |
781 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
782 | if (Res.isInvalid()) |
783 | return ExprError(); |
784 | E = Res.get(); |
785 | |
786 | QualType Ty = E->getType(); |
787 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type" ); |
788 | |
789 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); |
790 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && |
791 | (getLangOpts().getFPEvalMethod() != |
792 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || |
793 | PP.getLastFPEvalPragmaLocation().isValid())) { |
794 | switch (EvalMethod) { |
795 | default: |
796 | llvm_unreachable("Unrecognized float evaluation method" ); |
797 | break; |
798 | case LangOptions::FEM_UnsetOnCommandLine: |
799 | llvm_unreachable("Float evaluation method should be set by now" ); |
800 | break; |
801 | case LangOptions::FEM_Double: |
802 | if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0) |
803 | // Widen the expression to double. |
804 | return Ty->isComplexType() |
805 | ? ImpCastExprToType(E, |
806 | Type: Context.getComplexType(T: Context.DoubleTy), |
807 | CK: CK_FloatingComplexCast) |
808 | : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast); |
809 | break; |
810 | case LangOptions::FEM_Extended: |
811 | if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0) |
812 | // Widen the expression to long double. |
813 | return Ty->isComplexType() |
814 | ? ImpCastExprToType( |
815 | E, Type: Context.getComplexType(T: Context.LongDoubleTy), |
816 | CK: CK_FloatingComplexCast) |
817 | : ImpCastExprToType(E, Type: Context.LongDoubleTy, |
818 | CK: CK_FloatingCast); |
819 | break; |
820 | } |
821 | } |
822 | |
823 | // Half FP have to be promoted to float unless it is natively supported |
824 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) |
825 | return ImpCastExprToType(E: Res.get(), Type: Context.FloatTy, CK: CK_FloatingCast); |
826 | |
827 | // Try to perform integral promotions if the object has a theoretically |
828 | // promotable type. |
829 | if (Ty->isIntegralOrUnscopedEnumerationType()) { |
830 | // C99 6.3.1.1p2: |
831 | // |
832 | // The following may be used in an expression wherever an int or |
833 | // unsigned int may be used: |
834 | // - an object or expression with an integer type whose integer |
835 | // conversion rank is less than or equal to the rank of int |
836 | // and unsigned int. |
837 | // - A bit-field of type _Bool, int, signed int, or unsigned int. |
838 | // |
839 | // If an int can represent all values of the original type, the |
840 | // value is converted to an int; otherwise, it is converted to an |
841 | // unsigned int. These are called the integer promotions. All |
842 | // other types are unchanged by the integer promotions. |
843 | |
844 | QualType PTy = Context.isPromotableBitField(E); |
845 | if (!PTy.isNull()) { |
846 | E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get(); |
847 | return E; |
848 | } |
849 | if (Context.isPromotableIntegerType(T: Ty)) { |
850 | QualType PT = Context.getPromotedIntegerType(PromotableType: Ty); |
851 | E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get(); |
852 | return E; |
853 | } |
854 | } |
855 | return E; |
856 | } |
857 | |
858 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
859 | /// do not have a prototype. Arguments that have type float or __fp16 |
860 | /// are promoted to double. All other argument types are converted by |
861 | /// UsualUnaryConversions(). |
862 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { |
863 | QualType Ty = E->getType(); |
864 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type" ); |
865 | |
866 | ExprResult Res = UsualUnaryConversions(E); |
867 | if (Res.isInvalid()) |
868 | return ExprError(); |
869 | E = Res.get(); |
870 | |
871 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) |
872 | // promote to double. |
873 | // Note that default argument promotion applies only to float (and |
874 | // half/fp16); it does not apply to _Float16. |
875 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
876 | if (BTy && (BTy->getKind() == BuiltinType::Half || |
877 | BTy->getKind() == BuiltinType::Float)) { |
878 | if (getLangOpts().OpenCL && |
879 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64" , LO: getLangOpts())) { |
880 | if (BTy->getKind() == BuiltinType::Half) { |
881 | E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
882 | } |
883 | } else { |
884 | E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get(); |
885 | } |
886 | } |
887 | if (BTy && |
888 | getLangOpts().getExtendIntArgs() == |
889 | LangOptions::ExtendArgsKind::ExtendTo64 && |
890 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && |
891 | Context.getTypeSizeInChars(T: BTy) < |
892 | Context.getTypeSizeInChars(T: Context.LongLongTy)) { |
893 | E = (Ty->isUnsignedIntegerType()) |
894 | ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast) |
895 | .get() |
896 | : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get(); |
897 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && |
898 | "Unexpected typesize for LongLongTy" ); |
899 | } |
900 | |
901 | // C++ performs lvalue-to-rvalue conversion as a default argument |
902 | // promotion, even on class types, but note: |
903 | // C++11 [conv.lval]p2: |
904 | // When an lvalue-to-rvalue conversion occurs in an unevaluated |
905 | // operand or a subexpression thereof the value contained in the |
906 | // referenced object is not accessed. Otherwise, if the glvalue |
907 | // has a class type, the conversion copy-initializes a temporary |
908 | // of type T from the glvalue and the result of the conversion |
909 | // is a prvalue for the temporary. |
910 | // FIXME: add some way to gate this entire thing for correctness in |
911 | // potentially potentially evaluated contexts. |
912 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { |
913 | ExprResult Temp = PerformCopyInitialization( |
914 | Entity: InitializedEntity::InitializeTemporary(Type: E->getType()), |
915 | EqualLoc: E->getExprLoc(), Init: E); |
916 | if (Temp.isInvalid()) |
917 | return ExprError(); |
918 | E = Temp.get(); |
919 | } |
920 | |
921 | return E; |
922 | } |
923 | |
924 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { |
925 | if (Ty->isIncompleteType()) { |
926 | // C++11 [expr.call]p7: |
927 | // After these conversions, if the argument does not have arithmetic, |
928 | // enumeration, pointer, pointer to member, or class type, the program |
929 | // is ill-formed. |
930 | // |
931 | // Since we've already performed array-to-pointer and function-to-pointer |
932 | // decay, the only such type in C++ is cv void. This also handles |
933 | // initializer lists as variadic arguments. |
934 | if (Ty->isVoidType()) |
935 | return VAK_Invalid; |
936 | |
937 | if (Ty->isObjCObjectType()) |
938 | return VAK_Invalid; |
939 | return VAK_Valid; |
940 | } |
941 | |
942 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
943 | return VAK_Invalid; |
944 | |
945 | if (Context.getTargetInfo().getTriple().isWasm() && |
946 | Ty.isWebAssemblyReferenceType()) { |
947 | return VAK_Invalid; |
948 | } |
949 | |
950 | if (Ty.isCXX98PODType(Context)) |
951 | return VAK_Valid; |
952 | |
953 | // C++11 [expr.call]p7: |
954 | // Passing a potentially-evaluated argument of class type (Clause 9) |
955 | // having a non-trivial copy constructor, a non-trivial move constructor, |
956 | // or a non-trivial destructor, with no corresponding parameter, |
957 | // is conditionally-supported with implementation-defined semantics. |
958 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) |
959 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) |
960 | if (!Record->hasNonTrivialCopyConstructor() && |
961 | !Record->hasNonTrivialMoveConstructor() && |
962 | !Record->hasNonTrivialDestructor()) |
963 | return VAK_ValidInCXX11; |
964 | |
965 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) |
966 | return VAK_Valid; |
967 | |
968 | if (Ty->isObjCObjectType()) |
969 | return VAK_Invalid; |
970 | |
971 | if (getLangOpts().MSVCCompat) |
972 | return VAK_MSVCUndefined; |
973 | |
974 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're |
975 | // permitted to reject them. We should consider doing so. |
976 | return VAK_Undefined; |
977 | } |
978 | |
979 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { |
980 | // Don't allow one to pass an Objective-C interface to a vararg. |
981 | const QualType &Ty = E->getType(); |
982 | VarArgKind VAK = isValidVarArgType(Ty); |
983 | |
984 | // Complain about passing non-POD types through varargs. |
985 | switch (VAK) { |
986 | case VAK_ValidInCXX11: |
987 | DiagRuntimeBehavior( |
988 | Loc: E->getBeginLoc(), Statement: nullptr, |
989 | PD: PDiag(DiagID: diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); |
990 | [[fallthrough]]; |
991 | case VAK_Valid: |
992 | if (Ty->isRecordType()) { |
993 | // This is unlikely to be what the user intended. If the class has a |
994 | // 'c_str' member function, the user probably meant to call that. |
995 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
996 | PD: PDiag(DiagID: diag::warn_pass_class_arg_to_vararg) |
997 | << Ty << CT << hasCStrMethod(E) << ".c_str()" ); |
998 | } |
999 | break; |
1000 | |
1001 | case VAK_Undefined: |
1002 | case VAK_MSVCUndefined: |
1003 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
1004 | PD: PDiag(DiagID: diag::warn_cannot_pass_non_pod_arg_to_vararg) |
1005 | << getLangOpts().CPlusPlus11 << Ty << CT); |
1006 | break; |
1007 | |
1008 | case VAK_Invalid: |
1009 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
1010 | Diag(Loc: E->getBeginLoc(), |
1011 | DiagID: diag::err_cannot_pass_non_trivial_c_struct_to_vararg) |
1012 | << Ty << CT; |
1013 | else if (Ty->isObjCObjectType()) |
1014 | DiagRuntimeBehavior(Loc: E->getBeginLoc(), Statement: nullptr, |
1015 | PD: PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg) |
1016 | << Ty << CT); |
1017 | else |
1018 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg) |
1019 | << isa<InitListExpr>(Val: E) << Ty << CT; |
1020 | break; |
1021 | } |
1022 | } |
1023 | |
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 = ObjC().stripARCUnbridgedCast(e: 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(E&: 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(Ty: E->getType()) == VAK_Undefined) { |
1055 | // Turn this into a trap. |
1056 | CXXScopeSpec SS; |
1057 | SourceLocation TemplateKWLoc; |
1058 | UnqualifiedId Name; |
1059 | Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap" ), |
1060 | IdLoc: E->getBeginLoc()); |
1061 | ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name, |
1062 | /*HasTrailingLParen=*/true, |
1063 | /*IsAddressOfOperand=*/false); |
1064 | if (TrapFn.isInvalid()) |
1065 | return ExprError(); |
1066 | |
1067 | ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), |
1068 | ArgExprs: std::nullopt, RParenLoc: E->getEndLoc()); |
1069 | if (Call.isInvalid()) |
1070 | return ExprError(); |
1071 | |
1072 | ExprResult Comma = |
1073 | ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E); |
1074 | if (Comma.isInvalid()) |
1075 | return ExprError(); |
1076 | return Comma.get(); |
1077 | } |
1078 | |
1079 | if (!getLangOpts().CPlusPlus && |
1080 | RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(), |
1081 | DiagID: diag::err_call_incomplete_argument)) |
1082 | return ExprError(); |
1083 | |
1084 | return E; |
1085 | } |
1086 | |
1087 | /// Convert complex integers to complex floats and real integers to |
1088 | /// real floats as required for complex arithmetic. Helper function of |
1089 | /// UsualArithmeticConversions() |
1090 | /// |
1091 | /// \return false if the integer expression is an integer type and is |
1092 | /// successfully converted to the (complex) float type. |
1093 | static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, |
1094 | ExprResult &ComplexExpr, |
1095 | QualType IntTy, |
1096 | QualType ComplexTy, |
1097 | bool SkipCast) { |
1098 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; |
1099 | if (SkipCast) return false; |
1100 | if (IntTy->isIntegerType()) { |
1101 | QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); |
1102 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating); |
1103 | } else { |
1104 | assert(IntTy->isComplexIntegerType()); |
1105 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy, |
1106 | CK: CK_IntegralComplexToFloatingComplex); |
1107 | } |
1108 | return false; |
1109 | } |
1110 | |
1111 | // This handles complex/complex, complex/float, or float/complex. |
1112 | // When both operands are complex, the shorter operand is converted to the |
1113 | // type of the longer, and that is the type of the result. This corresponds |
1114 | // to what is done when combining two real floating-point operands. |
1115 | // The fun begins when size promotion occur across type domains. |
1116 | // From H&S 6.3.4: When one operand is complex and the other is a real |
1117 | // floating-point type, the less precise type is converted, within it's |
1118 | // real or complex domain, to the precision of the other type. For example, |
1119 | // when combining a "long double" with a "double _Complex", the |
1120 | // "double _Complex" is promoted to "long double _Complex". |
1121 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, |
1122 | QualType ShorterType, |
1123 | QualType LongerType, |
1124 | bool PromotePrecision) { |
1125 | bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType()); |
1126 | QualType Result = |
1127 | LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType); |
1128 | |
1129 | if (PromotePrecision) { |
1130 | if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) { |
1131 | Shorter = |
1132 | S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast); |
1133 | } else { |
1134 | if (LongerIsComplex) |
1135 | LongerType = LongerType->castAs<ComplexType>()->getElementType(); |
1136 | Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast); |
1137 | } |
1138 | } |
1139 | return Result; |
1140 | } |
1141 | |
1142 | /// Handle arithmetic conversion with complex types. Helper function of |
1143 | /// UsualArithmeticConversions() |
1144 | static QualType handleComplexConversion(Sema &S, ExprResult &LHS, |
1145 | ExprResult &RHS, QualType LHSType, |
1146 | QualType RHSType, bool IsCompAssign) { |
1147 | // Handle (complex) integer types. |
1148 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType, |
1149 | /*SkipCast=*/false)) |
1150 | return LHSType; |
1151 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType, |
1152 | /*SkipCast=*/IsCompAssign)) |
1153 | return RHSType; |
1154 | |
1155 | // Compute the rank of the two types, regardless of whether they are complex. |
1156 | int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
1157 | if (Order < 0) |
1158 | // Promote the precision of the LHS if not an assignment. |
1159 | return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType, |
1160 | /*PromotePrecision=*/!IsCompAssign); |
1161 | // Promote the precision of the RHS unless it is already the same as the LHS. |
1162 | return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType, |
1163 | /*PromotePrecision=*/Order > 0); |
1164 | } |
1165 | |
1166 | /// Handle arithmetic conversion from integer to float. Helper function |
1167 | /// of UsualArithmeticConversions() |
1168 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, |
1169 | ExprResult &IntExpr, |
1170 | QualType FloatTy, QualType IntTy, |
1171 | bool ConvertFloat, bool ConvertInt) { |
1172 | if (IntTy->isIntegerType()) { |
1173 | if (ConvertInt) |
1174 | // Convert intExpr to the lhs floating point type. |
1175 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy, |
1176 | CK: CK_IntegralToFloating); |
1177 | return FloatTy; |
1178 | } |
1179 | |
1180 | // Convert both sides to the appropriate complex float. |
1181 | assert(IntTy->isComplexIntegerType()); |
1182 | QualType result = S.Context.getComplexType(T: FloatTy); |
1183 | |
1184 | // _Complex int -> _Complex float |
1185 | if (ConvertInt) |
1186 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result, |
1187 | CK: CK_IntegralComplexToFloatingComplex); |
1188 | |
1189 | // float -> _Complex float |
1190 | if (ConvertFloat) |
1191 | FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result, |
1192 | CK: CK_FloatingRealToComplex); |
1193 | |
1194 | return result; |
1195 | } |
1196 | |
1197 | /// Handle arithmethic conversion with floating point types. Helper |
1198 | /// function of UsualArithmeticConversions() |
1199 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, |
1200 | ExprResult &RHS, QualType LHSType, |
1201 | QualType RHSType, bool IsCompAssign) { |
1202 | bool LHSFloat = LHSType->isRealFloatingType(); |
1203 | bool RHSFloat = RHSType->isRealFloatingType(); |
1204 | |
1205 | // N1169 4.1.4: If one of the operands has a floating type and the other |
1206 | // operand has a fixed-point type, the fixed-point operand |
1207 | // is converted to the floating type [...] |
1208 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { |
1209 | if (LHSFloat) |
1210 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating); |
1211 | else if (!IsCompAssign) |
1212 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating); |
1213 | return LHSFloat ? LHSType : RHSType; |
1214 | } |
1215 | |
1216 | // If we have two real floating types, convert the smaller operand |
1217 | // to the bigger result. |
1218 | if (LHSFloat && RHSFloat) { |
1219 | int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
1220 | if (order > 0) { |
1221 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast); |
1222 | return LHSType; |
1223 | } |
1224 | |
1225 | assert(order < 0 && "illegal float comparison" ); |
1226 | if (!IsCompAssign) |
1227 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast); |
1228 | return RHSType; |
1229 | } |
1230 | |
1231 | if (LHSFloat) { |
1232 | // Half FP has to be promoted to float unless it is natively supported |
1233 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) |
1234 | LHSType = S.Context.FloatTy; |
1235 | |
1236 | return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType, |
1237 | /*ConvertFloat=*/!IsCompAssign, |
1238 | /*ConvertInt=*/ true); |
1239 | } |
1240 | assert(RHSFloat); |
1241 | return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType, |
1242 | /*ConvertFloat=*/ true, |
1243 | /*ConvertInt=*/!IsCompAssign); |
1244 | } |
1245 | |
1246 | /// Diagnose attempts to convert between __float128, __ibm128 and |
1247 | /// long double if there is no support for such conversion. |
1248 | /// Helper function of UsualArithmeticConversions(). |
1249 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, |
1250 | QualType RHSType) { |
1251 | // No issue if either is not a floating point type. |
1252 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) |
1253 | return false; |
1254 | |
1255 | // No issue if both have the same 128-bit float semantics. |
1256 | auto *LHSComplex = LHSType->getAs<ComplexType>(); |
1257 | auto *RHSComplex = RHSType->getAs<ComplexType>(); |
1258 | |
1259 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; |
1260 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; |
1261 | |
1262 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem); |
1263 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem); |
1264 | |
1265 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || |
1266 | &RHSSem != &llvm::APFloat::IEEEquad()) && |
1267 | (&LHSSem != &llvm::APFloat::IEEEquad() || |
1268 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) |
1269 | return false; |
1270 | |
1271 | return true; |
1272 | } |
1273 | |
1274 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); |
1275 | |
1276 | namespace { |
1277 | /// These helper callbacks are placed in an anonymous namespace to |
1278 | /// permit their use as function template parameters. |
1279 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { |
1280 | return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast); |
1281 | } |
1282 | |
1283 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { |
1284 | return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType), |
1285 | CK: CK_IntegralComplexCast); |
1286 | } |
1287 | } |
1288 | |
1289 | /// Handle integer arithmetic conversions. Helper function of |
1290 | /// UsualArithmeticConversions() |
1291 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> |
1292 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, |
1293 | ExprResult &RHS, QualType LHSType, |
1294 | QualType RHSType, bool IsCompAssign) { |
1295 | // The rules for this case are in C99 6.3.1.8 |
1296 | int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType); |
1297 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); |
1298 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); |
1299 | if (LHSSigned == RHSSigned) { |
1300 | // Same signedness; use the higher-ranked type |
1301 | if (order >= 0) { |
1302 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1303 | return LHSType; |
1304 | } else if (!IsCompAssign) |
1305 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1306 | return RHSType; |
1307 | } else if (order != (LHSSigned ? 1 : -1)) { |
1308 | // The unsigned type has greater than or equal rank to the |
1309 | // signed type, so use the unsigned type |
1310 | if (RHSSigned) { |
1311 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1312 | return LHSType; |
1313 | } else if (!IsCompAssign) |
1314 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1315 | return RHSType; |
1316 | } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) { |
1317 | // The two types are different widths; if we are here, that |
1318 | // means the signed type is larger than the unsigned type, so |
1319 | // use the signed type. |
1320 | if (LHSSigned) { |
1321 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1322 | return LHSType; |
1323 | } else if (!IsCompAssign) |
1324 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1325 | return RHSType; |
1326 | } else { |
1327 | // The signed type is higher-ranked than the unsigned type, |
1328 | // but isn't actually any bigger (like unsigned int and long |
1329 | // on most 32-bit systems). Use the unsigned type corresponding |
1330 | // to the signed type. |
1331 | QualType result = |
1332 | S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType); |
1333 | RHS = (*doRHSCast)(S, RHS.get(), result); |
1334 | if (!IsCompAssign) |
1335 | LHS = (*doLHSCast)(S, LHS.get(), result); |
1336 | return result; |
1337 | } |
1338 | } |
1339 | |
1340 | /// Handle conversions with GCC complex int extension. Helper function |
1341 | /// of UsualArithmeticConversions() |
1342 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, |
1343 | ExprResult &RHS, QualType LHSType, |
1344 | QualType RHSType, |
1345 | bool IsCompAssign) { |
1346 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); |
1347 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); |
1348 | |
1349 | if (LHSComplexInt && RHSComplexInt) { |
1350 | QualType LHSEltType = LHSComplexInt->getElementType(); |
1351 | QualType RHSEltType = RHSComplexInt->getElementType(); |
1352 | QualType ScalarType = |
1353 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> |
1354 | (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign); |
1355 | |
1356 | return S.Context.getComplexType(T: ScalarType); |
1357 | } |
1358 | |
1359 | if (LHSComplexInt) { |
1360 | QualType LHSEltType = LHSComplexInt->getElementType(); |
1361 | QualType ScalarType = |
1362 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> |
1363 | (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign); |
1364 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
1365 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType, |
1366 | CK: CK_IntegralRealToComplex); |
1367 | |
1368 | return ComplexType; |
1369 | } |
1370 | |
1371 | assert(RHSComplexInt); |
1372 | |
1373 | QualType RHSEltType = RHSComplexInt->getElementType(); |
1374 | QualType ScalarType = |
1375 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> |
1376 | (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign); |
1377 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
1378 | |
1379 | if (!IsCompAssign) |
1380 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType, |
1381 | CK: CK_IntegralRealToComplex); |
1382 | return ComplexType; |
1383 | } |
1384 | |
1385 | /// Return the rank of a given fixed point or integer type. The value itself |
1386 | /// doesn't matter, but the values must be increasing with proper increasing |
1387 | /// rank as described in N1169 4.1.1. |
1388 | static unsigned GetFixedPointRank(QualType Ty) { |
1389 | const auto *BTy = Ty->getAs<BuiltinType>(); |
1390 | assert(BTy && "Expected a builtin type." ); |
1391 | |
1392 | switch (BTy->getKind()) { |
1393 | case BuiltinType::ShortFract: |
1394 | case BuiltinType::UShortFract: |
1395 | case BuiltinType::SatShortFract: |
1396 | case BuiltinType::SatUShortFract: |
1397 | return 1; |
1398 | case BuiltinType::Fract: |
1399 | case BuiltinType::UFract: |
1400 | case BuiltinType::SatFract: |
1401 | case BuiltinType::SatUFract: |
1402 | return 2; |
1403 | case BuiltinType::LongFract: |
1404 | case BuiltinType::ULongFract: |
1405 | case BuiltinType::SatLongFract: |
1406 | case BuiltinType::SatULongFract: |
1407 | return 3; |
1408 | case BuiltinType::ShortAccum: |
1409 | case BuiltinType::UShortAccum: |
1410 | case BuiltinType::SatShortAccum: |
1411 | case BuiltinType::SatUShortAccum: |
1412 | return 4; |
1413 | case BuiltinType::Accum: |
1414 | case BuiltinType::UAccum: |
1415 | case BuiltinType::SatAccum: |
1416 | case BuiltinType::SatUAccum: |
1417 | return 5; |
1418 | case BuiltinType::LongAccum: |
1419 | case BuiltinType::ULongAccum: |
1420 | case BuiltinType::SatLongAccum: |
1421 | case BuiltinType::SatULongAccum: |
1422 | return 6; |
1423 | default: |
1424 | if (BTy->isInteger()) |
1425 | return 0; |
1426 | llvm_unreachable("Unexpected fixed point or integer type" ); |
1427 | } |
1428 | } |
1429 | |
1430 | /// handleFixedPointConversion - Fixed point operations between fixed |
1431 | /// point types and integers or other fixed point types do not fall under |
1432 | /// usual arithmetic conversion since these conversions could result in loss |
1433 | /// of precsision (N1169 4.1.4). These operations should be calculated with |
1434 | /// the full precision of their result type (N1169 4.1.6.2.1). |
1435 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, |
1436 | QualType RHSTy) { |
1437 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && |
1438 | "Expected at least one of the operands to be a fixed point type" ); |
1439 | assert((LHSTy->isFixedPointOrIntegerType() || |
1440 | RHSTy->isFixedPointOrIntegerType()) && |
1441 | "Special fixed point arithmetic operation conversions are only " |
1442 | "applied to ints or other fixed point types" ); |
1443 | |
1444 | // If one operand has signed fixed-point type and the other operand has |
1445 | // unsigned fixed-point type, then the unsigned fixed-point operand is |
1446 | // converted to its corresponding signed fixed-point type and the resulting |
1447 | // type is the type of the converted operand. |
1448 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) |
1449 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy); |
1450 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) |
1451 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy); |
1452 | |
1453 | // The result type is the type with the highest rank, whereby a fixed-point |
1454 | // conversion rank is always greater than an integer conversion rank; if the |
1455 | // type of either of the operands is a saturating fixedpoint type, the result |
1456 | // type shall be the saturating fixed-point type corresponding to the type |
1457 | // with the highest rank; the resulting value is converted (taking into |
1458 | // account rounding and overflow) to the precision of the resulting type. |
1459 | // Same ranks between signed and unsigned types are resolved earlier, so both |
1460 | // types are either signed or both unsigned at this point. |
1461 | unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy); |
1462 | unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy); |
1463 | |
1464 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; |
1465 | |
1466 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) |
1467 | ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy); |
1468 | |
1469 | return ResultTy; |
1470 | } |
1471 | |
1472 | /// Check that the usual arithmetic conversions can be performed on this pair of |
1473 | /// expressions that might be of enumeration type. |
1474 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, |
1475 | SourceLocation Loc, |
1476 | Sema::ArithConvKind ACK) { |
1477 | // C++2a [expr.arith.conv]p1: |
1478 | // If one operand is of enumeration type and the other operand is of a |
1479 | // different enumeration type or a floating-point type, this behavior is |
1480 | // deprecated ([depr.arith.conv.enum]). |
1481 | // |
1482 | // Warn on this in all language modes. Produce a deprecation warning in C++20. |
1483 | // Eventually we will presumably reject these cases (in C++23 onwards?). |
1484 | QualType L = LHS->getEnumCoercedType(Ctx: S.Context), |
1485 | R = RHS->getEnumCoercedType(Ctx: S.Context); |
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, DiagID: S.getLangOpts().CPlusPlus26 |
1492 | ? diag::err_arith_conv_enum_float_cxx26 |
1493 | : S.getLangOpts().CPlusPlus20 |
1494 | ? diag::warn_arith_conv_enum_float_cxx20 |
1495 | : diag::warn_arith_conv_enum_float) |
1496 | << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum |
1497 | << L << R; |
1498 | } else if (!IsCompAssign && LEnum && REnum && |
1499 | !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) { |
1500 | unsigned DiagID; |
1501 | // In C++ 26, usual arithmetic conversions between 2 different enum types |
1502 | // are ill-formed. |
1503 | if (S.getLangOpts().CPlusPlus26) |
1504 | DiagID = diag::err_conv_mixed_enum_types_cxx26; |
1505 | else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || |
1506 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { |
1507 | // If either enumeration type is unnamed, it's less likely that the |
1508 | // user cares about this, but this situation is still deprecated in |
1509 | // C++2a. Use a different warning group. |
1510 | DiagID = S.getLangOpts().CPlusPlus20 |
1511 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 |
1512 | : diag::warn_arith_conv_mixed_anon_enum_types; |
1513 | } else if (ACK == Sema::ACK_Conditional) { |
1514 | // Conditional expressions are separated out because they have |
1515 | // historically had a different warning flag. |
1516 | DiagID = S.getLangOpts().CPlusPlus20 |
1517 | ? diag::warn_conditional_mixed_enum_types_cxx20 |
1518 | : diag::warn_conditional_mixed_enum_types; |
1519 | } else if (ACK == Sema::ACK_Comparison) { |
1520 | // Comparison expressions are separated out because they have |
1521 | // historically had a different warning flag. |
1522 | DiagID = S.getLangOpts().CPlusPlus20 |
1523 | ? diag::warn_comparison_mixed_enum_types_cxx20 |
1524 | : diag::warn_comparison_mixed_enum_types; |
1525 | } else { |
1526 | DiagID = S.getLangOpts().CPlusPlus20 |
1527 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 |
1528 | : diag::warn_arith_conv_mixed_enum_types; |
1529 | } |
1530 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() |
1531 | << (int)ACK << L << R; |
1532 | } |
1533 | } |
1534 | |
1535 | /// UsualArithmeticConversions - Performs various conversions that are common to |
1536 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
1537 | /// routine returns the first non-arithmetic type found. The client is |
1538 | /// responsible for emitting appropriate error diagnostics. |
1539 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
1540 | SourceLocation Loc, |
1541 | ArithConvKind ACK) { |
1542 | checkEnumArithmeticConversions(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK); |
1543 | |
1544 | if (ACK != ACK_CompAssign) { |
1545 | LHS = UsualUnaryConversions(E: LHS.get()); |
1546 | if (LHS.isInvalid()) |
1547 | return QualType(); |
1548 | } |
1549 | |
1550 | RHS = UsualUnaryConversions(E: RHS.get()); |
1551 | if (RHS.isInvalid()) |
1552 | return QualType(); |
1553 | |
1554 | // For conversion purposes, we ignore any qualifiers. |
1555 | // For example, "const float" and "float" are equivalent. |
1556 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
1557 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
1558 | |
1559 | // For conversion purposes, we ignore any atomic qualifier on the LHS. |
1560 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) |
1561 | LHSType = AtomicLHS->getValueType(); |
1562 | |
1563 | // If both types are identical, no conversion is needed. |
1564 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
1565 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
1566 | |
1567 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. |
1568 | // The caller can deal with this (e.g. pointer + int). |
1569 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) |
1570 | return QualType(); |
1571 | |
1572 | // Apply unary and bitfield promotions to the LHS's type. |
1573 | QualType LHSUnpromotedType = LHSType; |
1574 | if (Context.isPromotableIntegerType(T: LHSType)) |
1575 | LHSType = Context.getPromotedIntegerType(PromotableType: LHSType); |
1576 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get()); |
1577 | if (!LHSBitfieldPromoteTy.isNull()) |
1578 | LHSType = LHSBitfieldPromoteTy; |
1579 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) |
1580 | LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast); |
1581 | |
1582 | // If both types are identical, no conversion is needed. |
1583 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
1584 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
1585 | |
1586 | // At this point, we have two different arithmetic types. |
1587 | |
1588 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
1589 | // where such conversions currently can't be handled. |
1590 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
1591 | return QualType(); |
1592 | |
1593 | // Handle complex types first (C99 6.3.1.8p1). |
1594 | if (LHSType->isComplexType() || RHSType->isComplexType()) |
1595 | return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1596 | IsCompAssign: ACK == ACK_CompAssign); |
1597 | |
1598 | // Now handle "real" floating types (i.e. float, double, long double). |
1599 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
1600 | return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1601 | IsCompAssign: ACK == ACK_CompAssign); |
1602 | |
1603 | // Handle GCC complex int extension. |
1604 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) |
1605 | return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1606 | IsCompAssign: ACK == ACK_CompAssign); |
1607 | |
1608 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) |
1609 | return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType); |
1610 | |
1611 | // Finally, we have two differing integer types. |
1612 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
1613 | (S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ACK_CompAssign); |
1614 | } |
1615 | |
1616 | //===----------------------------------------------------------------------===// |
1617 | // Semantic Analysis for various Expression Types |
1618 | //===----------------------------------------------------------------------===// |
1619 | |
1620 | |
1621 | ExprResult Sema::ActOnGenericSelectionExpr( |
1622 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
1623 | bool PredicateIsExpr, void *ControllingExprOrType, |
1624 | ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) { |
1625 | unsigned NumAssocs = ArgTypes.size(); |
1626 | assert(NumAssocs == ArgExprs.size()); |
1627 | |
1628 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; |
1629 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1630 | if (ArgTypes[i]) |
1631 | (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]); |
1632 | else |
1633 | Types[i] = nullptr; |
1634 | } |
1635 | |
1636 | // If we have a controlling type, we need to convert it from a parsed type |
1637 | // into a semantic type and then pass that along. |
1638 | if (!PredicateIsExpr) { |
1639 | TypeSourceInfo *ControllingType; |
1640 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType), |
1641 | TInfo: &ControllingType); |
1642 | assert(ControllingType && "couldn't get the type out of the parser" ); |
1643 | ControllingExprOrType = ControllingType; |
1644 | } |
1645 | |
1646 | ExprResult ER = CreateGenericSelectionExpr( |
1647 | KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType, |
1648 | Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs); |
1649 | delete [] Types; |
1650 | return ER; |
1651 | } |
1652 | |
1653 | ExprResult Sema::CreateGenericSelectionExpr( |
1654 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
1655 | bool PredicateIsExpr, void *ControllingExprOrType, |
1656 | ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) { |
1657 | unsigned NumAssocs = Types.size(); |
1658 | assert(NumAssocs == Exprs.size()); |
1659 | assert(ControllingExprOrType && |
1660 | "Must have either a controlling expression or a controlling type" ); |
1661 | |
1662 | Expr *ControllingExpr = nullptr; |
1663 | TypeSourceInfo *ControllingType = nullptr; |
1664 | if (PredicateIsExpr) { |
1665 | // Decay and strip qualifiers for the controlling expression type, and |
1666 | // handle placeholder type replacement. See committee discussion from WG14 |
1667 | // DR423. |
1668 | EnterExpressionEvaluationContext Unevaluated( |
1669 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
1670 | ExprResult R = DefaultFunctionArrayLvalueConversion( |
1671 | E: reinterpret_cast<Expr *>(ControllingExprOrType)); |
1672 | if (R.isInvalid()) |
1673 | return ExprError(); |
1674 | ControllingExpr = R.get(); |
1675 | } else { |
1676 | // The extension form uses the type directly rather than converting it. |
1677 | ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType); |
1678 | if (!ControllingType) |
1679 | return ExprError(); |
1680 | } |
1681 | |
1682 | bool TypeErrorFound = false, |
1683 | IsResultDependent = ControllingExpr |
1684 | ? ControllingExpr->isTypeDependent() |
1685 | : ControllingType->getType()->isDependentType(), |
1686 | ContainsUnexpandedParameterPack = |
1687 | ControllingExpr |
1688 | ? ControllingExpr->containsUnexpandedParameterPack() |
1689 | : ControllingType->getType()->containsUnexpandedParameterPack(); |
1690 | |
1691 | // The controlling expression is an unevaluated operand, so side effects are |
1692 | // likely unintended. |
1693 | if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr && |
1694 | ControllingExpr->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) |
1695 | Diag(Loc: ControllingExpr->getExprLoc(), |
1696 | DiagID: diag::warn_side_effects_unevaluated_context); |
1697 | |
1698 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1699 | if (Exprs[i]->containsUnexpandedParameterPack()) |
1700 | ContainsUnexpandedParameterPack = true; |
1701 | |
1702 | if (Types[i]) { |
1703 | if (Types[i]->getType()->containsUnexpandedParameterPack()) |
1704 | ContainsUnexpandedParameterPack = true; |
1705 | |
1706 | if (Types[i]->getType()->isDependentType()) { |
1707 | IsResultDependent = true; |
1708 | } else { |
1709 | // We relax the restriction on use of incomplete types and non-object |
1710 | // types with the type-based extension of _Generic. Allowing incomplete |
1711 | // objects means those can be used as "tags" for a type-safe way to map |
1712 | // to a value. Similarly, matching on function types rather than |
1713 | // function pointer types can be useful. However, the restriction on VM |
1714 | // types makes sense to retain as there are open questions about how |
1715 | // the selection can be made at compile time. |
1716 | // |
1717 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a |
1718 | // complete object type other than a variably modified type." |
1719 | unsigned D = 0; |
1720 | if (ControllingExpr && Types[i]->getType()->isIncompleteType()) |
1721 | D = diag::err_assoc_type_incomplete; |
1722 | else if (ControllingExpr && !Types[i]->getType()->isObjectType()) |
1723 | D = diag::err_assoc_type_nonobject; |
1724 | else if (Types[i]->getType()->isVariablyModifiedType()) |
1725 | D = diag::err_assoc_type_variably_modified; |
1726 | else if (ControllingExpr) { |
1727 | // Because the controlling expression undergoes lvalue conversion, |
1728 | // array conversion, and function conversion, an association which is |
1729 | // of array type, function type, or is qualified can never be |
1730 | // reached. We will warn about this so users are less surprised by |
1731 | // the unreachable association. However, we don't have to handle |
1732 | // function types; that's not an object type, so it's handled above. |
1733 | // |
1734 | // The logic is somewhat different for C++ because C++ has different |
1735 | // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, |
1736 | // If T is a non-class type, the type of the prvalue is the cv- |
1737 | // unqualified version of T. Otherwise, the type of the prvalue is T. |
1738 | // The result of these rules is that all qualified types in an |
1739 | // association in C are unreachable, and in C++, only qualified non- |
1740 | // class types are unreachable. |
1741 | // |
1742 | // NB: this does not apply when the first operand is a type rather |
1743 | // than an expression, because the type form does not undergo |
1744 | // conversion. |
1745 | unsigned Reason = 0; |
1746 | QualType QT = Types[i]->getType(); |
1747 | if (QT->isArrayType()) |
1748 | Reason = 1; |
1749 | else if (QT.hasQualifiers() && |
1750 | (!LangOpts.CPlusPlus || !QT->isRecordType())) |
1751 | Reason = 2; |
1752 | |
1753 | if (Reason) |
1754 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), |
1755 | DiagID: diag::warn_unreachable_association) |
1756 | << QT << (Reason - 1); |
1757 | } |
1758 | |
1759 | if (D != 0) { |
1760 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), DiagID: D) |
1761 | << Types[i]->getTypeLoc().getSourceRange() |
1762 | << Types[i]->getType(); |
1763 | TypeErrorFound = true; |
1764 | } |
1765 | |
1766 | // C11 6.5.1.1p2 "No two generic associations in the same generic |
1767 | // selection shall specify compatible types." |
1768 | for (unsigned j = i+1; j < NumAssocs; ++j) |
1769 | if (Types[j] && !Types[j]->getType()->isDependentType() && |
1770 | Context.typesAreCompatible(T1: Types[i]->getType(), |
1771 | T2: Types[j]->getType())) { |
1772 | Diag(Loc: Types[j]->getTypeLoc().getBeginLoc(), |
1773 | DiagID: diag::err_assoc_compatible_types) |
1774 | << Types[j]->getTypeLoc().getSourceRange() |
1775 | << Types[j]->getType() |
1776 | << Types[i]->getType(); |
1777 | Diag(Loc: Types[i]->getTypeLoc().getBeginLoc(), |
1778 | DiagID: diag::note_compat_assoc) |
1779 | << Types[i]->getTypeLoc().getSourceRange() |
1780 | << Types[i]->getType(); |
1781 | TypeErrorFound = true; |
1782 | } |
1783 | } |
1784 | } |
1785 | } |
1786 | if (TypeErrorFound) |
1787 | return ExprError(); |
1788 | |
1789 | // If we determined that the generic selection is result-dependent, don't |
1790 | // try to compute the result expression. |
1791 | if (IsResultDependent) { |
1792 | if (ControllingExpr) |
1793 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr, |
1794 | AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1795 | ContainsUnexpandedParameterPack); |
1796 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, |
1797 | AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1798 | ContainsUnexpandedParameterPack); |
1799 | } |
1800 | |
1801 | SmallVector<unsigned, 1> CompatIndices; |
1802 | unsigned DefaultIndex = -1U; |
1803 | // Look at the canonical type of the controlling expression in case it was a |
1804 | // deduced type like __auto_type. However, when issuing diagnostics, use the |
1805 | // type the user wrote in source rather than the canonical one. |
1806 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1807 | if (!Types[i]) |
1808 | DefaultIndex = i; |
1809 | else if (ControllingExpr && |
1810 | Context.typesAreCompatible( |
1811 | T1: ControllingExpr->getType().getCanonicalType(), |
1812 | T2: Types[i]->getType())) |
1813 | CompatIndices.push_back(Elt: i); |
1814 | else if (ControllingType && |
1815 | Context.typesAreCompatible( |
1816 | T1: ControllingType->getType().getCanonicalType(), |
1817 | T2: Types[i]->getType())) |
1818 | CompatIndices.push_back(Elt: i); |
1819 | } |
1820 | |
1821 | auto GetControllingRangeAndType = [](Expr *ControllingExpr, |
1822 | TypeSourceInfo *ControllingType) { |
1823 | // We strip parens here because the controlling expression is typically |
1824 | // parenthesized in macro definitions. |
1825 | if (ControllingExpr) |
1826 | ControllingExpr = ControllingExpr->IgnoreParens(); |
1827 | |
1828 | SourceRange SR = ControllingExpr |
1829 | ? ControllingExpr->getSourceRange() |
1830 | : ControllingType->getTypeLoc().getSourceRange(); |
1831 | QualType QT = ControllingExpr ? ControllingExpr->getType() |
1832 | : ControllingType->getType(); |
1833 | |
1834 | return std::make_pair(x&: SR, y&: QT); |
1835 | }; |
1836 | |
1837 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have |
1838 | // type compatible with at most one of the types named in its generic |
1839 | // association list." |
1840 | if (CompatIndices.size() > 1) { |
1841 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
1842 | SourceRange SR = P.first; |
1843 | Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_multi_match) |
1844 | << SR << P.second << (unsigned)CompatIndices.size(); |
1845 | for (unsigned I : CompatIndices) { |
1846 | Diag(Loc: Types[I]->getTypeLoc().getBeginLoc(), |
1847 | DiagID: diag::note_compat_assoc) |
1848 | << Types[I]->getTypeLoc().getSourceRange() |
1849 | << Types[I]->getType(); |
1850 | } |
1851 | return ExprError(); |
1852 | } |
1853 | |
1854 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, |
1855 | // its controlling expression shall have type compatible with exactly one of |
1856 | // the types named in its generic association list." |
1857 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { |
1858 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
1859 | SourceRange SR = P.first; |
1860 | Diag(Loc: SR.getBegin(), DiagID: diag::err_generic_sel_no_match) << SR << P.second; |
1861 | return ExprError(); |
1862 | } |
1863 | |
1864 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a |
1865 | // type name that is compatible with the type of the controlling expression, |
1866 | // then the result expression of the generic selection is the expression |
1867 | // in that generic association. Otherwise, the result expression of the |
1868 | // generic selection is the expression in the default generic association." |
1869 | unsigned ResultIndex = |
1870 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; |
1871 | |
1872 | if (ControllingExpr) { |
1873 | return GenericSelectionExpr::Create( |
1874 | Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1875 | ContainsUnexpandedParameterPack, ResultIndex); |
1876 | } |
1877 | return GenericSelectionExpr::Create( |
1878 | Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1879 | ContainsUnexpandedParameterPack, ResultIndex); |
1880 | } |
1881 | |
1882 | static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) { |
1883 | switch (Kind) { |
1884 | default: |
1885 | llvm_unreachable("unexpected TokenKind" ); |
1886 | case tok::kw___func__: |
1887 | return PredefinedIdentKind::Func; // [C99 6.4.2.2] |
1888 | case tok::kw___FUNCTION__: |
1889 | return PredefinedIdentKind::Function; |
1890 | case tok::kw___FUNCDNAME__: |
1891 | return PredefinedIdentKind::FuncDName; // [MS] |
1892 | case tok::kw___FUNCSIG__: |
1893 | return PredefinedIdentKind::FuncSig; // [MS] |
1894 | case tok::kw_L__FUNCTION__: |
1895 | return PredefinedIdentKind::LFunction; // [MS] |
1896 | case tok::kw_L__FUNCSIG__: |
1897 | return PredefinedIdentKind::LFuncSig; // [MS] |
1898 | case tok::kw___PRETTY_FUNCTION__: |
1899 | return PredefinedIdentKind::PrettyFunction; // [GNU] |
1900 | } |
1901 | } |
1902 | |
1903 | /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used |
1904 | /// to determine the value of a PredefinedExpr. This can be either a |
1905 | /// block, lambda, captured statement, function, otherwise a nullptr. |
1906 | static Decl *getPredefinedExprDecl(DeclContext *DC) { |
1907 | while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) |
1908 | DC = DC->getParent(); |
1909 | return cast_or_null<Decl>(Val: DC); |
1910 | } |
1911 | |
1912 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the |
1913 | /// location of the token and the offset of the ud-suffix within it. |
1914 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, |
1915 | unsigned Offset) { |
1916 | return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(), |
1917 | LangOpts: S.getLangOpts()); |
1918 | } |
1919 | |
1920 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up |
1921 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. |
1922 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, |
1923 | IdentifierInfo *UDSuffix, |
1924 | SourceLocation UDSuffixLoc, |
1925 | ArrayRef<Expr*> Args, |
1926 | SourceLocation LitEndLoc) { |
1927 | assert(Args.size() <= 2 && "too many arguments for literal operator" ); |
1928 | |
1929 | QualType ArgTy[2]; |
1930 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { |
1931 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); |
1932 | if (ArgTy[ArgIdx]->isArrayType()) |
1933 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]); |
1934 | } |
1935 | |
1936 | DeclarationName OpName = |
1937 | S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
1938 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
1939 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
1940 | |
1941 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); |
1942 | if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()), |
1943 | /*AllowRaw*/ false, /*AllowTemplate*/ false, |
1944 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
1945 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) |
1946 | return ExprError(); |
1947 | |
1948 | return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc); |
1949 | } |
1950 | |
1951 | ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) { |
1952 | // StringToks needs backing storage as it doesn't hold array elements itself |
1953 | std::vector<Token> ExpandedToks; |
1954 | if (getLangOpts().MicrosoftExt) |
1955 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
1956 | |
1957 | StringLiteralParser Literal(StringToks, PP, |
1958 | StringLiteralEvalMethod::Unevaluated); |
1959 | if (Literal.hadError) |
1960 | return ExprError(); |
1961 | |
1962 | SmallVector<SourceLocation, 4> StringTokLocs; |
1963 | for (const Token &Tok : StringToks) |
1964 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
1965 | |
1966 | StringLiteral *Lit = StringLiteral::Create( |
1967 | Ctx: Context, Str: Literal.GetString(), Kind: StringLiteralKind::Unevaluated, Pascal: false, Ty: {}, |
1968 | Loc: &StringTokLocs[0], NumConcatenated: StringTokLocs.size()); |
1969 | |
1970 | if (!Literal.getUDSuffix().empty()) { |
1971 | SourceLocation UDSuffixLoc = |
1972 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
1973 | Offset: Literal.getUDSuffixOffset()); |
1974 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl)); |
1975 | } |
1976 | |
1977 | return Lit; |
1978 | } |
1979 | |
1980 | std::vector<Token> |
1981 | Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) { |
1982 | // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function |
1983 | // local macros that expand to string literals that may be concatenated. |
1984 | // These macros are expanded here (in Sema), because StringLiteralParser |
1985 | // (in Lex) doesn't know the enclosing function (because it hasn't been |
1986 | // parsed yet). |
1987 | assert(getLangOpts().MicrosoftExt); |
1988 | |
1989 | // Note: Although function local macros are defined only inside functions, |
1990 | // we ensure a valid `CurrentDecl` even outside of a function. This allows |
1991 | // expansion of macros into empty string literals without additional checks. |
1992 | Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext); |
1993 | if (!CurrentDecl) |
1994 | CurrentDecl = Context.getTranslationUnitDecl(); |
1995 | |
1996 | std::vector<Token> ExpandedToks; |
1997 | ExpandedToks.reserve(n: Toks.size()); |
1998 | for (const Token &Tok : Toks) { |
1999 | if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) { |
2000 | assert(tok::isStringLiteral(Tok.getKind())); |
2001 | ExpandedToks.emplace_back(args: Tok); |
2002 | continue; |
2003 | } |
2004 | if (isa<TranslationUnitDecl>(Val: CurrentDecl)) |
2005 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_predef_outside_function); |
2006 | // Stringify predefined expression |
2007 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_string_literal_from_predefined) |
2008 | << Tok.getKind(); |
2009 | SmallString<64> Str; |
2010 | llvm::raw_svector_ostream OS(Str); |
2011 | Token &Exp = ExpandedToks.emplace_back(); |
2012 | Exp.startToken(); |
2013 | if (Tok.getKind() == tok::kw_L__FUNCTION__ || |
2014 | Tok.getKind() == tok::kw_L__FUNCSIG__) { |
2015 | OS << 'L'; |
2016 | Exp.setKind(tok::wide_string_literal); |
2017 | } else { |
2018 | Exp.setKind(tok::string_literal); |
2019 | } |
2020 | OS << '"' |
2021 | << Lexer::Stringify(Str: PredefinedExpr::ComputeName( |
2022 | IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl)) |
2023 | << '"'; |
2024 | PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc()); |
2025 | } |
2026 | return ExpandedToks; |
2027 | } |
2028 | |
2029 | ExprResult |
2030 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { |
2031 | assert(!StringToks.empty() && "Must have at least one string!" ); |
2032 | |
2033 | // StringToks needs backing storage as it doesn't hold array elements itself |
2034 | std::vector<Token> ExpandedToks; |
2035 | if (getLangOpts().MicrosoftExt) |
2036 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
2037 | |
2038 | StringLiteralParser Literal(StringToks, PP); |
2039 | if (Literal.hadError) |
2040 | return ExprError(); |
2041 | |
2042 | SmallVector<SourceLocation, 4> StringTokLocs; |
2043 | for (const Token &Tok : StringToks) |
2044 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
2045 | |
2046 | QualType CharTy = Context.CharTy; |
2047 | StringLiteralKind Kind = StringLiteralKind::Ordinary; |
2048 | if (Literal.isWide()) { |
2049 | CharTy = Context.getWideCharType(); |
2050 | Kind = StringLiteralKind::Wide; |
2051 | } else if (Literal.isUTF8()) { |
2052 | if (getLangOpts().Char8) |
2053 | CharTy = Context.Char8Ty; |
2054 | else if (getLangOpts().C23) |
2055 | CharTy = Context.UnsignedCharTy; |
2056 | Kind = StringLiteralKind::UTF8; |
2057 | } else if (Literal.isUTF16()) { |
2058 | CharTy = Context.Char16Ty; |
2059 | Kind = StringLiteralKind::UTF16; |
2060 | } else if (Literal.isUTF32()) { |
2061 | CharTy = Context.Char32Ty; |
2062 | Kind = StringLiteralKind::UTF32; |
2063 | } else if (Literal.isPascal()) { |
2064 | CharTy = Context.UnsignedCharTy; |
2065 | } |
2066 | |
2067 | // Warn on u8 string literals before C++20 and C23, whose type |
2068 | // was an array of char before but becomes an array of char8_t. |
2069 | // In C++20, it cannot be used where a pointer to char is expected. |
2070 | // In C23, it might have an unexpected value if char was signed. |
2071 | if (Kind == StringLiteralKind::UTF8 && |
2072 | (getLangOpts().CPlusPlus |
2073 | ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8 |
2074 | : !getLangOpts().C23)) { |
2075 | Diag(Loc: StringTokLocs.front(), DiagID: getLangOpts().CPlusPlus |
2076 | ? diag::warn_cxx20_compat_utf8_string |
2077 | : diag::warn_c23_compat_utf8_string); |
2078 | |
2079 | // Create removals for all 'u8' prefixes in the string literal(s). This |
2080 | // ensures C++20/C23 compatibility (but may change the program behavior when |
2081 | // built by non-Clang compilers for which the execution character set is |
2082 | // not always UTF-8). |
2083 | auto RemovalDiag = PDiag(DiagID: diag::note_cxx20_c23_compat_utf8_string_remove_u8); |
2084 | SourceLocation RemovalDiagLoc; |
2085 | for (const Token &Tok : StringToks) { |
2086 | if (Tok.getKind() == tok::utf8_string_literal) { |
2087 | if (RemovalDiagLoc.isInvalid()) |
2088 | RemovalDiagLoc = Tok.getLocation(); |
2089 | RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange( |
2090 | B: Tok.getLocation(), |
2091 | E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2, |
2092 | SM: getSourceManager(), LangOpts: getLangOpts()))); |
2093 | } |
2094 | } |
2095 | Diag(Loc: RemovalDiagLoc, PD: RemovalDiag); |
2096 | } |
2097 | |
2098 | QualType StrTy = |
2099 | Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars()); |
2100 | |
2101 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! |
2102 | StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(), |
2103 | Kind, Pascal: Literal.Pascal, Ty: StrTy, |
2104 | Loc: &StringTokLocs[0], |
2105 | NumConcatenated: StringTokLocs.size()); |
2106 | if (Literal.getUDSuffix().empty()) |
2107 | return Lit; |
2108 | |
2109 | // We're building a user-defined literal. |
2110 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
2111 | SourceLocation UDSuffixLoc = |
2112 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
2113 | Offset: Literal.getUDSuffixOffset()); |
2114 | |
2115 | // Make sure we're allowed user-defined literals here. |
2116 | if (!UDLScope) |
2117 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_string_udl)); |
2118 | |
2119 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form |
2120 | // operator "" X (str, len) |
2121 | QualType SizeType = Context.getSizeType(); |
2122 | |
2123 | DeclarationName OpName = |
2124 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
2125 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
2126 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
2127 | |
2128 | QualType ArgTy[] = { |
2129 | Context.getArrayDecayedType(T: StrTy), SizeType |
2130 | }; |
2131 | |
2132 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
2133 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy, |
2134 | /*AllowRaw*/ false, /*AllowTemplate*/ true, |
2135 | /*AllowStringTemplatePack*/ AllowStringTemplate: true, |
2136 | /*DiagnoseMissing*/ true, StringLit: Lit)) { |
2137 | |
2138 | case LOLR_Cooked: { |
2139 | llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars()); |
2140 | IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType, |
2141 | l: StringTokLocs[0]); |
2142 | Expr *Args[] = { Lit, LenArg }; |
2143 | |
2144 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc: StringTokLocs.back()); |
2145 | } |
2146 | |
2147 | case LOLR_Template: { |
2148 | TemplateArgumentListInfo ExplicitArgs; |
2149 | TemplateArgument Arg(Lit); |
2150 | TemplateArgumentLocInfo ArgInfo(Lit); |
2151 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
2152 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt, |
2153 | LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs); |
2154 | } |
2155 | |
2156 | case LOLR_StringTemplatePack: { |
2157 | TemplateArgumentListInfo ExplicitArgs; |
2158 | |
2159 | unsigned CharBits = Context.getIntWidth(T: CharTy); |
2160 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); |
2161 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
2162 | |
2163 | TemplateArgument TypeArg(CharTy); |
2164 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy)); |
2165 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo)); |
2166 | |
2167 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { |
2168 | Value = Lit->getCodeUnit(i: I); |
2169 | TemplateArgument Arg(Context, Value, CharTy); |
2170 | TemplateArgumentLocInfo ArgInfo; |
2171 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
2172 | } |
2173 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt, |
2174 | LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs); |
2175 | } |
2176 | case LOLR_Raw: |
2177 | case LOLR_ErrorNoDiagnostic: |
2178 | llvm_unreachable("unexpected literal operator lookup result" ); |
2179 | case LOLR_Error: |
2180 | return ExprError(); |
2181 | } |
2182 | llvm_unreachable("unexpected literal operator lookup result" ); |
2183 | } |
2184 | |
2185 | DeclRefExpr * |
2186 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2187 | SourceLocation Loc, |
2188 | const CXXScopeSpec *SS) { |
2189 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); |
2190 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); |
2191 | } |
2192 | |
2193 | DeclRefExpr * |
2194 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2195 | const DeclarationNameInfo &NameInfo, |
2196 | const CXXScopeSpec *SS, NamedDecl *FoundD, |
2197 | SourceLocation TemplateKWLoc, |
2198 | const TemplateArgumentListInfo *TemplateArgs) { |
2199 | NestedNameSpecifierLoc NNS = |
2200 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); |
2201 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, |
2202 | TemplateArgs); |
2203 | } |
2204 | |
2205 | // CUDA/HIP: Check whether a captured reference variable is referencing a |
2206 | // host variable in a device or host device lambda. |
2207 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, |
2208 | VarDecl *VD) { |
2209 | if (!S.getLangOpts().CUDA || !VD->hasInit()) |
2210 | return false; |
2211 | assert(VD->getType()->isReferenceType()); |
2212 | |
2213 | // Check whether the reference variable is referencing a host variable. |
2214 | auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit()); |
2215 | if (!DRE) |
2216 | return false; |
2217 | auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
2218 | if (!Referee || !Referee->hasGlobalStorage() || |
2219 | Referee->hasAttr<CUDADeviceAttr>()) |
2220 | return false; |
2221 | |
2222 | // Check whether the current function is a device or host device lambda. |
2223 | // Check whether the reference variable is a capture by getDeclContext() |
2224 | // since refersToEnclosingVariableOrCapture() is not ready at this point. |
2225 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext); |
2226 | if (MD && MD->getParent()->isLambda() && |
2227 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && |
2228 | VD->getDeclContext() != MD) |
2229 | return true; |
2230 | |
2231 | return false; |
2232 | } |
2233 | |
2234 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { |
2235 | // A declaration named in an unevaluated operand never constitutes an odr-use. |
2236 | if (isUnevaluatedContext()) |
2237 | return NOUR_Unevaluated; |
2238 | |
2239 | // C++2a [basic.def.odr]p4: |
2240 | // A variable x whose name appears as a potentially-evaluated expression e |
2241 | // is odr-used by e unless [...] x is a reference that is usable in |
2242 | // constant expressions. |
2243 | // CUDA/HIP: |
2244 | // If a reference variable referencing a host variable is captured in a |
2245 | // device or host device lambda, the value of the referee must be copied |
2246 | // to the capture and the reference variable must be treated as odr-use |
2247 | // since the value of the referee is not known at compile time and must |
2248 | // be loaded from the captured. |
2249 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
2250 | if (VD->getType()->isReferenceType() && |
2251 | !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) && |
2252 | !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) && |
2253 | VD->isUsableInConstantExpressions(C: Context)) |
2254 | return NOUR_Constant; |
2255 | } |
2256 | |
2257 | // All remaining non-variable cases constitute an odr-use. For variables, we |
2258 | // need to wait and see how the expression is used. |
2259 | return NOUR_None; |
2260 | } |
2261 | |
2262 | DeclRefExpr * |
2263 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2264 | const DeclarationNameInfo &NameInfo, |
2265 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, |
2266 | SourceLocation TemplateKWLoc, |
2267 | const TemplateArgumentListInfo *TemplateArgs) { |
2268 | bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) && |
2269 | NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc()); |
2270 | |
2271 | DeclRefExpr *E = DeclRefExpr::Create( |
2272 | Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty, |
2273 | VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D)); |
2274 | MarkDeclRefReferenced(E); |
2275 | |
2276 | // C++ [except.spec]p17: |
2277 | // An exception-specification is considered to be needed when: |
2278 | // - in an expression, the function is the unique lookup result or |
2279 | // the selected member of a set of overloaded functions. |
2280 | // |
2281 | // We delay doing this until after we've built the function reference and |
2282 | // marked it as used so that: |
2283 | // a) if the function is defaulted, we get errors from defining it before / |
2284 | // instead of errors from computing its exception specification, and |
2285 | // b) if the function is a defaulted comparison, we can use the body we |
2286 | // build when defining it as input to the exception specification |
2287 | // computation rather than computing a new body. |
2288 | if (const auto *FPT = Ty->getAs<FunctionProtoType>()) { |
2289 | if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) { |
2290 | if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT)) |
2291 | E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers())); |
2292 | } |
2293 | } |
2294 | |
2295 | if (getLangOpts().ObjCWeak && isa<VarDecl>(Val: D) && |
2296 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && |
2297 | !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: E->getBeginLoc())) |
2298 | getCurFunction()->recordUseOfWeak(E); |
2299 | |
2300 | const auto *FD = dyn_cast<FieldDecl>(Val: D); |
2301 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D)) |
2302 | FD = IFD->getAnonField(); |
2303 | if (FD) { |
2304 | UnusedPrivateFields.remove(X: FD); |
2305 | // Just in case we're building an illegal pointer-to-member. |
2306 | if (FD->isBitField()) |
2307 | E->setObjectKind(OK_BitField); |
2308 | } |
2309 | |
2310 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier |
2311 | // designates a bit-field. |
2312 | if (const auto *BD = dyn_cast<BindingDecl>(Val: D)) |
2313 | if (const auto *BE = BD->getBinding()) |
2314 | E->setObjectKind(BE->getObjectKind()); |
2315 | |
2316 | return E; |
2317 | } |
2318 | |
2319 | void |
2320 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, |
2321 | TemplateArgumentListInfo &Buffer, |
2322 | DeclarationNameInfo &NameInfo, |
2323 | const TemplateArgumentListInfo *&TemplateArgs) { |
2324 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { |
2325 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); |
2326 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); |
2327 | |
2328 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), |
2329 | Id.TemplateId->NumArgs); |
2330 | translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer); |
2331 | |
2332 | TemplateName TName = Id.TemplateId->Template.get(); |
2333 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; |
2334 | NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc); |
2335 | TemplateArgs = &Buffer; |
2336 | } else { |
2337 | NameInfo = GetNameFromUnqualifiedId(Name: Id); |
2338 | TemplateArgs = nullptr; |
2339 | } |
2340 | } |
2341 | |
2342 | static void emitEmptyLookupTypoDiagnostic( |
2343 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, |
2344 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, |
2345 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { |
2346 | DeclContext *Ctx = |
2347 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, EnteringContext: false); |
2348 | if (!TC) { |
2349 | // Emit a special diagnostic for failed member lookups. |
2350 | // FIXME: computing the declaration context might fail here (?) |
2351 | if (Ctx) |
2352 | SemaRef.Diag(Loc: TypoLoc, DiagID: diag::err_no_member) << Typo << Ctx |
2353 | << SS.getRange(); |
2354 | else |
2355 | SemaRef.Diag(Loc: TypoLoc, DiagID: DiagnosticID) << Typo; |
2356 | return; |
2357 | } |
2358 | |
2359 | std::string CorrectedStr = TC.getAsString(LO: SemaRef.getLangOpts()); |
2360 | bool DroppedSpecifier = |
2361 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; |
2362 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() |
2363 | ? diag::note_implicit_param_decl |
2364 | : diag::note_previous_decl; |
2365 | if (!Ctx) |
2366 | SemaRef.diagnoseTypo(Correction: TC, TypoDiag: SemaRef.PDiag(DiagID: DiagnosticSuggestID) << Typo, |
2367 | PrevNote: SemaRef.PDiag(DiagID: NoteID)); |
2368 | else |
2369 | SemaRef.diagnoseTypo(Correction: TC, TypoDiag: SemaRef.PDiag(DiagID: diag::err_no_member_suggest) |
2370 | << Typo << Ctx << DroppedSpecifier |
2371 | << SS.getRange(), |
2372 | PrevNote: SemaRef.PDiag(DiagID: NoteID)); |
2373 | } |
2374 | |
2375 | bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) { |
2376 | // During a default argument instantiation the CurContext points |
2377 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a |
2378 | // function parameter list, hence add an explicit check. |
2379 | bool isDefaultArgument = |
2380 | !CodeSynthesisContexts.empty() && |
2381 | CodeSynthesisContexts.back().Kind == |
2382 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; |
2383 | const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext); |
2384 | bool isInstance = CurMethod && CurMethod->isInstance() && |
2385 | R.getNamingClass() == CurMethod->getParent() && |
2386 | !isDefaultArgument; |
2387 | |
2388 | // There are two ways we can find a class-scope declaration during template |
2389 | // instantiation that we did not find in the template definition: if it is a |
2390 | // member of a dependent base class, or if it is declared after the point of |
2391 | // use in the same class. Distinguish these by comparing the class in which |
2392 | // the member was found to the naming class of the lookup. |
2393 | unsigned DiagID = diag::err_found_in_dependent_base; |
2394 | unsigned NoteID = diag::note_member_declared_at; |
2395 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(DC: R.getNamingClass())) { |
2396 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class |
2397 | : diag::err_found_later_in_class; |
2398 | } else if (getLangOpts().MSVCCompat) { |
2399 | DiagID = diag::ext_found_in_dependent_base; |
2400 | NoteID = diag::note_dependent_member_use; |
2401 | } |
2402 | |
2403 | if (isInstance) { |
2404 | // Give a code modification hint to insert 'this->'. |
2405 | Diag(Loc: R.getNameLoc(), DiagID) |
2406 | << R.getLookupName() |
2407 | << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->" ); |
2408 | CheckCXXThisCapture(Loc: R.getNameLoc()); |
2409 | } else { |
2410 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming |
2411 | // they're not shadowed). |
2412 | Diag(Loc: R.getNameLoc(), DiagID) << R.getLookupName(); |
2413 | } |
2414 | |
2415 | for (const NamedDecl *D : R) |
2416 | Diag(Loc: D->getLocation(), DiagID: NoteID); |
2417 | |
2418 | // Return true if we are inside a default argument instantiation |
2419 | // and the found name refers to an instance member function, otherwise |
2420 | // the caller will try to create an implicit member call and this is wrong |
2421 | // for default arguments. |
2422 | // |
2423 | // FIXME: Is this special case necessary? We could allow the caller to |
2424 | // diagnose this. |
2425 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { |
2426 | Diag(Loc: R.getNameLoc(), DiagID: diag::err_member_call_without_object) << 0; |
2427 | return true; |
2428 | } |
2429 | |
2430 | // Tell the callee to try to recover. |
2431 | return false; |
2432 | } |
2433 | |
2434 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
2435 | CorrectionCandidateCallback &CCC, |
2436 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2437 | ArrayRef<Expr *> Args, DeclContext *LookupCtx, |
2438 | TypoExpr **Out) { |
2439 | DeclarationName Name = R.getLookupName(); |
2440 | |
2441 | unsigned diagnostic = diag::err_undeclared_var_use; |
2442 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; |
2443 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || |
2444 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || |
2445 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
2446 | diagnostic = diag::err_undeclared_use; |
2447 | diagnostic_suggest = diag::err_undeclared_use_suggest; |
2448 | } |
2449 | |
2450 | // If the original lookup was an unqualified lookup, fake an |
2451 | // unqualified lookup. This is useful when (for example) the |
2452 | // original lookup would not have found something because it was a |
2453 | // dependent name. |
2454 | DeclContext *DC = |
2455 | LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr); |
2456 | while (DC) { |
2457 | if (isa<CXXRecordDecl>(Val: DC)) { |
2458 | LookupQualifiedName(R, LookupCtx: DC); |
2459 | |
2460 | if (!R.empty()) { |
2461 | // Don't give errors about ambiguities in this lookup. |
2462 | R.suppressDiagnostics(); |
2463 | |
2464 | // If there's a best viable function among the results, only mention |
2465 | // that one in the notes. |
2466 | OverloadCandidateSet Candidates(R.getNameLoc(), |
2467 | OverloadCandidateSet::CSK_Normal); |
2468 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates); |
2469 | OverloadCandidateSet::iterator Best; |
2470 | if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) == |
2471 | OR_Success) { |
2472 | R.clear(); |
2473 | R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess()); |
2474 | R.resolveKind(); |
2475 | } |
2476 | |
2477 | return DiagnoseDependentMemberLookup(R); |
2478 | } |
2479 | |
2480 | R.clear(); |
2481 | } |
2482 | |
2483 | DC = DC->getLookupParent(); |
2484 | } |
2485 | |
2486 | // We didn't find anything, so try to correct for a typo. |
2487 | TypoCorrection Corrected; |
2488 | if (S && Out) { |
2489 | SourceLocation TypoLoc = R.getNameLoc(); |
2490 | assert(!ExplicitTemplateArgs && |
2491 | "Diagnosing an empty lookup with explicit template args!" ); |
2492 | *Out = CorrectTypoDelayed( |
2493 | Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC, |
2494 | TDG: [=](const TypoCorrection &TC) { |
2495 | emitEmptyLookupTypoDiagnostic(TC, SemaRef&: *this, SS, Typo: Name, TypoLoc, Args, |
2496 | DiagnosticID: diagnostic, DiagnosticSuggestID: diagnostic_suggest); |
2497 | }, |
2498 | TRC: nullptr, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx); |
2499 | if (*Out) |
2500 | return true; |
2501 | } else if (S && (Corrected = |
2502 | CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, |
2503 | SS: &SS, CCC, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx))) { |
2504 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
2505 | bool DroppedSpecifier = |
2506 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; |
2507 | R.setLookupName(Corrected.getCorrection()); |
2508 | |
2509 | bool AcceptableWithRecovery = false; |
2510 | bool AcceptableWithoutRecovery = false; |
2511 | NamedDecl *ND = Corrected.getFoundDecl(); |
2512 | if (ND) { |
2513 | if (Corrected.isOverloaded()) { |
2514 | OverloadCandidateSet OCS(R.getNameLoc(), |
2515 | OverloadCandidateSet::CSK_Normal); |
2516 | OverloadCandidateSet::iterator Best; |
2517 | for (NamedDecl *CD : Corrected) { |
2518 | if (FunctionTemplateDecl *FTD = |
2519 | dyn_cast<FunctionTemplateDecl>(Val: CD)) |
2520 | AddTemplateOverloadCandidate( |
2521 | FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: AS_none), ExplicitTemplateArgs, |
2522 | Args, CandidateSet&: OCS); |
2523 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD)) |
2524 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) |
2525 | AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), |
2526 | Args, CandidateSet&: OCS); |
2527 | } |
2528 | switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) { |
2529 | case OR_Success: |
2530 | ND = Best->FoundDecl; |
2531 | Corrected.setCorrectionDecl(ND); |
2532 | break; |
2533 | default: |
2534 | // FIXME: Arbitrarily pick the first declaration for the note. |
2535 | Corrected.setCorrectionDecl(ND); |
2536 | break; |
2537 | } |
2538 | } |
2539 | R.addDecl(D: ND); |
2540 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { |
2541 | CXXRecordDecl *Record = nullptr; |
2542 | if (Corrected.getCorrectionSpecifier()) { |
2543 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); |
2544 | Record = Ty->getAsCXXRecordDecl(); |
2545 | } |
2546 | if (!Record) |
2547 | Record = cast<CXXRecordDecl>( |
2548 | Val: ND->getDeclContext()->getRedeclContext()); |
2549 | R.setNamingClass(Record); |
2550 | } |
2551 | |
2552 | auto *UnderlyingND = ND->getUnderlyingDecl(); |
2553 | AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) || |
2554 | isa<FunctionTemplateDecl>(Val: UnderlyingND); |
2555 | // FIXME: If we ended up with a typo for a type name or |
2556 | // Objective-C class name, we're in trouble because the parser |
2557 | // is in the wrong place to recover. Suggest the typo |
2558 | // correction, but don't make it a fix-it since we're not going |
2559 | // to recover well anyway. |
2560 | AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) || |
2561 | getAsTypeTemplateDecl(D: UnderlyingND) || |
2562 | isa<ObjCInterfaceDecl>(Val: UnderlyingND); |
2563 | } else { |
2564 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it |
2565 | // because we aren't able to recover. |
2566 | AcceptableWithoutRecovery = true; |
2567 | } |
2568 | |
2569 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { |
2570 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() |
2571 | ? diag::note_implicit_param_decl |
2572 | : diag::note_previous_decl; |
2573 | if (SS.isEmpty()) |
2574 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name, |
2575 | PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery); |
2576 | else |
2577 | diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest) |
2578 | << Name << computeDeclContext(SS, EnteringContext: false) |
2579 | << DroppedSpecifier << SS.getRange(), |
2580 | PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: AcceptableWithRecovery); |
2581 | |
2582 | // Tell the callee whether to try to recover. |
2583 | return !AcceptableWithRecovery; |
2584 | } |
2585 | } |
2586 | R.clear(); |
2587 | |
2588 | // Emit a special diagnostic for failed member lookups. |
2589 | // FIXME: computing the declaration context might fail here (?) |
2590 | if (!SS.isEmpty()) { |
2591 | Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member) |
2592 | << Name << computeDeclContext(SS, EnteringContext: false) |
2593 | << SS.getRange(); |
2594 | return true; |
2595 | } |
2596 | |
2597 | // Give up, we can't recover. |
2598 | Diag(Loc: R.getNameLoc(), DiagID: diagnostic) << Name; |
2599 | return true; |
2600 | } |
2601 | |
2602 | /// In Microsoft mode, if we are inside a template class whose parent class has |
2603 | /// dependent base classes, and we can't resolve an unqualified identifier, then |
2604 | /// assume the identifier is a member of a dependent base class. We can only |
2605 | /// recover successfully in static methods, instance methods, and other contexts |
2606 | /// where 'this' is available. This doesn't precisely match MSVC's |
2607 | /// instantiation model, but it's close enough. |
2608 | static Expr * |
2609 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, |
2610 | DeclarationNameInfo &NameInfo, |
2611 | SourceLocation TemplateKWLoc, |
2612 | const TemplateArgumentListInfo *TemplateArgs) { |
2613 | // Only try to recover from lookup into dependent bases in static methods or |
2614 | // contexts where 'this' is available. |
2615 | QualType ThisType = S.getCurrentThisType(); |
2616 | const CXXRecordDecl *RD = nullptr; |
2617 | if (!ThisType.isNull()) |
2618 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); |
2619 | else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext)) |
2620 | RD = MD->getParent(); |
2621 | if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases()) |
2622 | return nullptr; |
2623 | |
2624 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' |
2625 | // is available, suggest inserting 'this->' as a fixit. |
2626 | SourceLocation Loc = NameInfo.getLoc(); |
2627 | auto DB = S.Diag(Loc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base); |
2628 | DB << NameInfo.getName() << RD; |
2629 | |
2630 | if (!ThisType.isNull()) { |
2631 | DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->" ); |
2632 | return CXXDependentScopeMemberExpr::Create( |
2633 | Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true, |
2634 | /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc, |
2635 | /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs); |
2636 | } |
2637 | |
2638 | // Synthesize a fake NNS that points to the derived class. This will |
2639 | // perform name lookup during template instantiation. |
2640 | CXXScopeSpec SS; |
2641 | auto *NNS = |
2642 | NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: true, T: RD->getTypeForDecl()); |
2643 | SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc)); |
2644 | return DependentScopeDeclRefExpr::Create( |
2645 | Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
2646 | TemplateArgs); |
2647 | } |
2648 | |
2649 | ExprResult |
2650 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, |
2651 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, |
2652 | bool HasTrailingLParen, bool IsAddressOfOperand, |
2653 | CorrectionCandidateCallback *CCC, |
2654 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { |
2655 | assert(!(IsAddressOfOperand && HasTrailingLParen) && |
2656 | "cannot be direct & operand and have a trailing lparen" ); |
2657 | if (SS.isInvalid()) |
2658 | return ExprError(); |
2659 | |
2660 | TemplateArgumentListInfo TemplateArgsBuffer; |
2661 | |
2662 | // Decompose the UnqualifiedId into the following data. |
2663 | DeclarationNameInfo NameInfo; |
2664 | const TemplateArgumentListInfo *TemplateArgs; |
2665 | DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs); |
2666 | |
2667 | DeclarationName Name = NameInfo.getName(); |
2668 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
2669 | SourceLocation NameLoc = NameInfo.getLoc(); |
2670 | |
2671 | if (II && II->isEditorPlaceholder()) { |
2672 | // FIXME: When typed placeholders are supported we can create a typed |
2673 | // placeholder expression node. |
2674 | return ExprError(); |
2675 | } |
2676 | |
2677 | // This specially handles arguments of attributes appertains to a type of C |
2678 | // struct field such that the name lookup within a struct finds the member |
2679 | // name, which is not the case for other contexts in C. |
2680 | if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) { |
2681 | // See if this is reference to a field of struct. |
2682 | LookupResult R(*this, NameInfo, LookupMemberName); |
2683 | // LookupName handles a name lookup from within anonymous struct. |
2684 | if (LookupName(R, S)) { |
2685 | if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) { |
2686 | QualType type = VD->getType().getNonReferenceType(); |
2687 | // This will eventually be translated into MemberExpr upon |
2688 | // the use of instantiated struct fields. |
2689 | return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc); |
2690 | } |
2691 | } |
2692 | } |
2693 | |
2694 | // Perform the required lookup. |
2695 | LookupResult R(*this, NameInfo, |
2696 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) |
2697 | ? LookupObjCImplicitSelfParam |
2698 | : LookupOrdinaryName); |
2699 | if (TemplateKWLoc.isValid() || TemplateArgs) { |
2700 | // Lookup the template name again to correctly establish the context in |
2701 | // which it was found. This is really unfortunate as we already did the |
2702 | // lookup to determine that it was a template name in the first place. If |
2703 | // this becomes a performance hit, we can work harder to preserve those |
2704 | // results until we get here but it's likely not worth it. |
2705 | AssumedTemplateKind AssumedTemplate; |
2706 | if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(), |
2707 | /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc, |
2708 | ATK: &AssumedTemplate)) |
2709 | return ExprError(); |
2710 | |
2711 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2712 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
2713 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
2714 | } else { |
2715 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); |
2716 | LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(), |
2717 | /*AllowBuiltinCreation=*/!IvarLookupFollowUp); |
2718 | |
2719 | // If the result might be in a dependent base class, this is a dependent |
2720 | // id-expression. |
2721 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2722 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
2723 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
2724 | |
2725 | // If this reference is in an Objective-C method, then we need to do |
2726 | // some special Objective-C lookup, too. |
2727 | if (IvarLookupFollowUp) { |
2728 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true)); |
2729 | if (E.isInvalid()) |
2730 | return ExprError(); |
2731 | |
2732 | if (Expr *Ex = E.getAs<Expr>()) |
2733 | return Ex; |
2734 | } |
2735 | } |
2736 | |
2737 | if (R.isAmbiguous()) |
2738 | return ExprError(); |
2739 | |
2740 | // This could be an implicitly declared function reference if the language |
2741 | // mode allows it as a feature. |
2742 | if (R.empty() && HasTrailingLParen && II && |
2743 | getLangOpts().implicitFunctionsAllowed()) { |
2744 | NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S); |
2745 | if (D) R.addDecl(D); |
2746 | } |
2747 | |
2748 | // Determine whether this name might be a candidate for |
2749 | // argument-dependent lookup. |
2750 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); |
2751 | |
2752 | if (R.empty() && !ADL) { |
2753 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { |
2754 | if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo, |
2755 | TemplateKWLoc, TemplateArgs)) |
2756 | return E; |
2757 | } |
2758 | |
2759 | // Don't diagnose an empty lookup for inline assembly. |
2760 | if (IsInlineAsmIdentifier) |
2761 | return ExprError(); |
2762 | |
2763 | // If this name wasn't predeclared and if this is not a function |
2764 | // call, diagnose the problem. |
2765 | TypoExpr *TE = nullptr; |
2766 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() |
2767 | : nullptr); |
2768 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; |
2769 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && |
2770 | "Typo correction callback misconfigured" ); |
2771 | if (CCC) { |
2772 | // Make sure the callback knows what the typo being diagnosed is. |
2773 | CCC->setTypoName(II); |
2774 | if (SS.isValid()) |
2775 | CCC->setTypoNNS(SS.getScopeRep()); |
2776 | } |
2777 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for |
2778 | // a template name, but we happen to have always already looked up the name |
2779 | // before we get here if it must be a template name. |
2780 | if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr, |
2781 | Args: std::nullopt, LookupCtx: nullptr, Out: &TE)) { |
2782 | if (TE && KeywordReplacement) { |
2783 | auto &State = getTypoExprState(TE); |
2784 | auto BestTC = State.Consumer->getNextCorrection(); |
2785 | if (BestTC.isKeyword()) { |
2786 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); |
2787 | if (State.DiagHandler) |
2788 | State.DiagHandler(BestTC); |
2789 | KeywordReplacement->startToken(); |
2790 | KeywordReplacement->setKind(II->getTokenID()); |
2791 | KeywordReplacement->setIdentifierInfo(II); |
2792 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); |
2793 | // Clean up the state associated with the TypoExpr, since it has |
2794 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). |
2795 | clearDelayedTypo(TE); |
2796 | // Signal that a correction to a keyword was performed by returning a |
2797 | // valid-but-null ExprResult. |
2798 | return (Expr*)nullptr; |
2799 | } |
2800 | State.Consumer->resetCorrectionStream(); |
2801 | } |
2802 | return TE ? TE : ExprError(); |
2803 | } |
2804 | |
2805 | assert(!R.empty() && |
2806 | "DiagnoseEmptyLookup returned false but added no results" ); |
2807 | |
2808 | // If we found an Objective-C instance variable, let |
2809 | // LookupInObjCMethod build the appropriate expression to |
2810 | // reference the ivar. |
2811 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { |
2812 | R.clear(); |
2813 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier())); |
2814 | // In a hopelessly buggy code, Objective-C instance variable |
2815 | // lookup fails and no expression will be built to reference it. |
2816 | if (!E.isInvalid() && !E.get()) |
2817 | return ExprError(); |
2818 | return E; |
2819 | } |
2820 | } |
2821 | |
2822 | // This is guaranteed from this point on. |
2823 | assert(!R.empty() || ADL); |
2824 | |
2825 | // Check whether this might be a C++ implicit instance member access. |
2826 | // C++ [class.mfct.non-static]p3: |
2827 | // When an id-expression that is not part of a class member access |
2828 | // syntax and not used to form a pointer to member is used in the |
2829 | // body of a non-static member function of class X, if name lookup |
2830 | // resolves the name in the id-expression to a non-static non-type |
2831 | // member of some class C, the id-expression is transformed into a |
2832 | // class member access expression using (*this) as the |
2833 | // postfix-expression to the left of the . operator. |
2834 | // |
2835 | // But we don't actually need to do this for '&' operands if R |
2836 | // resolved to a function or overloaded function set, because the |
2837 | // expression is ill-formed if it actually works out to be a |
2838 | // non-static member function: |
2839 | // |
2840 | // C++ [expr.ref]p4: |
2841 | // Otherwise, if E1.E2 refers to a non-static member function. . . |
2842 | // [t]he expression can be used only as the left-hand operand of a |
2843 | // member function call. |
2844 | // |
2845 | // There are other safeguards against such uses, but it's important |
2846 | // to get this right here so that we don't end up making a |
2847 | // spuriously dependent expression if we're inside a dependent |
2848 | // instance method. |
2849 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
2850 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, |
2851 | S); |
2852 | |
2853 | if (TemplateArgs || TemplateKWLoc.isValid()) { |
2854 | |
2855 | // In C++1y, if this is a variable template id, then check it |
2856 | // in BuildTemplateIdExpr(). |
2857 | // The single lookup result must be a variable template declaration. |
2858 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && |
2859 | Id.TemplateId->Kind == TNK_Var_template) { |
2860 | assert(R.getAsSingle<VarTemplateDecl>() && |
2861 | "There should only be one declaration found." ); |
2862 | } |
2863 | |
2864 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs); |
2865 | } |
2866 | |
2867 | return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL); |
2868 | } |
2869 | |
2870 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( |
2871 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, |
2872 | bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) { |
2873 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
2874 | LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType()); |
2875 | |
2876 | if (R.isAmbiguous()) |
2877 | return ExprError(); |
2878 | |
2879 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2880 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), |
2881 | NameInfo, /*TemplateArgs=*/nullptr); |
2882 | |
2883 | if (R.empty()) { |
2884 | // Don't diagnose problems with invalid record decl, the secondary no_member |
2885 | // diagnostic during template instantiation is likely bogus, e.g. if a class |
2886 | // is invalid because it's derived from an invalid base class, then missing |
2887 | // members were likely supposed to be inherited. |
2888 | DeclContext *DC = computeDeclContext(SS); |
2889 | if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC)) |
2890 | if (CD->isInvalidDecl()) |
2891 | return ExprError(); |
2892 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member) |
2893 | << NameInfo.getName() << DC << SS.getRange(); |
2894 | return ExprError(); |
2895 | } |
2896 | |
2897 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { |
2898 | // Diagnose a missing typename if this resolved unambiguously to a type in |
2899 | // a dependent context. If we can recover with a type, downgrade this to |
2900 | // a warning in Microsoft compatibility mode. |
2901 | unsigned DiagID = diag::err_typename_missing; |
2902 | if (RecoveryTSI && getLangOpts().MSVCCompat) |
2903 | DiagID = diag::ext_typename_missing; |
2904 | SourceLocation Loc = SS.getBeginLoc(); |
2905 | auto D = Diag(Loc, DiagID); |
2906 | D << SS.getScopeRep() << NameInfo.getName().getAsString() |
2907 | << SourceRange(Loc, NameInfo.getEndLoc()); |
2908 | |
2909 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE |
2910 | // context. |
2911 | if (!RecoveryTSI) |
2912 | return ExprError(); |
2913 | |
2914 | // Only issue the fixit if we're prepared to recover. |
2915 | D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename " ); |
2916 | |
2917 | // Recover by pretending this was an elaborated type. |
2918 | QualType Ty = Context.getTypeDeclType(Decl: TD); |
2919 | TypeLocBuilder TLB; |
2920 | TLB.pushTypeSpec(T: Ty).setNameLoc(NameInfo.getLoc()); |
2921 | |
2922 | QualType ET = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, T: Ty); |
2923 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(T: ET); |
2924 | QTL.setElaboratedKeywordLoc(SourceLocation()); |
2925 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
2926 | |
2927 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET); |
2928 | |
2929 | return ExprEmpty(); |
2930 | } |
2931 | |
2932 | // If necessary, build an implicit class member access. |
2933 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
2934 | return BuildPossibleImplicitMemberExpr(SS, |
2935 | /*TemplateKWLoc=*/SourceLocation(), |
2936 | R, /*TemplateArgs=*/nullptr, |
2937 | /*S=*/nullptr); |
2938 | |
2939 | return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false); |
2940 | } |
2941 | |
2942 | ExprResult |
2943 | Sema::PerformObjectMemberConversion(Expr *From, |
2944 | NestedNameSpecifier *Qualifier, |
2945 | NamedDecl *FoundDecl, |
2946 | NamedDecl *Member) { |
2947 | const auto *RD = dyn_cast<CXXRecordDecl>(Val: Member->getDeclContext()); |
2948 | if (!RD) |
2949 | return From; |
2950 | |
2951 | QualType DestRecordType; |
2952 | QualType DestType; |
2953 | QualType FromRecordType; |
2954 | QualType FromType = From->getType(); |
2955 | bool PointerConversions = false; |
2956 | if (isa<FieldDecl>(Val: Member)) { |
2957 | DestRecordType = Context.getCanonicalType(T: Context.getTypeDeclType(Decl: RD)); |
2958 | auto FromPtrType = FromType->getAs<PointerType>(); |
2959 | DestRecordType = Context.getAddrSpaceQualType( |
2960 | T: DestRecordType, AddressSpace: FromPtrType |
2961 | ? FromType->getPointeeType().getAddressSpace() |
2962 | : FromType.getAddressSpace()); |
2963 | |
2964 | if (FromPtrType) { |
2965 | DestType = Context.getPointerType(T: DestRecordType); |
2966 | FromRecordType = FromPtrType->getPointeeType(); |
2967 | PointerConversions = true; |
2968 | } else { |
2969 | DestType = DestRecordType; |
2970 | FromRecordType = FromType; |
2971 | } |
2972 | } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) { |
2973 | if (!Method->isImplicitObjectMemberFunction()) |
2974 | return From; |
2975 | |
2976 | DestType = Method->getThisType().getNonReferenceType(); |
2977 | DestRecordType = Method->getFunctionObjectParameterType(); |
2978 | |
2979 | if (FromType->getAs<PointerType>()) { |
2980 | FromRecordType = FromType->getPointeeType(); |
2981 | PointerConversions = true; |
2982 | } else { |
2983 | FromRecordType = FromType; |
2984 | DestType = DestRecordType; |
2985 | } |
2986 | |
2987 | LangAS FromAS = FromRecordType.getAddressSpace(); |
2988 | LangAS DestAS = DestRecordType.getAddressSpace(); |
2989 | if (FromAS != DestAS) { |
2990 | QualType FromRecordTypeWithoutAS = |
2991 | Context.removeAddrSpaceQualType(T: FromRecordType); |
2992 | QualType FromTypeWithDestAS = |
2993 | Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS); |
2994 | if (PointerConversions) |
2995 | FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS); |
2996 | From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS, |
2997 | CK: CK_AddressSpaceConversion, VK: From->getValueKind()) |
2998 | .get(); |
2999 | } |
3000 | } else { |
3001 | // No conversion necessary. |
3002 | return From; |
3003 | } |
3004 | |
3005 | if (DestType->isDependentType() || FromType->isDependentType()) |
3006 | return From; |
3007 | |
3008 | // If the unqualified types are the same, no conversion is necessary. |
3009 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
3010 | return From; |
3011 | |
3012 | SourceRange FromRange = From->getSourceRange(); |
3013 | SourceLocation FromLoc = FromRange.getBegin(); |
3014 | |
3015 | ExprValueKind VK = From->getValueKind(); |
3016 | |
3017 | // C++ [class.member.lookup]p8: |
3018 | // [...] Ambiguities can often be resolved by qualifying a name with its |
3019 | // class name. |
3020 | // |
3021 | // If the member was a qualified name and the qualified referred to a |
3022 | // specific base subobject type, we'll cast to that intermediate type |
3023 | // first and then to the object in which the member is declared. That allows |
3024 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: |
3025 | // |
3026 | // class Base { public: int x; }; |
3027 | // class Derived1 : public Base { }; |
3028 | // class Derived2 : public Base { }; |
3029 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; |
3030 | // |
3031 | // void VeryDerived::f() { |
3032 | // x = 17; // error: ambiguous base subobjects |
3033 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 |
3034 | // } |
3035 | if (Qualifier && Qualifier->getAsType()) { |
3036 | QualType QType = QualType(Qualifier->getAsType(), 0); |
3037 | assert(QType->isRecordType() && "lookup done with non-record type" ); |
3038 | |
3039 | QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); |
3040 | |
3041 | // In C++98, the qualifier type doesn't actually have to be a base |
3042 | // type of the object type, in which case we just ignore it. |
3043 | // Otherwise build the appropriate casts. |
3044 | if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) { |
3045 | CXXCastPath BasePath; |
3046 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType, |
3047 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath)) |
3048 | return ExprError(); |
3049 | |
3050 | if (PointerConversions) |
3051 | QType = Context.getPointerType(T: QType); |
3052 | From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase, |
3053 | VK, BasePath: &BasePath).get(); |
3054 | |
3055 | FromType = QType; |
3056 | FromRecordType = QRecordType; |
3057 | |
3058 | // If the qualifier type was the same as the destination type, |
3059 | // we're done. |
3060 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
3061 | return From; |
3062 | } |
3063 | } |
3064 | |
3065 | CXXCastPath BasePath; |
3066 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType, |
3067 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath, |
3068 | /*IgnoreAccess=*/true)) |
3069 | return ExprError(); |
3070 | |
3071 | return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, |
3072 | VK, BasePath: &BasePath); |
3073 | } |
3074 | |
3075 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, |
3076 | const LookupResult &R, |
3077 | bool HasTrailingLParen) { |
3078 | // Only when used directly as the postfix-expression of a call. |
3079 | if (!HasTrailingLParen) |
3080 | return false; |
3081 | |
3082 | // Never if a scope specifier was provided. |
3083 | if (SS.isNotEmpty()) |
3084 | return false; |
3085 | |
3086 | // Only in C++ or ObjC++. |
3087 | if (!getLangOpts().CPlusPlus) |
3088 | return false; |
3089 | |
3090 | // Turn off ADL when we find certain kinds of declarations during |
3091 | // normal lookup: |
3092 | for (const NamedDecl *D : R) { |
3093 | // C++0x [basic.lookup.argdep]p3: |
3094 | // -- a declaration of a class member |
3095 | // Since using decls preserve this property, we check this on the |
3096 | // original decl. |
3097 | if (D->isCXXClassMember()) |
3098 | return false; |
3099 | |
3100 | // C++0x [basic.lookup.argdep]p3: |
3101 | // -- a block-scope function declaration that is not a |
3102 | // using-declaration |
3103 | // NOTE: we also trigger this for function templates (in fact, we |
3104 | // don't check the decl type at all, since all other decl types |
3105 | // turn off ADL anyway). |
3106 | if (isa<UsingShadowDecl>(Val: D)) |
3107 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
3108 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) |
3109 | return false; |
3110 | |
3111 | // C++0x [basic.lookup.argdep]p3: |
3112 | // -- a declaration that is neither a function or a function |
3113 | // template |
3114 | // And also for builtin functions. |
3115 | if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) { |
3116 | // But also builtin functions. |
3117 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) |
3118 | return false; |
3119 | } else if (!isa<FunctionTemplateDecl>(Val: D)) |
3120 | return false; |
3121 | } |
3122 | |
3123 | return true; |
3124 | } |
3125 | |
3126 | |
3127 | /// Diagnoses obvious problems with the use of the given declaration |
3128 | /// as an expression. This is only actually called for lookups that |
3129 | /// were not overloaded, and it doesn't promise that the declaration |
3130 | /// will in fact be used. |
3131 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, |
3132 | bool AcceptInvalid) { |
3133 | if (D->isInvalidDecl() && !AcceptInvalid) |
3134 | return true; |
3135 | |
3136 | if (isa<TypedefNameDecl>(Val: D)) { |
3137 | S.Diag(Loc, DiagID: diag::err_unexpected_typedef) << D->getDeclName(); |
3138 | return true; |
3139 | } |
3140 | |
3141 | if (isa<ObjCInterfaceDecl>(Val: D)) { |
3142 | S.Diag(Loc, DiagID: diag::err_unexpected_interface) << D->getDeclName(); |
3143 | return true; |
3144 | } |
3145 | |
3146 | if (isa<NamespaceDecl>(Val: D)) { |
3147 | S.Diag(Loc, DiagID: diag::err_unexpected_namespace) << D->getDeclName(); |
3148 | return true; |
3149 | } |
3150 | |
3151 | return false; |
3152 | } |
3153 | |
3154 | // Certain multiversion types should be treated as overloaded even when there is |
3155 | // only one result. |
3156 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { |
3157 | assert(R.isSingleResult() && "Expected only a single result" ); |
3158 | const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl()); |
3159 | return FD && |
3160 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); |
3161 | } |
3162 | |
3163 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
3164 | LookupResult &R, bool NeedsADL, |
3165 | bool AcceptInvalidDecl) { |
3166 | // If this is a single, fully-resolved result and we don't need ADL, |
3167 | // just build an ordinary singleton decl ref. |
3168 | if (!NeedsADL && R.isSingleResult() && |
3169 | !R.getAsSingle<FunctionTemplateDecl>() && |
3170 | !ShouldLookupResultBeMultiVersionOverload(R)) |
3171 | return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(), |
3172 | FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr, |
3173 | AcceptInvalidDecl); |
3174 | |
3175 | // We only need to check the declaration if there's exactly one |
3176 | // result, because in the overloaded case the results can only be |
3177 | // functions and function templates. |
3178 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && |
3179 | CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(), |
3180 | AcceptInvalid: AcceptInvalidDecl)) |
3181 | return ExprError(); |
3182 | |
3183 | // Otherwise, just build an unresolved lookup expression. Suppress |
3184 | // any lookup-related diagnostics; we'll hash these out later, when |
3185 | // we've picked a target. |
3186 | R.suppressDiagnostics(); |
3187 | |
3188 | UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( |
3189 | Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context), |
3190 | NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(), |
3191 | /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false); |
3192 | |
3193 | return ULE; |
3194 | } |
3195 | |
3196 | static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, |
3197 | SourceLocation loc, |
3198 | ValueDecl *var); |
3199 | |
3200 | ExprResult Sema::BuildDeclarationNameExpr( |
3201 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
3202 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, |
3203 | bool AcceptInvalidDecl) { |
3204 | assert(D && "Cannot refer to a NULL declaration" ); |
3205 | assert(!isa<FunctionTemplateDecl>(D) && |
3206 | "Cannot refer unambiguously to a function template" ); |
3207 | |
3208 | SourceLocation Loc = NameInfo.getLoc(); |
3209 | if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) { |
3210 | // Recovery from invalid cases (e.g. D is an invalid Decl). |
3211 | // We use the dependent type for the RecoveryExpr to prevent bogus follow-up |
3212 | // diagnostics, as invalid decls use int as a fallback type. |
3213 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}); |
3214 | } |
3215 | |
3216 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) { |
3217 | // Specifically diagnose references to class templates that are missing |
3218 | // a template argument list. |
3219 | diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc); |
3220 | return ExprError(); |
3221 | } |
3222 | |
3223 | // Make sure that we're referring to a value. |
3224 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) { |
3225 | Diag(Loc, DiagID: diag::err_ref_non_value) << D << SS.getRange(); |
3226 | Diag(Loc: D->getLocation(), DiagID: diag::note_declared_at); |
3227 | return ExprError(); |
3228 | } |
3229 | |
3230 | // Check whether this declaration can be used. Note that we suppress |
3231 | // this check when we're going to perform argument-dependent lookup |
3232 | // on this function name, because this might not be the function |
3233 | // that overload resolution actually selects. |
3234 | if (DiagnoseUseOfDecl(D, Locs: Loc)) |
3235 | return ExprError(); |
3236 | |
3237 | auto *VD = cast<ValueDecl>(Val: D); |
3238 | |
3239 | // Only create DeclRefExpr's for valid Decl's. |
3240 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) |
3241 | return ExprError(); |
3242 | |
3243 | // Handle members of anonymous structs and unions. If we got here, |
3244 | // and the reference is to a class member indirect field, then this |
3245 | // must be the subject of a pointer-to-member expression. |
3246 | if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD); |
3247 | IndirectField && !IndirectField->isCXXClassMember()) |
3248 | return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(), |
3249 | indirectField: IndirectField); |
3250 | |
3251 | QualType type = VD->getType(); |
3252 | if (type.isNull()) |
3253 | return ExprError(); |
3254 | ExprValueKind valueKind = VK_PRValue; |
3255 | |
3256 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of |
3257 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, |
3258 | // is expanded by some outer '...' in the context of the use. |
3259 | type = type.getNonPackExpansionType(); |
3260 | |
3261 | switch (D->getKind()) { |
3262 | // Ignore all the non-ValueDecl kinds. |
3263 | #define ABSTRACT_DECL(kind) |
3264 | #define VALUE(type, base) |
3265 | #define DECL(type, base) case Decl::type: |
3266 | #include "clang/AST/DeclNodes.inc" |
3267 | llvm_unreachable("invalid value decl kind" ); |
3268 | |
3269 | // These shouldn't make it here. |
3270 | case Decl::ObjCAtDefsField: |
3271 | llvm_unreachable("forming non-member reference to ivar?" ); |
3272 | |
3273 | // Enum constants are always r-values and never references. |
3274 | // Unresolved using declarations are dependent. |
3275 | case Decl::EnumConstant: |
3276 | case Decl::UnresolvedUsingValue: |
3277 | case Decl::OMPDeclareReduction: |
3278 | case Decl::OMPDeclareMapper: |
3279 | valueKind = VK_PRValue; |
3280 | break; |
3281 | |
3282 | // Fields and indirect fields that got here must be for |
3283 | // pointer-to-member expressions; we just call them l-values for |
3284 | // internal consistency, because this subexpression doesn't really |
3285 | // exist in the high-level semantics. |
3286 | case Decl::Field: |
3287 | case Decl::IndirectField: |
3288 | case Decl::ObjCIvar: |
3289 | assert((getLangOpts().CPlusPlus || isAttrContext()) && |
3290 | "building reference to field in C?" ); |
3291 | |
3292 | // These can't have reference type in well-formed programs, but |
3293 | // for internal consistency we do this anyway. |
3294 | type = type.getNonReferenceType(); |
3295 | valueKind = VK_LValue; |
3296 | break; |
3297 | |
3298 | // Non-type template parameters are either l-values or r-values |
3299 | // depending on the type. |
3300 | case Decl::NonTypeTemplateParm: { |
3301 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { |
3302 | type = reftype->getPointeeType(); |
3303 | valueKind = VK_LValue; // even if the parameter is an r-value reference |
3304 | break; |
3305 | } |
3306 | |
3307 | // [expr.prim.id.unqual]p2: |
3308 | // If the entity is a template parameter object for a template |
3309 | // parameter of type T, the type of the expression is const T. |
3310 | // [...] The expression is an lvalue if the entity is a [...] template |
3311 | // parameter object. |
3312 | if (type->isRecordType()) { |
3313 | type = type.getUnqualifiedType().withConst(); |
3314 | valueKind = VK_LValue; |
3315 | break; |
3316 | } |
3317 | |
3318 | // For non-references, we need to strip qualifiers just in case |
3319 | // the template parameter was declared as 'const int' or whatever. |
3320 | valueKind = VK_PRValue; |
3321 | type = type.getUnqualifiedType(); |
3322 | break; |
3323 | } |
3324 | |
3325 | case Decl::Var: |
3326 | case Decl::VarTemplateSpecialization: |
3327 | case Decl::VarTemplatePartialSpecialization: |
3328 | case Decl::Decomposition: |
3329 | case Decl::OMPCapturedExpr: |
3330 | // In C, "extern void blah;" is valid and is an r-value. |
3331 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && |
3332 | type->isVoidType()) { |
3333 | valueKind = VK_PRValue; |
3334 | break; |
3335 | } |
3336 | [[fallthrough]]; |
3337 | |
3338 | case Decl::ImplicitParam: |
3339 | case Decl::ParmVar: { |
3340 | // These are always l-values. |
3341 | valueKind = VK_LValue; |
3342 | type = type.getNonReferenceType(); |
3343 | |
3344 | // FIXME: Does the addition of const really only apply in |
3345 | // potentially-evaluated contexts? Since the variable isn't actually |
3346 | // captured in an unevaluated context, it seems that the answer is no. |
3347 | if (!isUnevaluatedContext()) { |
3348 | QualType CapturedType = getCapturedDeclRefType(Var: cast<VarDecl>(Val: VD), Loc); |
3349 | if (!CapturedType.isNull()) |
3350 | type = CapturedType; |
3351 | } |
3352 | |
3353 | break; |
3354 | } |
3355 | |
3356 | case Decl::Binding: |
3357 | // These are always lvalues. |
3358 | valueKind = VK_LValue; |
3359 | type = type.getNonReferenceType(); |
3360 | break; |
3361 | |
3362 | case Decl::Function: { |
3363 | if (unsigned BID = cast<FunctionDecl>(Val: VD)->getBuiltinID()) { |
3364 | if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) { |
3365 | type = Context.BuiltinFnTy; |
3366 | valueKind = VK_PRValue; |
3367 | break; |
3368 | } |
3369 | } |
3370 | |
3371 | const FunctionType *fty = type->castAs<FunctionType>(); |
3372 | |
3373 | // If we're referring to a function with an __unknown_anytype |
3374 | // result type, make the entire expression __unknown_anytype. |
3375 | if (fty->getReturnType() == Context.UnknownAnyTy) { |
3376 | type = Context.UnknownAnyTy; |
3377 | valueKind = VK_PRValue; |
3378 | break; |
3379 | } |
3380 | |
3381 | // Functions are l-values in C++. |
3382 | if (getLangOpts().CPlusPlus) { |
3383 | valueKind = VK_LValue; |
3384 | break; |
3385 | } |
3386 | |
3387 | // C99 DR 316 says that, if a function type comes from a |
3388 | // function definition (without a prototype), that type is only |
3389 | // used for checking compatibility. Therefore, when referencing |
3390 | // the function, we pretend that we don't have the full function |
3391 | // type. |
3392 | if (!cast<FunctionDecl>(Val: VD)->hasPrototype() && isa<FunctionProtoType>(Val: fty)) |
3393 | type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(), |
3394 | Info: fty->getExtInfo()); |
3395 | |
3396 | // Functions are r-values in C. |
3397 | valueKind = VK_PRValue; |
3398 | break; |
3399 | } |
3400 | |
3401 | case Decl::CXXDeductionGuide: |
3402 | llvm_unreachable("building reference to deduction guide" ); |
3403 | |
3404 | case Decl::MSProperty: |
3405 | case Decl::MSGuid: |
3406 | case Decl::TemplateParamObject: |
3407 | // FIXME: Should MSGuidDecl and template parameter objects be subject to |
3408 | // capture in OpenMP, or duplicated between host and device? |
3409 | valueKind = VK_LValue; |
3410 | break; |
3411 | |
3412 | case Decl::UnnamedGlobalConstant: |
3413 | valueKind = VK_LValue; |
3414 | break; |
3415 | |
3416 | case Decl::CXXMethod: |
3417 | // If we're referring to a method with an __unknown_anytype |
3418 | // result type, make the entire expression __unknown_anytype. |
3419 | // This should only be possible with a type written directly. |
3420 | if (const FunctionProtoType *proto = |
3421 | dyn_cast<FunctionProtoType>(Val: VD->getType())) |
3422 | if (proto->getReturnType() == Context.UnknownAnyTy) { |
3423 | type = Context.UnknownAnyTy; |
3424 | valueKind = VK_PRValue; |
3425 | break; |
3426 | } |
3427 | |
3428 | // C++ methods are l-values if static, r-values if non-static. |
3429 | if (cast<CXXMethodDecl>(Val: VD)->isStatic()) { |
3430 | valueKind = VK_LValue; |
3431 | break; |
3432 | } |
3433 | [[fallthrough]]; |
3434 | |
3435 | case Decl::CXXConversion: |
3436 | case Decl::CXXDestructor: |
3437 | case Decl::CXXConstructor: |
3438 | valueKind = VK_PRValue; |
3439 | break; |
3440 | } |
3441 | |
3442 | auto *E = |
3443 | BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD, |
3444 | /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs); |
3445 | // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We |
3446 | // wrap a DeclRefExpr referring to an invalid decl with a dependent-type |
3447 | // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus |
3448 | // diagnostics). |
3449 | if (VD->isInvalidDecl() && E) |
3450 | return CreateRecoveryExpr(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: {E}); |
3451 | return E; |
3452 | } |
3453 | |
3454 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, |
3455 | SmallString<32> &Target) { |
3456 | Target.resize(N: CharByteWidth * (Source.size() + 1)); |
3457 | char *ResultPtr = &Target[0]; |
3458 | const llvm::UTF8 *ErrorPtr; |
3459 | bool success = |
3460 | llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr); |
3461 | (void)success; |
3462 | assert(success); |
3463 | Target.resize(N: ResultPtr - &Target[0]); |
3464 | } |
3465 | |
3466 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, |
3467 | PredefinedIdentKind IK) { |
3468 | Decl *currentDecl = getPredefinedExprDecl(DC: CurContext); |
3469 | if (!currentDecl) { |
3470 | Diag(Loc, DiagID: diag::ext_predef_outside_function); |
3471 | currentDecl = Context.getTranslationUnitDecl(); |
3472 | } |
3473 | |
3474 | QualType ResTy; |
3475 | StringLiteral *SL = nullptr; |
3476 | if (cast<DeclContext>(Val: currentDecl)->isDependentContext()) |
3477 | ResTy = Context.DependentTy; |
3478 | else { |
3479 | // Pre-defined identifiers are of type char[x], where x is the length of |
3480 | // the string. |
3481 | bool ForceElaboratedPrinting = |
3482 | IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat; |
3483 | auto Str = |
3484 | PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting); |
3485 | unsigned Length = Str.length(); |
3486 | |
3487 | llvm::APInt LengthI(32, Length + 1); |
3488 | if (IK == PredefinedIdentKind::LFunction || |
3489 | IK == PredefinedIdentKind::LFuncSig) { |
3490 | ResTy = |
3491 | Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst()); |
3492 | SmallString<32> RawChars; |
3493 | ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(), |
3494 | Source: Str, Target&: RawChars); |
3495 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
3496 | ASM: ArraySizeModifier::Normal, |
3497 | /*IndexTypeQuals*/ 0); |
3498 | SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide, |
3499 | /*Pascal*/ false, Ty: ResTy, Loc); |
3500 | } else { |
3501 | ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()); |
3502 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
3503 | ASM: ArraySizeModifier::Normal, |
3504 | /*IndexTypeQuals*/ 0); |
3505 | SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary, |
3506 | /*Pascal*/ false, Ty: ResTy, Loc); |
3507 | } |
3508 | } |
3509 | |
3510 | return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt, |
3511 | SL); |
3512 | } |
3513 | |
3514 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { |
3515 | return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind)); |
3516 | } |
3517 | |
3518 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { |
3519 | SmallString<16> CharBuffer; |
3520 | bool Invalid = false; |
3521 | StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid); |
3522 | if (Invalid) |
3523 | return ExprError(); |
3524 | |
3525 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), |
3526 | PP, Tok.getKind()); |
3527 | if (Literal.hadError()) |
3528 | return ExprError(); |
3529 | |
3530 | QualType Ty; |
3531 | if (Literal.isWide()) |
3532 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. |
3533 | else if (Literal.isUTF8() && getLangOpts().C23) |
3534 | Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23 |
3535 | else if (Literal.isUTF8() && getLangOpts().Char8) |
3536 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. |
3537 | else if (Literal.isUTF16()) |
3538 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. |
3539 | else if (Literal.isUTF32()) |
3540 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. |
3541 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) |
3542 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. |
3543 | else |
3544 | Ty = Context.CharTy; // 'x' -> char in C++; |
3545 | // u8'x' -> char in C11-C17 and in C++ without char8_t. |
3546 | |
3547 | CharacterLiteralKind Kind = CharacterLiteralKind::Ascii; |
3548 | if (Literal.isWide()) |
3549 | Kind = CharacterLiteralKind::Wide; |
3550 | else if (Literal.isUTF16()) |
3551 | Kind = CharacterLiteralKind::UTF16; |
3552 | else if (Literal.isUTF32()) |
3553 | Kind = CharacterLiteralKind::UTF32; |
3554 | else if (Literal.isUTF8()) |
3555 | Kind = CharacterLiteralKind::UTF8; |
3556 | |
3557 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, |
3558 | Tok.getLocation()); |
3559 | |
3560 | if (Literal.getUDSuffix().empty()) |
3561 | return Lit; |
3562 | |
3563 | // We're building a user-defined literal. |
3564 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
3565 | SourceLocation UDSuffixLoc = |
3566 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
3567 | |
3568 | // Make sure we're allowed user-defined literals here. |
3569 | if (!UDLScope) |
3570 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_character_udl)); |
3571 | |
3572 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form |
3573 | // operator "" X (ch) |
3574 | return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc, |
3575 | Args: Lit, LitEndLoc: Tok.getLocation()); |
3576 | } |
3577 | |
3578 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { |
3579 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
3580 | return IntegerLiteral::Create(C: Context, V: llvm::APInt(IntSize, Val), |
3581 | type: Context.IntTy, l: Loc); |
3582 | } |
3583 | |
3584 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, |
3585 | QualType Ty, SourceLocation Loc) { |
3586 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty); |
3587 | |
3588 | using llvm::APFloat; |
3589 | APFloat Val(Format); |
3590 | |
3591 | llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode(); |
3592 | if (RM == llvm::RoundingMode::Dynamic) |
3593 | RM = llvm::RoundingMode::NearestTiesToEven; |
3594 | APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM); |
3595 | |
3596 | // Overflow is always an error, but underflow is only an error if |
3597 | // we underflowed to zero (APFloat reports denormals as underflow). |
3598 | if ((result & APFloat::opOverflow) || |
3599 | ((result & APFloat::opUnderflow) && Val.isZero())) { |
3600 | unsigned diagnostic; |
3601 | SmallString<20> buffer; |
3602 | if (result & APFloat::opOverflow) { |
3603 | diagnostic = diag::warn_float_overflow; |
3604 | APFloat::getLargest(Sem: Format).toString(Str&: buffer); |
3605 | } else { |
3606 | diagnostic = diag::warn_float_underflow; |
3607 | APFloat::getSmallest(Sem: Format).toString(Str&: buffer); |
3608 | } |
3609 | |
3610 | S.Diag(Loc, DiagID: diagnostic) << Ty << buffer.str(); |
3611 | } |
3612 | |
3613 | bool isExact = (result == APFloat::opOK); |
3614 | return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc); |
3615 | } |
3616 | |
3617 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) { |
3618 | assert(E && "Invalid expression" ); |
3619 | |
3620 | if (E->isValueDependent()) |
3621 | return false; |
3622 | |
3623 | QualType QT = E->getType(); |
3624 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { |
3625 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_pragma_loop_invalid_argument_type) << QT; |
3626 | return true; |
3627 | } |
3628 | |
3629 | llvm::APSInt ValueAPS; |
3630 | ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS); |
3631 | |
3632 | if (R.isInvalid()) |
3633 | return true; |
3634 | |
3635 | // GCC allows the value of unroll count to be 0. |
3636 | // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says |
3637 | // "The values of 0 and 1 block any unrolling of the loop." |
3638 | // The values doesn't have to be strictly positive in '#pragma GCC unroll' and |
3639 | // '#pragma unroll' cases. |
3640 | bool ValueIsPositive = |
3641 | AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive(); |
3642 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { |
3643 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_requires_positive_value) |
3644 | << toString(I: ValueAPS, Radix: 10) << ValueIsPositive; |
3645 | return true; |
3646 | } |
3647 | |
3648 | return false; |
3649 | } |
3650 | |
3651 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { |
3652 | // Fast path for a single digit (which is quite common). A single digit |
3653 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. |
3654 | if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) { |
3655 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); |
3656 | return ActOnIntegerConstant(Loc: Tok.getLocation(), Val); |
3657 | } |
3658 | |
3659 | SmallString<128> SpellingBuffer; |
3660 | // NumericLiteralParser wants to overread by one character. Add padding to |
3661 | // the buffer in case the token is copied to the buffer. If getSpelling() |
3662 | // returns a StringRef to the memory buffer, it should have a null char at |
3663 | // the EOF, so it is also safe. |
3664 | SpellingBuffer.resize(N: Tok.getLength() + 1); |
3665 | |
3666 | // Get the spelling of the token, which eliminates trigraphs, etc. |
3667 | bool Invalid = false; |
3668 | StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid); |
3669 | if (Invalid) |
3670 | return ExprError(); |
3671 | |
3672 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), |
3673 | PP.getSourceManager(), PP.getLangOpts(), |
3674 | PP.getTargetInfo(), PP.getDiagnostics()); |
3675 | if (Literal.hadError) |
3676 | return ExprError(); |
3677 | |
3678 | if (Literal.hasUDSuffix()) { |
3679 | // We're building a user-defined literal. |
3680 | const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
3681 | SourceLocation UDSuffixLoc = |
3682 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
3683 | |
3684 | // Make sure we're allowed user-defined literals here. |
3685 | if (!UDLScope) |
3686 | return ExprError(Diag(Loc: UDSuffixLoc, DiagID: diag::err_invalid_numeric_udl)); |
3687 | |
3688 | QualType CookedTy; |
3689 | if (Literal.isFloatingLiteral()) { |
3690 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type |
3691 | // long double, the literal is treated as a call of the form |
3692 | // operator "" X (f L) |
3693 | CookedTy = Context.LongDoubleTy; |
3694 | } else { |
3695 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type |
3696 | // unsigned long long, the literal is treated as a call of the form |
3697 | // operator "" X (n ULL) |
3698 | CookedTy = Context.UnsignedLongLongTy; |
3699 | } |
3700 | |
3701 | DeclarationName OpName = |
3702 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
3703 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
3704 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
3705 | |
3706 | SourceLocation TokLoc = Tok.getLocation(); |
3707 | |
3708 | // Perform literal operator lookup to determine if we're building a raw |
3709 | // literal or a cooked one. |
3710 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
3711 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy, |
3712 | /*AllowRaw*/ true, /*AllowTemplate*/ true, |
3713 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
3714 | /*DiagnoseMissing*/ !Literal.isImaginary)) { |
3715 | case LOLR_ErrorNoDiagnostic: |
3716 | // Lookup failure for imaginary constants isn't fatal, there's still the |
3717 | // GNU extension producing _Complex types. |
3718 | break; |
3719 | case LOLR_Error: |
3720 | return ExprError(); |
3721 | case LOLR_Cooked: { |
3722 | Expr *Lit; |
3723 | if (Literal.isFloatingLiteral()) { |
3724 | Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation()); |
3725 | } else { |
3726 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); |
3727 | if (Literal.GetIntegerValue(Val&: ResultVal)) |
3728 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
3729 | << /* Unsigned */ 1; |
3730 | Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy, |
3731 | l: Tok.getLocation()); |
3732 | } |
3733 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
3734 | } |
3735 | |
3736 | case LOLR_Raw: { |
3737 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the |
3738 | // literal is treated as a call of the form |
3739 | // operator "" X ("n") |
3740 | unsigned Length = Literal.getUDSuffixOffset(); |
3741 | QualType StrTy = Context.getConstantArrayType( |
3742 | EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()), |
3743 | ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
3744 | Expr *Lit = |
3745 | StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length), |
3746 | Kind: StringLiteralKind::Ordinary, |
3747 | /*Pascal*/ false, Ty: StrTy, Loc: &TokLoc, NumConcatenated: 1); |
3748 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
3749 | } |
3750 | |
3751 | case LOLR_Template: { |
3752 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator |
3753 | // template), L is treated as a call fo the form |
3754 | // operator "" X <'c1', 'c2', ... 'ck'>() |
3755 | // where n is the source character sequence c1 c2 ... ck. |
3756 | TemplateArgumentListInfo ExplicitArgs; |
3757 | unsigned CharBits = Context.getIntWidth(T: Context.CharTy); |
3758 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); |
3759 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
3760 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { |
3761 | Value = TokSpelling[I]; |
3762 | TemplateArgument Arg(Context, Value, Context.CharTy); |
3763 | TemplateArgumentLocInfo ArgInfo; |
3764 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
3765 | } |
3766 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt, LitEndLoc: TokLoc, |
3767 | ExplicitTemplateArgs: &ExplicitArgs); |
3768 | } |
3769 | case LOLR_StringTemplatePack: |
3770 | llvm_unreachable("unexpected literal operator lookup result" ); |
3771 | } |
3772 | } |
3773 | |
3774 | Expr *Res; |
3775 | |
3776 | if (Literal.isFixedPointLiteral()) { |
3777 | QualType Ty; |
3778 | |
3779 | if (Literal.isAccum) { |
3780 | if (Literal.isHalf) { |
3781 | Ty = Context.ShortAccumTy; |
3782 | } else if (Literal.isLong) { |
3783 | Ty = Context.LongAccumTy; |
3784 | } else { |
3785 | Ty = Context.AccumTy; |
3786 | } |
3787 | } else if (Literal.isFract) { |
3788 | if (Literal.isHalf) { |
3789 | Ty = Context.ShortFractTy; |
3790 | } else if (Literal.isLong) { |
3791 | Ty = Context.LongFractTy; |
3792 | } else { |
3793 | Ty = Context.FractTy; |
3794 | } |
3795 | } |
3796 | |
3797 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty); |
3798 | |
3799 | bool isSigned = !Literal.isUnsigned; |
3800 | unsigned scale = Context.getFixedPointScale(Ty); |
3801 | unsigned bit_width = Context.getTypeInfo(T: Ty).Width; |
3802 | |
3803 | llvm::APInt Val(bit_width, 0, isSigned); |
3804 | bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale); |
3805 | bool ValIsZero = Val.isZero() && !Overflowed; |
3806 | |
3807 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); |
3808 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) |
3809 | // Clause 6.4.4 - The value of a constant shall be in the range of |
3810 | // representable values for its type, with exception for constants of a |
3811 | // fract type with a value of exactly 1; such a constant shall denote |
3812 | // the maximal value for the type. |
3813 | --Val; |
3814 | else if (Val.ugt(RHS: MaxVal) || Overflowed) |
3815 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_too_large_for_fixed_point); |
3816 | |
3817 | Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty, |
3818 | l: Tok.getLocation(), Scale: scale); |
3819 | } else if (Literal.isFloatingLiteral()) { |
3820 | QualType Ty; |
3821 | if (Literal.isHalf){ |
3822 | if (getLangOpts().HLSL || |
3823 | getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts())) |
3824 | Ty = Context.HalfTy; |
3825 | else { |
3826 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_half_const_requires_fp16); |
3827 | return ExprError(); |
3828 | } |
3829 | } else if (Literal.isFloat) |
3830 | Ty = Context.FloatTy; |
3831 | else if (Literal.isLong) |
3832 | Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy; |
3833 | else if (Literal.isFloat16) |
3834 | Ty = Context.Float16Ty; |
3835 | else if (Literal.isFloat128) |
3836 | Ty = Context.Float128Ty; |
3837 | else if (getLangOpts().HLSL) |
3838 | Ty = Context.FloatTy; |
3839 | else |
3840 | Ty = Context.DoubleTy; |
3841 | |
3842 | Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation()); |
3843 | |
3844 | if (Ty == Context.DoubleTy) { |
3845 | if (getLangOpts().SinglePrecisionConstants) { |
3846 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { |
3847 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
3848 | } |
3849 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( |
3850 | Ext: "cl_khr_fp64" , LO: getLangOpts())) { |
3851 | // Impose single-precision float type when cl_khr_fp64 is not enabled. |
3852 | Diag(Loc: Tok.getLocation(), DiagID: diag::warn_double_const_requires_fp64) |
3853 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); |
3854 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
3855 | } |
3856 | } |
3857 | } else if (!Literal.isIntegerLiteral()) { |
3858 | return ExprError(); |
3859 | } else { |
3860 | QualType Ty; |
3861 | |
3862 | // 'z/uz' literals are a C++23 feature. |
3863 | if (Literal.isSizeT) |
3864 | Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus |
3865 | ? getLangOpts().CPlusPlus23 |
3866 | ? diag::warn_cxx20_compat_size_t_suffix |
3867 | : diag::ext_cxx23_size_t_suffix |
3868 | : diag::err_cxx23_size_t_suffix); |
3869 | |
3870 | // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++, |
3871 | // but we do not currently support the suffix in C++ mode because it's not |
3872 | // entirely clear whether WG21 will prefer this suffix to return a library |
3873 | // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb' |
3874 | // literals are a C++ extension. |
3875 | if (Literal.isBitInt) |
3876 | PP.Diag(Loc: Tok.getLocation(), |
3877 | DiagID: getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix |
3878 | : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix |
3879 | : diag::ext_c23_bitint_suffix); |
3880 | |
3881 | // Get the value in the widest-possible width. What is "widest" depends on |
3882 | // whether the literal is a bit-precise integer or not. For a bit-precise |
3883 | // integer type, try to scan the source to determine how many bits are |
3884 | // needed to represent the value. This may seem a bit expensive, but trying |
3885 | // to get the integer value from an overly-wide APInt is *extremely* |
3886 | // expensive, so the naive approach of assuming |
3887 | // llvm::IntegerType::MAX_INT_BITS is a big performance hit. |
3888 | unsigned BitsNeeded = |
3889 | Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( |
3890 | Str: Literal.getLiteralDigits(), Radix: Literal.getRadix()) |
3891 | : Context.getTargetInfo().getIntMaxTWidth(); |
3892 | llvm::APInt ResultVal(BitsNeeded, 0); |
3893 | |
3894 | if (Literal.GetIntegerValue(Val&: ResultVal)) { |
3895 | // If this value didn't fit into uintmax_t, error and force to ull. |
3896 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
3897 | << /* Unsigned */ 1; |
3898 | Ty = Context.UnsignedLongLongTy; |
3899 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && |
3900 | "long long is not intmax_t?" ); |
3901 | } else { |
3902 | // If this value fits into a ULL, try to figure out what else it fits into |
3903 | // according to the rules of C99 6.4.4.1p5. |
3904 | |
3905 | // Octal, Hexadecimal, and integers with a U suffix are allowed to |
3906 | // be an unsigned int. |
3907 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; |
3908 | |
3909 | // HLSL doesn't really have `long` or `long long`. We support the `ll` |
3910 | // suffix for portability of code with C++, but both `l` and `ll` are |
3911 | // 64-bit integer types, and we want the type of `1l` and `1ll` to be the |
3912 | // same. |
3913 | if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) { |
3914 | Literal.isLong = true; |
3915 | Literal.isLongLong = false; |
3916 | } |
3917 | |
3918 | // Check from smallest to largest, picking the smallest type we can. |
3919 | unsigned Width = 0; |
3920 | |
3921 | // Microsoft specific integer suffixes are explicitly sized. |
3922 | if (Literal.MicrosoftInteger) { |
3923 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { |
3924 | Width = 8; |
3925 | Ty = Context.CharTy; |
3926 | } else { |
3927 | Width = Literal.MicrosoftInteger; |
3928 | Ty = Context.getIntTypeForBitwidth(DestWidth: Width, |
3929 | /*Signed=*/!Literal.isUnsigned); |
3930 | } |
3931 | } |
3932 | |
3933 | // Bit-precise integer literals are automagically-sized based on the |
3934 | // width required by the literal. |
3935 | if (Literal.isBitInt) { |
3936 | // The signed version has one more bit for the sign value. There are no |
3937 | // zero-width bit-precise integers, even if the literal value is 0. |
3938 | Width = std::max(a: ResultVal.getActiveBits(), b: 1u) + |
3939 | (Literal.isUnsigned ? 0u : 1u); |
3940 | |
3941 | // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, |
3942 | // and reset the type to the largest supported width. |
3943 | unsigned int MaxBitIntWidth = |
3944 | Context.getTargetInfo().getMaxBitIntWidth(); |
3945 | if (Width > MaxBitIntWidth) { |
3946 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_integer_literal_too_large) |
3947 | << Literal.isUnsigned; |
3948 | Width = MaxBitIntWidth; |
3949 | } |
3950 | |
3951 | // Reset the result value to the smaller APInt and select the correct |
3952 | // type to be used. Note, we zext even for signed values because the |
3953 | // literal itself is always an unsigned value (a preceeding - is a |
3954 | // unary operator, not part of the literal). |
3955 | ResultVal = ResultVal.zextOrTrunc(width: Width); |
3956 | Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width); |
3957 | } |
3958 | |
3959 | // Check C++23 size_t literals. |
3960 | if (Literal.isSizeT) { |
3961 | assert(!Literal.MicrosoftInteger && |
3962 | "size_t literals can't be Microsoft literals" ); |
3963 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( |
3964 | T: Context.getTargetInfo().getSizeType()); |
3965 | |
3966 | // Does it fit in size_t? |
3967 | if (ResultVal.isIntN(N: SizeTSize)) { |
3968 | // Does it fit in ssize_t? |
3969 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) |
3970 | Ty = Context.getSignedSizeType(); |
3971 | else if (AllowUnsigned) |
3972 | Ty = Context.getSizeType(); |
3973 | Width = SizeTSize; |
3974 | } |
3975 | } |
3976 | |
3977 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && |
3978 | !Literal.isSizeT) { |
3979 | // Are int/unsigned possibilities? |
3980 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
3981 | |
3982 | // Does it fit in a unsigned int? |
3983 | if (ResultVal.isIntN(N: IntSize)) { |
3984 | // Does it fit in a signed int? |
3985 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) |
3986 | Ty = Context.IntTy; |
3987 | else if (AllowUnsigned) |
3988 | Ty = Context.UnsignedIntTy; |
3989 | Width = IntSize; |
3990 | } |
3991 | } |
3992 | |
3993 | // Are long/unsigned long possibilities? |
3994 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { |
3995 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); |
3996 | |
3997 | // Does it fit in a unsigned long? |
3998 | if (ResultVal.isIntN(N: LongSize)) { |
3999 | // Does it fit in a signed long? |
4000 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) |
4001 | Ty = Context.LongTy; |
4002 | else if (AllowUnsigned) |
4003 | Ty = Context.UnsignedLongTy; |
4004 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 |
4005 | // is compatible. |
4006 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { |
4007 | const unsigned LongLongSize = |
4008 | Context.getTargetInfo().getLongLongWidth(); |
4009 | Diag(Loc: Tok.getLocation(), |
4010 | DiagID: getLangOpts().CPlusPlus |
4011 | ? Literal.isLong |
4012 | ? diag::warn_old_implicitly_unsigned_long_cxx |
4013 | : /*C++98 UB*/ diag:: |
4014 | ext_old_implicitly_unsigned_long_cxx |
4015 | : diag::warn_old_implicitly_unsigned_long) |
4016 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 |
4017 | : /*will be ill-formed*/ 1); |
4018 | Ty = Context.UnsignedLongTy; |
4019 | } |
4020 | Width = LongSize; |
4021 | } |
4022 | } |
4023 | |
4024 | // Check long long if needed. |
4025 | if (Ty.isNull() && !Literal.isSizeT) { |
4026 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); |
4027 | |
4028 | // Does it fit in a unsigned long long? |
4029 | if (ResultVal.isIntN(N: LongLongSize)) { |
4030 | // Does it fit in a signed long long? |
4031 | // To be compatible with MSVC, hex integer literals ending with the |
4032 | // LL or i64 suffix are always signed in Microsoft mode. |
4033 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || |
4034 | (getLangOpts().MSVCCompat && Literal.isLongLong))) |
4035 | Ty = Context.LongLongTy; |
4036 | else if (AllowUnsigned) |
4037 | Ty = Context.UnsignedLongLongTy; |
4038 | Width = LongLongSize; |
4039 | |
4040 | // 'long long' is a C99 or C++11 feature, whether the literal |
4041 | // explicitly specified 'long long' or we needed the extra width. |
4042 | if (getLangOpts().CPlusPlus) |
4043 | Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus11 |
4044 | ? diag::warn_cxx98_compat_longlong |
4045 | : diag::ext_cxx11_longlong); |
4046 | else if (!getLangOpts().C99) |
4047 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_c99_longlong); |
4048 | } |
4049 | } |
4050 | |
4051 | // If we still couldn't decide a type, we either have 'size_t' literal |
4052 | // that is out of range, or a decimal literal that does not fit in a |
4053 | // signed long long and has no U suffix. |
4054 | if (Ty.isNull()) { |
4055 | if (Literal.isSizeT) |
4056 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_size_t_literal_too_large) |
4057 | << Literal.isUnsigned; |
4058 | else |
4059 | Diag(Loc: Tok.getLocation(), |
4060 | DiagID: diag::ext_integer_literal_too_large_for_signed); |
4061 | Ty = Context.UnsignedLongLongTy; |
4062 | Width = Context.getTargetInfo().getLongLongWidth(); |
4063 | } |
4064 | |
4065 | if (ResultVal.getBitWidth() != Width) |
4066 | ResultVal = ResultVal.trunc(width: Width); |
4067 | } |
4068 | Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation()); |
4069 | } |
4070 | |
4071 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. |
4072 | if (Literal.isImaginary) { |
4073 | Res = new (Context) ImaginaryLiteral(Res, |
4074 | Context.getComplexType(T: Res->getType())); |
4075 | |
4076 | Diag(Loc: Tok.getLocation(), DiagID: diag::ext_imaginary_constant); |
4077 | } |
4078 | return Res; |
4079 | } |
4080 | |
4081 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { |
4082 | assert(E && "ActOnParenExpr() missing expr" ); |
4083 | QualType ExprTy = E->getType(); |
4084 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && |
4085 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) |
4086 | return BuildBuiltinCallExpr(Loc: R, Id: Builtin::BI__arithmetic_fence, CallArgs: E); |
4087 | return new (Context) ParenExpr(L, R, E); |
4088 | } |
4089 | |
4090 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, |
4091 | SourceLocation Loc, |
4092 | SourceRange ArgRange) { |
4093 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in |
4094 | // scalar or vector data type argument..." |
4095 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic |
4096 | // type (C99 6.2.5p18) or void. |
4097 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { |
4098 | S.Diag(Loc, DiagID: diag::err_vecstep_non_scalar_vector_type) |
4099 | << T << ArgRange; |
4100 | return true; |
4101 | } |
4102 | |
4103 | assert((T->isVoidType() || !T->isIncompleteType()) && |
4104 | "Scalar types should always be complete" ); |
4105 | return false; |
4106 | } |
4107 | |
4108 | static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, |
4109 | SourceLocation Loc, |
4110 | SourceRange ArgRange) { |
4111 | // builtin_vectorelements supports both fixed-sized and scalable vectors. |
4112 | if (!T->isVectorType() && !T->isSizelessVectorType()) |
4113 | return S.Diag(Loc, DiagID: diag::err_builtin_non_vector_type) |
4114 | << "" |
4115 | << "__builtin_vectorelements" << T << ArgRange; |
4116 | |
4117 | return false; |
4118 | } |
4119 | |
4120 | static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, |
4121 | SourceLocation Loc, |
4122 | SourceRange ArgRange) { |
4123 | if (S.checkPointerAuthEnabled(Loc, Range: ArgRange)) |
4124 | return true; |
4125 | |
4126 | if (!T->isFunctionType() && !T->isFunctionPointerType() && |
4127 | !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) { |
4128 | S.Diag(Loc, DiagID: diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange; |
4129 | return true; |
4130 | } |
4131 | |
4132 | return false; |
4133 | } |
4134 | |
4135 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, |
4136 | SourceLocation Loc, |
4137 | SourceRange ArgRange, |
4138 | UnaryExprOrTypeTrait TraitKind) { |
4139 | // Invalid types must be hard errors for SFINAE in C++. |
4140 | if (S.LangOpts.CPlusPlus) |
4141 | return true; |
4142 | |
4143 | // C99 6.5.3.4p1: |
4144 | if (T->isFunctionType() && |
4145 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || |
4146 | TraitKind == UETT_PreferredAlignOf)) { |
4147 | // sizeof(function)/alignof(function) is allowed as an extension. |
4148 | S.Diag(Loc, DiagID: diag::ext_sizeof_alignof_function_type) |
4149 | << getTraitSpelling(T: TraitKind) << ArgRange; |
4150 | return false; |
4151 | } |
4152 | |
4153 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where |
4154 | // this is an error (OpenCL v1.1 s6.3.k) |
4155 | if (T->isVoidType()) { |
4156 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type |
4157 | : diag::ext_sizeof_alignof_void_type; |
4158 | S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange; |
4159 | return false; |
4160 | } |
4161 | |
4162 | return true; |
4163 | } |
4164 | |
4165 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, |
4166 | SourceLocation Loc, |
4167 | SourceRange ArgRange, |
4168 | UnaryExprOrTypeTrait TraitKind) { |
4169 | // Reject sizeof(interface) and sizeof(interface<proto>) if the |
4170 | // runtime doesn't allow it. |
4171 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { |
4172 | S.Diag(Loc, DiagID: diag::err_sizeof_nonfragile_interface) |
4173 | << T << (TraitKind == UETT_SizeOf) |
4174 | << ArgRange; |
4175 | return true; |
4176 | } |
4177 | |
4178 | return false; |
4179 | } |
4180 | |
4181 | /// Check whether E is a pointer from a decayed array type (the decayed |
4182 | /// pointer type is equal to T) and emit a warning if it is. |
4183 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, |
4184 | const Expr *E) { |
4185 | // Don't warn if the operation changed the type. |
4186 | if (T != E->getType()) |
4187 | return; |
4188 | |
4189 | // Now look for array decays. |
4190 | const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E); |
4191 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) |
4192 | return; |
4193 | |
4194 | S.Diag(Loc, DiagID: diag::warn_sizeof_array_decay) << ICE->getSourceRange() |
4195 | << ICE->getType() |
4196 | << ICE->getSubExpr()->getType(); |
4197 | } |
4198 | |
4199 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, |
4200 | UnaryExprOrTypeTrait ExprKind) { |
4201 | QualType ExprTy = E->getType(); |
4202 | assert(!ExprTy->isReferenceType()); |
4203 | |
4204 | bool IsUnevaluatedOperand = |
4205 | (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf || |
4206 | ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
4207 | ExprKind == UETT_VecStep); |
4208 | if (IsUnevaluatedOperand) { |
4209 | ExprResult Result = CheckUnevaluatedOperand(E); |
4210 | if (Result.isInvalid()) |
4211 | return true; |
4212 | E = Result.get(); |
4213 | } |
4214 | |
4215 | // The operand for sizeof and alignof is in an unevaluated expression context, |
4216 | // so side effects could result in unintended consequences. |
4217 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes |
4218 | // used to build SFINAE gadgets. |
4219 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? |
4220 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && |
4221 | !E->isInstantiationDependent() && |
4222 | !E->getType()->isVariableArrayType() && |
4223 | E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) |
4224 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context); |
4225 | |
4226 | if (ExprKind == UETT_VecStep) |
4227 | return CheckVecStepTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
4228 | ArgRange: E->getSourceRange()); |
4229 | |
4230 | if (ExprKind == UETT_VectorElements) |
4231 | return CheckVectorElementsTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
4232 | ArgRange: E->getSourceRange()); |
4233 | |
4234 | // Explicitly list some types as extensions. |
4235 | if (!CheckExtensionTraitOperandType(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
4236 | ArgRange: E->getSourceRange(), TraitKind: ExprKind)) |
4237 | return false; |
4238 | |
4239 | // WebAssembly tables are always illegal operands to unary expressions and |
4240 | // type traits. |
4241 | if (Context.getTargetInfo().getTriple().isWasm() && |
4242 | E->getType()->isWebAssemblyTableType()) { |
4243 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_wasm_table_invalid_uett_operand) |
4244 | << getTraitSpelling(T: ExprKind); |
4245 | return true; |
4246 | } |
4247 | |
4248 | // 'alignof' applied to an expression only requires the base element type of |
4249 | // the expression to be complete. 'sizeof' requires the expression's type to |
4250 | // be complete (and will attempt to complete it if it's an array of unknown |
4251 | // bound). |
4252 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
4253 | if (RequireCompleteSizedType( |
4254 | Loc: E->getExprLoc(), T: Context.getBaseElementType(QT: E->getType()), |
4255 | DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4256 | Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange())) |
4257 | return true; |
4258 | } else { |
4259 | if (RequireCompleteSizedExprType( |
4260 | E, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4261 | Args: getTraitSpelling(T: ExprKind), Args: E->getSourceRange())) |
4262 | return true; |
4263 | } |
4264 | |
4265 | // Completing the expression's type may have changed it. |
4266 | ExprTy = E->getType(); |
4267 | assert(!ExprTy->isReferenceType()); |
4268 | |
4269 | if (ExprTy->isFunctionType()) { |
4270 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_function_type) |
4271 | << getTraitSpelling(T: ExprKind) << E->getSourceRange(); |
4272 | return true; |
4273 | } |
4274 | |
4275 | if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprTy, Loc: E->getExprLoc(), |
4276 | ArgRange: E->getSourceRange(), TraitKind: ExprKind)) |
4277 | return true; |
4278 | |
4279 | if (ExprKind == UETT_SizeOf) { |
4280 | if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) { |
4281 | if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) { |
4282 | QualType OType = PVD->getOriginalType(); |
4283 | QualType Type = PVD->getType(); |
4284 | if (Type->isPointerType() && OType->isArrayType()) { |
4285 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_sizeof_array_param) |
4286 | << Type << OType; |
4287 | Diag(Loc: PVD->getLocation(), DiagID: diag::note_declared_at); |
4288 | } |
4289 | } |
4290 | } |
4291 | |
4292 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array |
4293 | // decays into a pointer and returns an unintended result. This is most |
4294 | // likely a typo for "sizeof(array) op x". |
4295 | if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) { |
4296 | warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(), |
4297 | E: BO->getLHS()); |
4298 | warnOnSizeofOnArrayDecay(S&: *this, Loc: BO->getOperatorLoc(), T: BO->getType(), |
4299 | E: BO->getRHS()); |
4300 | } |
4301 | } |
4302 | |
4303 | return false; |
4304 | } |
4305 | |
4306 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { |
4307 | // Cannot know anything else if the expression is dependent. |
4308 | if (E->isTypeDependent()) |
4309 | return false; |
4310 | |
4311 | if (E->getObjectKind() == OK_BitField) { |
4312 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) |
4313 | << 1 << E->getSourceRange(); |
4314 | return true; |
4315 | } |
4316 | |
4317 | ValueDecl *D = nullptr; |
4318 | Expr *Inner = E->IgnoreParens(); |
4319 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) { |
4320 | D = DRE->getDecl(); |
4321 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) { |
4322 | D = ME->getMemberDecl(); |
4323 | } |
4324 | |
4325 | // If it's a field, require the containing struct to have a |
4326 | // complete definition so that we can compute the layout. |
4327 | // |
4328 | // This can happen in C++11 onwards, either by naming the member |
4329 | // in a way that is not transformed into a member access expression |
4330 | // (in an unevaluated operand, for instance), or by naming the member |
4331 | // in a trailing-return-type. |
4332 | // |
4333 | // For the record, since __alignof__ on expressions is a GCC |
4334 | // extension, GCC seems to permit this but always gives the |
4335 | // nonsensical answer 0. |
4336 | // |
4337 | // We don't really need the layout here --- we could instead just |
4338 | // directly check for all the appropriate alignment-lowing |
4339 | // attributes --- but that would require duplicating a lot of |
4340 | // logic that just isn't worth duplicating for such a marginal |
4341 | // use-case. |
4342 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) { |
4343 | // Fast path this check, since we at least know the record has a |
4344 | // definition if we can find a member of it. |
4345 | if (!FD->getParent()->isCompleteDefinition()) { |
4346 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_alignof_member_of_incomplete_type) |
4347 | << E->getSourceRange(); |
4348 | return true; |
4349 | } |
4350 | |
4351 | // Otherwise, if it's a field, and the field doesn't have |
4352 | // reference type, then it must have a complete type (or be a |
4353 | // flexible array member, which we explicitly want to |
4354 | // white-list anyway), which makes the following checks trivial. |
4355 | if (!FD->getType()->isReferenceType()) |
4356 | return false; |
4357 | } |
4358 | |
4359 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
4360 | } |
4361 | |
4362 | bool Sema::CheckVecStepExpr(Expr *E) { |
4363 | E = E->IgnoreParens(); |
4364 | |
4365 | // Cannot know anything else if the expression is dependent. |
4366 | if (E->isTypeDependent()) |
4367 | return false; |
4368 | |
4369 | return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep); |
4370 | } |
4371 | |
4372 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, |
4373 | CapturingScopeInfo *CSI) { |
4374 | assert(T->isVariablyModifiedType()); |
4375 | assert(CSI != nullptr); |
4376 | |
4377 | // We're going to walk down into the type and look for VLA expressions. |
4378 | do { |
4379 | const Type *Ty = T.getTypePtr(); |
4380 | switch (Ty->getTypeClass()) { |
4381 | #define TYPE(Class, Base) |
4382 | #define ABSTRACT_TYPE(Class, Base) |
4383 | #define NON_CANONICAL_TYPE(Class, Base) |
4384 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
4385 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) |
4386 | #include "clang/AST/TypeNodes.inc" |
4387 | T = QualType(); |
4388 | break; |
4389 | // These types are never variably-modified. |
4390 | case Type::Builtin: |
4391 | case Type::Complex: |
4392 | case Type::Vector: |
4393 | case Type::ExtVector: |
4394 | case Type::ConstantMatrix: |
4395 | case Type::Record: |
4396 | case Type::Enum: |
4397 | case Type::TemplateSpecialization: |
4398 | case Type::ObjCObject: |
4399 | case Type::ObjCInterface: |
4400 | case Type::ObjCObjectPointer: |
4401 | case Type::ObjCTypeParam: |
4402 | case Type::Pipe: |
4403 | case Type::BitInt: |
4404 | llvm_unreachable("type class is never variably-modified!" ); |
4405 | case Type::Elaborated: |
4406 | T = cast<ElaboratedType>(Val: Ty)->getNamedType(); |
4407 | break; |
4408 | case Type::Adjusted: |
4409 | T = cast<AdjustedType>(Val: Ty)->getOriginalType(); |
4410 | break; |
4411 | case Type::Decayed: |
4412 | T = cast<DecayedType>(Val: Ty)->getPointeeType(); |
4413 | break; |
4414 | case Type::ArrayParameter: |
4415 | T = cast<ArrayParameterType>(Val: Ty)->getElementType(); |
4416 | break; |
4417 | case Type::Pointer: |
4418 | T = cast<PointerType>(Val: Ty)->getPointeeType(); |
4419 | break; |
4420 | case Type::BlockPointer: |
4421 | T = cast<BlockPointerType>(Val: Ty)->getPointeeType(); |
4422 | break; |
4423 | case Type::LValueReference: |
4424 | case Type::RValueReference: |
4425 | T = cast<ReferenceType>(Val: Ty)->getPointeeType(); |
4426 | break; |
4427 | case Type::MemberPointer: |
4428 | T = cast<MemberPointerType>(Val: Ty)->getPointeeType(); |
4429 | break; |
4430 | case Type::ConstantArray: |
4431 | case Type::IncompleteArray: |
4432 | // Losing element qualification here is fine. |
4433 | T = cast<ArrayType>(Val: Ty)->getElementType(); |
4434 | break; |
4435 | case Type::VariableArray: { |
4436 | // Losing element qualification here is fine. |
4437 | const VariableArrayType *VAT = cast<VariableArrayType>(Val: Ty); |
4438 | |
4439 | // Unknown size indication requires no size computation. |
4440 | // Otherwise, evaluate and record it. |
4441 | auto Size = VAT->getSizeExpr(); |
4442 | if (Size && !CSI->isVLATypeCaptured(VAT) && |
4443 | (isa<CapturedRegionScopeInfo>(Val: CSI) || isa<LambdaScopeInfo>(Val: CSI))) |
4444 | CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType()); |
4445 | |
4446 | T = VAT->getElementType(); |
4447 | break; |
4448 | } |
4449 | case Type::FunctionProto: |
4450 | case Type::FunctionNoProto: |
4451 | T = cast<FunctionType>(Val: Ty)->getReturnType(); |
4452 | break; |
4453 | case Type::Paren: |
4454 | case Type::TypeOf: |
4455 | case Type::UnaryTransform: |
4456 | case Type::Attributed: |
4457 | case Type::BTFTagAttributed: |
4458 | case Type::SubstTemplateTypeParm: |
4459 | case Type::MacroQualified: |
4460 | case Type::CountAttributed: |
4461 | // Keep walking after single level desugaring. |
4462 | T = T.getSingleStepDesugaredType(Context); |
4463 | break; |
4464 | case Type::Typedef: |
4465 | T = cast<TypedefType>(Val: Ty)->desugar(); |
4466 | break; |
4467 | case Type::Decltype: |
4468 | T = cast<DecltypeType>(Val: Ty)->desugar(); |
4469 | break; |
4470 | case Type::PackIndexing: |
4471 | T = cast<PackIndexingType>(Val: Ty)->desugar(); |
4472 | break; |
4473 | case Type::Using: |
4474 | T = cast<UsingType>(Val: Ty)->desugar(); |
4475 | break; |
4476 | case Type::Auto: |
4477 | case Type::DeducedTemplateSpecialization: |
4478 | T = cast<DeducedType>(Val: Ty)->getDeducedType(); |
4479 | break; |
4480 | case Type::TypeOfExpr: |
4481 | T = cast<TypeOfExprType>(Val: Ty)->getUnderlyingExpr()->getType(); |
4482 | break; |
4483 | case Type::Atomic: |
4484 | T = cast<AtomicType>(Val: Ty)->getValueType(); |
4485 | break; |
4486 | } |
4487 | } while (!T.isNull() && T->isVariablyModifiedType()); |
4488 | } |
4489 | |
4490 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, |
4491 | SourceLocation OpLoc, |
4492 | SourceRange ExprRange, |
4493 | UnaryExprOrTypeTrait ExprKind, |
4494 | StringRef KWName) { |
4495 | if (ExprType->isDependentType()) |
4496 | return false; |
4497 | |
4498 | // C++ [expr.sizeof]p2: |
4499 | // When applied to a reference or a reference type, the result |
4500 | // is the size of the referenced type. |
4501 | // C++11 [expr.alignof]p3: |
4502 | // When alignof is applied to a reference type, the result |
4503 | // shall be the alignment of the referenced type. |
4504 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) |
4505 | ExprType = Ref->getPointeeType(); |
4506 | |
4507 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: |
4508 | // When alignof or _Alignof is applied to an array type, the result |
4509 | // is the alignment of the element type. |
4510 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
4511 | ExprKind == UETT_OpenMPRequiredSimdAlign) { |
4512 | // If the trait is 'alignof' in C before C2y, the ability to apply the |
4513 | // trait to an incomplete array is an extension. |
4514 | if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus && |
4515 | ExprType->isIncompleteArrayType()) |
4516 | Diag(Loc: OpLoc, DiagID: getLangOpts().C2y |
4517 | ? diag::warn_c2y_compat_alignof_incomplete_array |
4518 | : diag::ext_c2y_alignof_incomplete_array); |
4519 | ExprType = Context.getBaseElementType(QT: ExprType); |
4520 | } |
4521 | |
4522 | if (ExprKind == UETT_VecStep) |
4523 | return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange); |
4524 | |
4525 | if (ExprKind == UETT_VectorElements) |
4526 | return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
4527 | ArgRange: ExprRange); |
4528 | |
4529 | if (ExprKind == UETT_PtrAuthTypeDiscriminator) |
4530 | return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
4531 | ArgRange: ExprRange); |
4532 | |
4533 | // Explicitly list some types as extensions. |
4534 | if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
4535 | TraitKind: ExprKind)) |
4536 | return false; |
4537 | |
4538 | if (RequireCompleteSizedType( |
4539 | Loc: OpLoc, T: ExprType, DiagID: diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4540 | Args: KWName, Args: ExprRange)) |
4541 | return true; |
4542 | |
4543 | if (ExprType->isFunctionType()) { |
4544 | Diag(Loc: OpLoc, DiagID: diag::err_sizeof_alignof_function_type) << KWName << ExprRange; |
4545 | return true; |
4546 | } |
4547 | |
4548 | // WebAssembly tables are always illegal operands to unary expressions and |
4549 | // type traits. |
4550 | if (Context.getTargetInfo().getTriple().isWasm() && |
4551 | ExprType->isWebAssemblyTableType()) { |
4552 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_invalid_uett_operand) |
4553 | << getTraitSpelling(T: ExprKind); |
4554 | return true; |
4555 | } |
4556 | |
4557 | if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
4558 | TraitKind: ExprKind)) |
4559 | return true; |
4560 | |
4561 | if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) { |
4562 | if (auto *TT = ExprType->getAs<TypedefType>()) { |
4563 | for (auto I = FunctionScopes.rbegin(), |
4564 | E = std::prev(x: FunctionScopes.rend()); |
4565 | I != E; ++I) { |
4566 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
4567 | if (CSI == nullptr) |
4568 | break; |
4569 | DeclContext *DC = nullptr; |
4570 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
4571 | DC = LSI->CallOperator; |
4572 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
4573 | DC = CRSI->TheCapturedDecl; |
4574 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
4575 | DC = BSI->TheDecl; |
4576 | if (DC) { |
4577 | if (DC->containsDecl(D: TT->getDecl())) |
4578 | break; |
4579 | captureVariablyModifiedType(Context, T: ExprType, CSI); |
4580 | } |
4581 | } |
4582 | } |
4583 | } |
4584 | |
4585 | return false; |
4586 | } |
4587 | |
4588 | ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
4589 | SourceLocation OpLoc, |
4590 | UnaryExprOrTypeTrait ExprKind, |
4591 | SourceRange R) { |
4592 | if (!TInfo) |
4593 | return ExprError(); |
4594 | |
4595 | QualType T = TInfo->getType(); |
4596 | |
4597 | if (!T->isDependentType() && |
4598 | CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind, |
4599 | KWName: getTraitSpelling(T: ExprKind))) |
4600 | return ExprError(); |
4601 | |
4602 | // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to |
4603 | // properly deal with VLAs in nested calls of sizeof and typeof. |
4604 | if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && |
4605 | TInfo->getType()->isVariablyModifiedType()) |
4606 | TInfo = TransformToPotentiallyEvaluated(TInfo); |
4607 | |
4608 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
4609 | return new (Context) UnaryExprOrTypeTraitExpr( |
4610 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); |
4611 | } |
4612 | |
4613 | ExprResult |
4614 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
4615 | UnaryExprOrTypeTrait ExprKind) { |
4616 | ExprResult PE = CheckPlaceholderExpr(E); |
4617 | if (PE.isInvalid()) |
4618 | return ExprError(); |
4619 | |
4620 | E = PE.get(); |
4621 | |
4622 | // Verify that the operand is valid. |
4623 | bool isInvalid = false; |
4624 | if (E->isTypeDependent()) { |
4625 | // Delay type-checking for type-dependent expressions. |
4626 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
4627 | isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind); |
4628 | } else if (ExprKind == UETT_VecStep) { |
4629 | isInvalid = CheckVecStepExpr(E); |
4630 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { |
4631 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_openmp_default_simd_align_expr); |
4632 | isInvalid = true; |
4633 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. |
4634 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield) << 0; |
4635 | isInvalid = true; |
4636 | } else if (ExprKind == UETT_VectorElements) { |
4637 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VectorElements); |
4638 | } else { |
4639 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_SizeOf); |
4640 | } |
4641 | |
4642 | if (isInvalid) |
4643 | return ExprError(); |
4644 | |
4645 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { |
4646 | PE = TransformToPotentiallyEvaluated(E); |
4647 | if (PE.isInvalid()) return ExprError(); |
4648 | E = PE.get(); |
4649 | } |
4650 | |
4651 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
4652 | return new (Context) UnaryExprOrTypeTraitExpr( |
4653 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); |
4654 | } |
4655 | |
4656 | ExprResult |
4657 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
4658 | UnaryExprOrTypeTrait ExprKind, bool IsType, |
4659 | void *TyOrEx, SourceRange ArgRange) { |
4660 | // If error parsing type, ignore. |
4661 | if (!TyOrEx) return ExprError(); |
4662 | |
4663 | if (IsType) { |
4664 | TypeSourceInfo *TInfo; |
4665 | (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo); |
4666 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange); |
4667 | } |
4668 | |
4669 | Expr *ArgEx = (Expr *)TyOrEx; |
4670 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind); |
4671 | return Result; |
4672 | } |
4673 | |
4674 | bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, |
4675 | SourceLocation OpLoc, SourceRange R) { |
4676 | if (!TInfo) |
4677 | return true; |
4678 | return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R, |
4679 | ExprKind: UETT_AlignOf, KWName); |
4680 | } |
4681 | |
4682 | bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, |
4683 | SourceLocation OpLoc, SourceRange R) { |
4684 | TypeSourceInfo *TInfo; |
4685 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()), |
4686 | TInfo: &TInfo); |
4687 | return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R); |
4688 | } |
4689 | |
4690 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, |
4691 | bool IsReal) { |
4692 | if (V.get()->isTypeDependent()) |
4693 | return S.Context.DependentTy; |
4694 | |
4695 | // _Real and _Imag are only l-values for normal l-values. |
4696 | if (V.get()->getObjectKind() != OK_Ordinary) { |
4697 | V = S.DefaultLvalueConversion(E: V.get()); |
4698 | if (V.isInvalid()) |
4699 | return QualType(); |
4700 | } |
4701 | |
4702 | // These operators return the element type of a complex type. |
4703 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) |
4704 | return CT->getElementType(); |
4705 | |
4706 | // Otherwise they pass through real integer and floating point types here. |
4707 | if (V.get()->getType()->isArithmeticType()) |
4708 | return V.get()->getType(); |
4709 | |
4710 | // Test for placeholders. |
4711 | ExprResult PR = S.CheckPlaceholderExpr(E: V.get()); |
4712 | if (PR.isInvalid()) return QualType(); |
4713 | if (PR.get() != V.get()) { |
4714 | V = PR; |
4715 | return CheckRealImagOperand(S, V, Loc, IsReal); |
4716 | } |
4717 | |
4718 | // Reject anything else. |
4719 | S.Diag(Loc, DiagID: diag::err_realimag_invalid_type) << V.get()->getType() |
4720 | << (IsReal ? "__real" : "__imag" ); |
4721 | return QualType(); |
4722 | } |
4723 | |
4724 | |
4725 | |
4726 | ExprResult |
4727 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
4728 | tok::TokenKind Kind, Expr *Input) { |
4729 | UnaryOperatorKind Opc; |
4730 | switch (Kind) { |
4731 | default: llvm_unreachable("Unknown unary op!" ); |
4732 | case tok::plusplus: Opc = UO_PostInc; break; |
4733 | case tok::minusminus: Opc = UO_PostDec; break; |
4734 | } |
4735 | |
4736 | // Since this might is a postfix expression, get rid of ParenListExprs. |
4737 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input); |
4738 | if (Result.isInvalid()) return ExprError(); |
4739 | Input = Result.get(); |
4740 | |
4741 | return BuildUnaryOp(S, OpLoc, Opc, Input); |
4742 | } |
4743 | |
4744 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. |
4745 | /// |
4746 | /// \return true on error |
4747 | static bool checkArithmeticOnObjCPointer(Sema &S, |
4748 | SourceLocation opLoc, |
4749 | Expr *op) { |
4750 | assert(op->getType()->isObjCObjectPointerType()); |
4751 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && |
4752 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) |
4753 | return false; |
4754 | |
4755 | S.Diag(Loc: opLoc, DiagID: diag::err_arithmetic_nonfragile_interface) |
4756 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() |
4757 | << op->getSourceRange(); |
4758 | return true; |
4759 | } |
4760 | |
4761 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { |
4762 | auto *BaseNoParens = Base->IgnoreParens(); |
4763 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens)) |
4764 | return MSProp->getPropertyDecl()->getType()->isArrayType(); |
4765 | return isa<MSPropertySubscriptExpr>(Val: BaseNoParens); |
4766 | } |
4767 | |
4768 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. |
4769 | // Typically this is DependentTy, but can sometimes be more precise. |
4770 | // |
4771 | // There are cases when we could determine a non-dependent type: |
4772 | // - LHS and RHS may have non-dependent types despite being type-dependent |
4773 | // (e.g. unbounded array static members of the current instantiation) |
4774 | // - one may be a dependent-sized array with known element type |
4775 | // - one may be a dependent-typed valid index (enum in current instantiation) |
4776 | // |
4777 | // We *always* return a dependent type, in such cases it is DependentTy. |
4778 | // This avoids creating type-dependent expressions with non-dependent types. |
4779 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 |
4780 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, |
4781 | const ASTContext &Ctx) { |
4782 | assert(LHS->isTypeDependent() || RHS->isTypeDependent()); |
4783 | QualType LTy = LHS->getType(), RTy = RHS->getType(); |
4784 | QualType Result = Ctx.DependentTy; |
4785 | if (RTy->isIntegralOrUnscopedEnumerationType()) { |
4786 | if (const PointerType *PT = LTy->getAs<PointerType>()) |
4787 | Result = PT->getPointeeType(); |
4788 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) |
4789 | Result = AT->getElementType(); |
4790 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { |
4791 | if (const PointerType *PT = RTy->getAs<PointerType>()) |
4792 | Result = PT->getPointeeType(); |
4793 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) |
4794 | Result = AT->getElementType(); |
4795 | } |
4796 | // Ensure we return a dependent type. |
4797 | return Result->isDependentType() ? Result : Ctx.DependentTy; |
4798 | } |
4799 | |
4800 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, |
4801 | SourceLocation lbLoc, |
4802 | MultiExprArg ArgExprs, |
4803 | SourceLocation rbLoc) { |
4804 | |
4805 | if (base && !base->getType().isNull() && |
4806 | base->hasPlaceholderType(K: BuiltinType::ArraySection)) { |
4807 | auto *AS = cast<ArraySectionExpr>(Val: base); |
4808 | if (AS->isOMPArraySection()) |
4809 | return OpenMP().ActOnOMPArraySectionExpr( |
4810 | Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(), |
4811 | /*Length*/ nullptr, |
4812 | /*Stride=*/nullptr, RBLoc: rbLoc); |
4813 | |
4814 | return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), |
4815 | ColonLocFirst: SourceLocation(), /*Length*/ nullptr, |
4816 | RBLoc: rbLoc); |
4817 | } |
4818 | |
4819 | // Since this might be a postfix expression, get rid of ParenListExprs. |
4820 | if (isa<ParenListExpr>(Val: base)) { |
4821 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base); |
4822 | if (result.isInvalid()) |
4823 | return ExprError(); |
4824 | base = result.get(); |
4825 | } |
4826 | |
4827 | // Check if base and idx form a MatrixSubscriptExpr. |
4828 | // |
4829 | // Helper to check for comma expressions, which are not allowed as indices for |
4830 | // matrix subscript expressions. |
4831 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { |
4832 | if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) { |
4833 | Diag(Loc: E->getExprLoc(), DiagID: diag::err_matrix_subscript_comma) |
4834 | << SourceRange(base->getBeginLoc(), rbLoc); |
4835 | return true; |
4836 | } |
4837 | return false; |
4838 | }; |
4839 | // The matrix subscript operator ([][])is considered a single operator. |
4840 | // Separating the index expressions by parenthesis is not allowed. |
4841 | if (base && !base->getType().isNull() && |
4842 | base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) && |
4843 | !isa<MatrixSubscriptExpr>(Val: base)) { |
4844 | Diag(Loc: base->getExprLoc(), DiagID: diag::err_matrix_separate_incomplete_index) |
4845 | << SourceRange(base->getBeginLoc(), rbLoc); |
4846 | return ExprError(); |
4847 | } |
4848 | // If the base is a MatrixSubscriptExpr, try to create a new |
4849 | // MatrixSubscriptExpr. |
4850 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base); |
4851 | if (matSubscriptE) { |
4852 | assert(ArgExprs.size() == 1); |
4853 | if (CheckAndReportCommaError(ArgExprs.front())) |
4854 | return ExprError(); |
4855 | |
4856 | assert(matSubscriptE->isIncomplete() && |
4857 | "base has to be an incomplete matrix subscript" ); |
4858 | return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(), |
4859 | RowIdx: matSubscriptE->getRowIdx(), |
4860 | ColumnIdx: ArgExprs.front(), RBLoc: rbLoc); |
4861 | } |
4862 | if (base->getType()->isWebAssemblyTableType()) { |
4863 | Diag(Loc: base->getExprLoc(), DiagID: diag::err_wasm_table_art) |
4864 | << SourceRange(base->getBeginLoc(), rbLoc) << 3; |
4865 | return ExprError(); |
4866 | } |
4867 | |
4868 | // Handle any non-overload placeholder types in the base and index |
4869 | // expressions. We can't handle overloads here because the other |
4870 | // operand might be an overloadable type, in which case the overload |
4871 | // resolution for the operator overload should get the first crack |
4872 | // at the overload. |
4873 | bool IsMSPropertySubscript = false; |
4874 | if (base->getType()->isNonOverloadPlaceholderType()) { |
4875 | IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base); |
4876 | if (!IsMSPropertySubscript) { |
4877 | ExprResult result = CheckPlaceholderExpr(E: base); |
4878 | if (result.isInvalid()) |
4879 | return ExprError(); |
4880 | base = result.get(); |
4881 | } |
4882 | } |
4883 | |
4884 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. |
4885 | if (base->getType()->isMatrixType()) { |
4886 | assert(ArgExprs.size() == 1); |
4887 | if (CheckAndReportCommaError(ArgExprs.front())) |
4888 | return ExprError(); |
4889 | |
4890 | return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr, |
4891 | RBLoc: rbLoc); |
4892 | } |
4893 | |
4894 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { |
4895 | Expr *idx = ArgExprs[0]; |
4896 | if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) || |
4897 | (isa<CXXOperatorCallExpr>(Val: idx) && |
4898 | cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) { |
4899 | Diag(Loc: idx->getExprLoc(), DiagID: diag::warn_deprecated_comma_subscript) |
4900 | << SourceRange(base->getBeginLoc(), rbLoc); |
4901 | } |
4902 | } |
4903 | |
4904 | if (ArgExprs.size() == 1 && |
4905 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { |
4906 | ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]); |
4907 | if (result.isInvalid()) |
4908 | return ExprError(); |
4909 | ArgExprs[0] = result.get(); |
4910 | } else { |
4911 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
4912 | return ExprError(); |
4913 | } |
4914 | |
4915 | // Build an unanalyzed expression if either operand is type-dependent. |
4916 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && |
4917 | (base->isTypeDependent() || |
4918 | Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) && |
4919 | !isa<PackExpansionExpr>(Val: ArgExprs[0])) { |
4920 | return new (Context) ArraySubscriptExpr( |
4921 | base, ArgExprs.front(), |
4922 | getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()), |
4923 | VK_LValue, OK_Ordinary, rbLoc); |
4924 | } |
4925 | |
4926 | // MSDN, property (C++) |
4927 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx |
4928 | // This attribute can also be used in the declaration of an empty array in a |
4929 | // class or structure definition. For example: |
4930 | // __declspec(property(get=GetX, put=PutX)) int x[]; |
4931 | // The above statement indicates that x[] can be used with one or more array |
4932 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), |
4933 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); |
4934 | if (IsMSPropertySubscript) { |
4935 | assert(ArgExprs.size() == 1); |
4936 | // Build MS property subscript expression if base is MS property reference |
4937 | // or MS property subscript. |
4938 | return new (Context) |
4939 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, |
4940 | VK_LValue, OK_Ordinary, rbLoc); |
4941 | } |
4942 | |
4943 | // Use C++ overloaded-operator rules if either operand has record |
4944 | // type. The spec says to do this if either type is *overloadable*, |
4945 | // but enum types can't declare subscript operators or conversion |
4946 | // operators, so there's nothing interesting for overload resolution |
4947 | // to do if there aren't any record types involved. |
4948 | // |
4949 | // ObjC pointers have their own subscripting logic that is not tied |
4950 | // to overload resolution and so should not take this path. |
4951 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && |
4952 | ((base->getType()->isRecordType() || |
4953 | (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) || |
4954 | ArgExprs[0]->getType()->isRecordType())))) { |
4955 | return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs); |
4956 | } |
4957 | |
4958 | ExprResult Res = |
4959 | CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc); |
4960 | |
4961 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get())) |
4962 | CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get())); |
4963 | |
4964 | return Res; |
4965 | } |
4966 | |
4967 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { |
4968 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty); |
4969 | InitializationKind Kind = |
4970 | InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation()); |
4971 | InitializationSequence InitSeq(*this, Entity, Kind, E); |
4972 | return InitSeq.Perform(S&: *this, Entity, Kind, Args: E); |
4973 | } |
4974 | |
4975 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, |
4976 | Expr *ColumnIdx, |
4977 | SourceLocation RBLoc) { |
4978 | ExprResult BaseR = CheckPlaceholderExpr(E: Base); |
4979 | if (BaseR.isInvalid()) |
4980 | return BaseR; |
4981 | Base = BaseR.get(); |
4982 | |
4983 | ExprResult RowR = CheckPlaceholderExpr(E: RowIdx); |
4984 | if (RowR.isInvalid()) |
4985 | return RowR; |
4986 | RowIdx = RowR.get(); |
4987 | |
4988 | if (!ColumnIdx) |
4989 | return new (Context) MatrixSubscriptExpr( |
4990 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); |
4991 | |
4992 | // Build an unanalyzed expression if any of the operands is type-dependent. |
4993 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || |
4994 | ColumnIdx->isTypeDependent()) |
4995 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
4996 | Context.DependentTy, RBLoc); |
4997 | |
4998 | ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx); |
4999 | if (ColumnR.isInvalid()) |
5000 | return ColumnR; |
5001 | ColumnIdx = ColumnR.get(); |
5002 | |
5003 | // Check that IndexExpr is an integer expression. If it is a constant |
5004 | // expression, check that it is less than Dim (= the number of elements in the |
5005 | // corresponding dimension). |
5006 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, |
5007 | bool IsColumnIdx) -> Expr * { |
5008 | if (!IndexExpr->getType()->isIntegerType() && |
5009 | !IndexExpr->isTypeDependent()) { |
5010 | Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_not_integer) |
5011 | << IsColumnIdx; |
5012 | return nullptr; |
5013 | } |
5014 | |
5015 | if (std::optional<llvm::APSInt> Idx = |
5016 | IndexExpr->getIntegerConstantExpr(Ctx: Context)) { |
5017 | if ((*Idx < 0 || *Idx >= Dim)) { |
5018 | Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_matrix_index_outside_range) |
5019 | << IsColumnIdx << Dim; |
5020 | return nullptr; |
5021 | } |
5022 | } |
5023 | |
5024 | ExprResult ConvExpr = |
5025 | tryConvertExprToType(E: IndexExpr, Ty: Context.getSizeType()); |
5026 | assert(!ConvExpr.isInvalid() && |
5027 | "should be able to convert any integer type to size type" ); |
5028 | return ConvExpr.get(); |
5029 | }; |
5030 | |
5031 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); |
5032 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); |
5033 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); |
5034 | if (!RowIdx || !ColumnIdx) |
5035 | return ExprError(); |
5036 | |
5037 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
5038 | MTy->getElementType(), RBLoc); |
5039 | } |
5040 | |
5041 | void Sema::CheckAddressOfNoDeref(const Expr *E) { |
5042 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
5043 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); |
5044 | |
5045 | // For expressions like `&(*s).b`, the base is recorded and what should be |
5046 | // checked. |
5047 | const MemberExpr *Member = nullptr; |
5048 | while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow()) |
5049 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); |
5050 | |
5051 | LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr); |
5052 | } |
5053 | |
5054 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { |
5055 | if (isUnevaluatedContext()) |
5056 | return; |
5057 | |
5058 | QualType ResultTy = E->getType(); |
5059 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
5060 | |
5061 | // Bail if the element is an array since it is not memory access. |
5062 | if (isa<ArrayType>(Val: ResultTy)) |
5063 | return; |
5064 | |
5065 | if (ResultTy->hasAttr(AK: attr::NoDeref)) { |
5066 | LastRecord.PossibleDerefs.insert(Ptr: E); |
5067 | return; |
5068 | } |
5069 | |
5070 | // Check if the base type is a pointer to a member access of a struct |
5071 | // marked with noderef. |
5072 | const Expr *Base = E->getBase(); |
5073 | QualType BaseTy = Base->getType(); |
5074 | if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy))) |
5075 | // Not a pointer access |
5076 | return; |
5077 | |
5078 | const MemberExpr *Member = nullptr; |
5079 | while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) && |
5080 | Member->isArrow()) |
5081 | Base = Member->getBase(); |
5082 | |
5083 | if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) { |
5084 | if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref)) |
5085 | LastRecord.PossibleDerefs.insert(Ptr: E); |
5086 | } |
5087 | } |
5088 | |
5089 | ExprResult |
5090 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
5091 | Expr *Idx, SourceLocation RLoc) { |
5092 | Expr *LHSExp = Base; |
5093 | Expr *RHSExp = Idx; |
5094 | |
5095 | ExprValueKind VK = VK_LValue; |
5096 | ExprObjectKind OK = OK_Ordinary; |
5097 | |
5098 | // Per C++ core issue 1213, the result is an xvalue if either operand is |
5099 | // a non-lvalue array, and an lvalue otherwise. |
5100 | if (getLangOpts().CPlusPlus11) { |
5101 | for (auto *Op : {LHSExp, RHSExp}) { |
5102 | Op = Op->IgnoreImplicit(); |
5103 | if (Op->getType()->isArrayType() && !Op->isLValue()) |
5104 | VK = VK_XValue; |
5105 | } |
5106 | } |
5107 | |
5108 | // Perform default conversions. |
5109 | if (!LHSExp->getType()->isSubscriptableVectorType()) { |
5110 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp); |
5111 | if (Result.isInvalid()) |
5112 | return ExprError(); |
5113 | LHSExp = Result.get(); |
5114 | } |
5115 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp); |
5116 | if (Result.isInvalid()) |
5117 | return ExprError(); |
5118 | RHSExp = Result.get(); |
5119 | |
5120 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); |
5121 | |
5122 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent |
5123 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be |
5124 | // in the subscript position. As a result, we need to derive the array base |
5125 | // and index from the expression types. |
5126 | Expr *BaseExpr, *IndexExpr; |
5127 | QualType ResultType; |
5128 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { |
5129 | BaseExpr = LHSExp; |
5130 | IndexExpr = RHSExp; |
5131 | ResultType = |
5132 | getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext()); |
5133 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { |
5134 | BaseExpr = LHSExp; |
5135 | IndexExpr = RHSExp; |
5136 | ResultType = PTy->getPointeeType(); |
5137 | } else if (const ObjCObjectPointerType *PTy = |
5138 | LHSTy->getAs<ObjCObjectPointerType>()) { |
5139 | BaseExpr = LHSExp; |
5140 | IndexExpr = RHSExp; |
5141 | |
5142 | // Use custom logic if this should be the pseudo-object subscript |
5143 | // expression. |
5144 | if (!LangOpts.isSubscriptPointerArithmetic()) |
5145 | return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr, |
5146 | getterMethod: nullptr, setterMethod: nullptr); |
5147 | |
5148 | ResultType = PTy->getPointeeType(); |
5149 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { |
5150 | // Handle the uncommon case of "123[Ptr]". |
5151 | BaseExpr = RHSExp; |
5152 | IndexExpr = LHSExp; |
5153 | ResultType = PTy->getPointeeType(); |
5154 | } else if (const ObjCObjectPointerType *PTy = |
5155 | RHSTy->getAs<ObjCObjectPointerType>()) { |
5156 | // Handle the uncommon case of "123[Ptr]". |
5157 | BaseExpr = RHSExp; |
5158 | IndexExpr = LHSExp; |
5159 | ResultType = PTy->getPointeeType(); |
5160 | if (!LangOpts.isSubscriptPointerArithmetic()) { |
5161 | Diag(Loc: LLoc, DiagID: diag::err_subscript_nonfragile_interface) |
5162 | << ResultType << BaseExpr->getSourceRange(); |
5163 | return ExprError(); |
5164 | } |
5165 | } else if (LHSTy->isSubscriptableVectorType()) { |
5166 | if (LHSTy->isBuiltinType() && |
5167 | LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) { |
5168 | const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); |
5169 | if (BTy->isSVEBool()) |
5170 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_subscript_svbool_t) |
5171 | << LHSExp->getSourceRange() |
5172 | << RHSExp->getSourceRange()); |
5173 | ResultType = BTy->getSveEltType(Ctx: Context); |
5174 | } else { |
5175 | const VectorType *VTy = LHSTy->getAs<VectorType>(); |
5176 | ResultType = VTy->getElementType(); |
5177 | } |
5178 | BaseExpr = LHSExp; // vectors: V[123] |
5179 | IndexExpr = RHSExp; |
5180 | // We apply C++ DR1213 to vector subscripting too. |
5181 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { |
5182 | ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp); |
5183 | if (Materialized.isInvalid()) |
5184 | return ExprError(); |
5185 | LHSExp = Materialized.get(); |
5186 | } |
5187 | VK = LHSExp->getValueKind(); |
5188 | if (VK != VK_PRValue) |
5189 | OK = OK_VectorComponent; |
5190 | |
5191 | QualType BaseType = BaseExpr->getType(); |
5192 | Qualifiers BaseQuals = BaseType.getQualifiers(); |
5193 | Qualifiers MemberQuals = ResultType.getQualifiers(); |
5194 | Qualifiers Combined = BaseQuals + MemberQuals; |
5195 | if (Combined != MemberQuals) |
5196 | ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined); |
5197 | } else if (LHSTy->isArrayType()) { |
5198 | // If we see an array that wasn't promoted by |
5199 | // DefaultFunctionArrayLvalueConversion, it must be an array that |
5200 | // wasn't promoted because of the C90 rule that doesn't |
5201 | // allow promoting non-lvalue arrays. Warn, then |
5202 | // force the promotion here. |
5203 | Diag(Loc: LHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue) |
5204 | << LHSExp->getSourceRange(); |
5205 | LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy), |
5206 | CK: CK_ArrayToPointerDecay).get(); |
5207 | LHSTy = LHSExp->getType(); |
5208 | |
5209 | BaseExpr = LHSExp; |
5210 | IndexExpr = RHSExp; |
5211 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); |
5212 | } else if (RHSTy->isArrayType()) { |
5213 | // Same as previous, except for 123[f().a] case |
5214 | Diag(Loc: RHSExp->getBeginLoc(), DiagID: diag::ext_subscript_non_lvalue) |
5215 | << RHSExp->getSourceRange(); |
5216 | RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy), |
5217 | CK: CK_ArrayToPointerDecay).get(); |
5218 | RHSTy = RHSExp->getType(); |
5219 | |
5220 | BaseExpr = RHSExp; |
5221 | IndexExpr = LHSExp; |
5222 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); |
5223 | } else { |
5224 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_value) |
5225 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); |
5226 | } |
5227 | // C99 6.5.2.1p1 |
5228 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) |
5229 | return ExprError(Diag(Loc: LLoc, DiagID: diag::err_typecheck_subscript_not_integer) |
5230 | << IndexExpr->getSourceRange()); |
5231 | |
5232 | if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
5233 | IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) && |
5234 | !IndexExpr->isTypeDependent()) { |
5235 | std::optional<llvm::APSInt> IntegerContantExpr = |
5236 | IndexExpr->getIntegerConstantExpr(Ctx: getASTContext()); |
5237 | if (!IntegerContantExpr.has_value() || |
5238 | IntegerContantExpr.value().isNegative()) |
5239 | Diag(Loc: LLoc, DiagID: diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); |
5240 | } |
5241 | |
5242 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, |
5243 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object |
5244 | // type. Note that Functions are not objects, and that (in C99 parlance) |
5245 | // incomplete types are not object types. |
5246 | if (ResultType->isFunctionType()) { |
5247 | Diag(Loc: BaseExpr->getBeginLoc(), DiagID: diag::err_subscript_function_type) |
5248 | << ResultType << BaseExpr->getSourceRange(); |
5249 | return ExprError(); |
5250 | } |
5251 | |
5252 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { |
5253 | // GNU extension: subscripting on pointer to void |
5254 | Diag(Loc: LLoc, DiagID: diag::ext_gnu_subscript_void_type) |
5255 | << BaseExpr->getSourceRange(); |
5256 | |
5257 | // C forbids expressions of unqualified void type from being l-values. |
5258 | // See IsCForbiddenLValueType. |
5259 | if (!ResultType.hasQualifiers()) |
5260 | VK = VK_PRValue; |
5261 | } else if (!ResultType->isDependentType() && |
5262 | !ResultType.isWebAssemblyReferenceType() && |
5263 | RequireCompleteSizedType( |
5264 | Loc: LLoc, T: ResultType, |
5265 | DiagID: diag::err_subscript_incomplete_or_sizeless_type, Args: BaseExpr)) |
5266 | return ExprError(); |
5267 | |
5268 | assert(VK == VK_PRValue || LangOpts.CPlusPlus || |
5269 | !ResultType.isCForbiddenLValueType()); |
5270 | |
5271 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && |
5272 | FunctionScopes.size() > 1) { |
5273 | if (auto *TT = |
5274 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { |
5275 | for (auto I = FunctionScopes.rbegin(), |
5276 | E = std::prev(x: FunctionScopes.rend()); |
5277 | I != E; ++I) { |
5278 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
5279 | if (CSI == nullptr) |
5280 | break; |
5281 | DeclContext *DC = nullptr; |
5282 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
5283 | DC = LSI->CallOperator; |
5284 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
5285 | DC = CRSI->TheCapturedDecl; |
5286 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
5287 | DC = BSI->TheDecl; |
5288 | if (DC) { |
5289 | if (DC->containsDecl(D: TT->getDecl())) |
5290 | break; |
5291 | captureVariablyModifiedType( |
5292 | Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI); |
5293 | } |
5294 | } |
5295 | } |
5296 | } |
5297 | |
5298 | return new (Context) |
5299 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); |
5300 | } |
5301 | |
5302 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
5303 | ParmVarDecl *Param, Expr *RewrittenInit, |
5304 | bool SkipImmediateInvocations) { |
5305 | if (Param->hasUnparsedDefaultArg()) { |
5306 | assert(!RewrittenInit && "Should not have a rewritten init expression yet" ); |
5307 | // If we've already cleared out the location for the default argument, |
5308 | // that means we're parsing it right now. |
5309 | if (!UnparsedDefaultArgLocs.count(Val: Param)) { |
5310 | Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument) << FD; |
5311 | Diag(Loc: CallLoc, DiagID: diag::note_recursive_default_argument_used_here); |
5312 | Param->setInvalidDecl(); |
5313 | return true; |
5314 | } |
5315 | |
5316 | Diag(Loc: CallLoc, DiagID: diag::err_use_of_default_argument_to_function_declared_later) |
5317 | << FD << cast<CXXRecordDecl>(Val: FD->getDeclContext()); |
5318 | Diag(Loc: UnparsedDefaultArgLocs[Param], |
5319 | DiagID: diag::note_default_argument_declared_here); |
5320 | return true; |
5321 | } |
5322 | |
5323 | if (Param->hasUninstantiatedDefaultArg()) { |
5324 | assert(!RewrittenInit && "Should not have a rewitten init expression yet" ); |
5325 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
5326 | return true; |
5327 | } |
5328 | |
5329 | Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); |
5330 | assert(Init && "default argument but no initializer?" ); |
5331 | |
5332 | // If the default expression creates temporaries, we need to |
5333 | // push them to the current stack of expression temporaries so they'll |
5334 | // be properly destroyed. |
5335 | // FIXME: We should really be rebuilding the default argument with new |
5336 | // bound temporaries; see the comment in PR5810. |
5337 | // We don't need to do that with block decls, though, because |
5338 | // blocks in default argument expression can never capture anything. |
5339 | if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Val: Init)) { |
5340 | // Set the "needs cleanups" bit regardless of whether there are |
5341 | // any explicit objects. |
5342 | Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); |
5343 | // Append all the objects to the cleanup list. Right now, this |
5344 | // should always be a no-op, because blocks in default argument |
5345 | // expressions should never be able to capture anything. |
5346 | assert(!InitWithCleanup->getNumObjects() && |
5347 | "default argument expression has capturing blocks?" ); |
5348 | } |
5349 | // C++ [expr.const]p15.1: |
5350 | // An expression or conversion is in an immediate function context if it is |
5351 | // potentially evaluated and [...] its innermost enclosing non-block scope |
5352 | // is a function parameter scope of an immediate function. |
5353 | EnterExpressionEvaluationContext EvalContext( |
5354 | *this, |
5355 | FD->isImmediateFunction() |
5356 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
5357 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
5358 | Param); |
5359 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
5360 | SkipImmediateInvocations; |
5361 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
5362 | MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true); |
5363 | }); |
5364 | return false; |
5365 | } |
5366 | |
5367 | struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> { |
5368 | const ASTContext &Context; |
5369 | ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {} |
5370 | |
5371 | bool HasImmediateCalls = false; |
5372 | bool shouldVisitImplicitCode() const { return true; } |
5373 | |
5374 | bool VisitCallExpr(CallExpr *E) { |
5375 | if (const FunctionDecl *FD = E->getDirectCallee()) |
5376 | HasImmediateCalls |= FD->isImmediateFunction(); |
5377 | return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(S: E); |
5378 | } |
5379 | |
5380 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { |
5381 | if (const FunctionDecl *FD = E->getConstructor()) |
5382 | HasImmediateCalls |= FD->isImmediateFunction(); |
5383 | return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(S: E); |
5384 | } |
5385 | |
5386 | // SourceLocExpr are not immediate invocations |
5387 | // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr |
5388 | // need to be rebuilt so that they refer to the correct SourceLocation and |
5389 | // DeclContext. |
5390 | bool VisitSourceLocExpr(SourceLocExpr *E) { |
5391 | HasImmediateCalls = true; |
5392 | return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(S: E); |
5393 | } |
5394 | |
5395 | // A nested lambda might have parameters with immediate invocations |
5396 | // in their default arguments. |
5397 | // The compound statement is not visited (as it does not constitute a |
5398 | // subexpression). |
5399 | // FIXME: We should consider visiting and transforming captures |
5400 | // with init expressions. |
5401 | bool VisitLambdaExpr(LambdaExpr *E) { |
5402 | return VisitCXXMethodDecl(D: E->getCallOperator()); |
5403 | } |
5404 | |
5405 | bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { |
5406 | return TraverseStmt(S: E->getExpr()); |
5407 | } |
5408 | |
5409 | bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { |
5410 | return TraverseStmt(S: E->getExpr()); |
5411 | } |
5412 | }; |
5413 | |
5414 | struct EnsureImmediateInvocationInDefaultArgs |
5415 | : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { |
5416 | EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) |
5417 | : TreeTransform(SemaRef) {} |
5418 | |
5419 | // Lambda can only have immediate invocations in the default |
5420 | // args of their parameters, which is transformed upon calling the closure. |
5421 | // The body is not a subexpression, so we have nothing to do. |
5422 | // FIXME: Immediate calls in capture initializers should be transformed. |
5423 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } |
5424 | ExprResult TransformBlockExpr(BlockExpr *E) { return E; } |
5425 | |
5426 | // Make sure we don't rebuild the this pointer as it would |
5427 | // cause it to incorrectly point it to the outermost class |
5428 | // in the case of nested struct initialization. |
5429 | ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } |
5430 | |
5431 | // Rewrite to source location to refer to the context in which they are used. |
5432 | ExprResult TransformSourceLocExpr(SourceLocExpr *E) { |
5433 | DeclContext *DC = E->getParentContext(); |
5434 | if (DC == SemaRef.CurContext) |
5435 | return E; |
5436 | |
5437 | // FIXME: During instantiation, because the rebuild of defaults arguments |
5438 | // is not always done in the context of the template instantiator, |
5439 | // we run the risk of producing a dependent source location |
5440 | // that would never be rebuilt. |
5441 | // This usually happens during overload resolution, or in contexts |
5442 | // where the value of the source location does not matter. |
5443 | // However, we should find a better way to deal with source location |
5444 | // of function templates. |
5445 | if (!SemaRef.CurrentInstantiationScope || |
5446 | !SemaRef.CurContext->isDependentContext() || DC->isDependentContext()) |
5447 | DC = SemaRef.CurContext; |
5448 | |
5449 | return getDerived().RebuildSourceLocExpr( |
5450 | Kind: E->getIdentKind(), ResultTy: E->getType(), BuiltinLoc: E->getBeginLoc(), RPLoc: E->getEndLoc(), ParentContext: DC); |
5451 | } |
5452 | }; |
5453 | |
5454 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
5455 | FunctionDecl *FD, ParmVarDecl *Param, |
5456 | Expr *Init) { |
5457 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg" ); |
5458 | |
5459 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
5460 | bool InLifetimeExtendingContext = isInLifetimeExtendingContext(); |
5461 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
5462 | InitializationContext = |
5463 | OutermostDeclarationWithDelayedImmediateInvocations(); |
5464 | if (!InitializationContext.has_value()) |
5465 | InitializationContext.emplace(args&: CallLoc, args&: Param, args&: CurContext); |
5466 | |
5467 | if (!Init && !Param->hasUnparsedDefaultArg()) { |
5468 | // Mark that we are replacing a default argument first. |
5469 | // If we are instantiating a template we won't have to |
5470 | // retransform immediate calls. |
5471 | // C++ [expr.const]p15.1: |
5472 | // An expression or conversion is in an immediate function context if it |
5473 | // is potentially evaluated and [...] its innermost enclosing non-block |
5474 | // scope is a function parameter scope of an immediate function. |
5475 | EnterExpressionEvaluationContext EvalContext( |
5476 | *this, |
5477 | FD->isImmediateFunction() |
5478 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
5479 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
5480 | Param); |
5481 | |
5482 | if (Param->hasUninstantiatedDefaultArg()) { |
5483 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
5484 | return ExprError(); |
5485 | } |
5486 | // CWG2631 |
5487 | // An immediate invocation that is not evaluated where it appears is |
5488 | // evaluated and checked for whether it is a constant expression at the |
5489 | // point where the enclosing initializer is used in a function call. |
5490 | ImmediateCallVisitor V(getASTContext()); |
5491 | if (!NestedDefaultChecking) |
5492 | V.TraverseDecl(D: Param); |
5493 | |
5494 | // Rewrite the call argument that was created from the corresponding |
5495 | // parameter's default argument. |
5496 | if (V.HasImmediateCalls || InLifetimeExtendingContext) { |
5497 | if (V.HasImmediateCalls) |
5498 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
5499 | CallLoc, Param, CurContext}; |
5500 | // Pass down lifetime extending flag, and collect temporaries in |
5501 | // CreateMaterializeTemporaryExpr when we rewrite the call argument. |
5502 | keepInLifetimeExtendingContext(); |
5503 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
5504 | ExprResult Res; |
5505 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
5506 | Res = Immediate.TransformInitializer(Init: Param->getInit(), |
5507 | /*NotCopy=*/NotCopyInit: false); |
5508 | }); |
5509 | if (Res.isInvalid()) |
5510 | return ExprError(); |
5511 | Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(), |
5512 | EqualLoc: Res.get()->getBeginLoc()); |
5513 | if (Res.isInvalid()) |
5514 | return ExprError(); |
5515 | Init = Res.get(); |
5516 | } |
5517 | } |
5518 | |
5519 | if (CheckCXXDefaultArgExpr( |
5520 | CallLoc, FD, Param, RewrittenInit: Init, |
5521 | /*SkipImmediateInvocations=*/NestedDefaultChecking)) |
5522 | return ExprError(); |
5523 | |
5524 | return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param, |
5525 | RewrittenExpr: Init, UsedContext: InitializationContext->Context); |
5526 | } |
5527 | |
5528 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { |
5529 | assert(Field->hasInClassInitializer()); |
5530 | |
5531 | // If we might have already tried and failed to instantiate, don't try again. |
5532 | if (Field->isInvalidDecl()) |
5533 | return ExprError(); |
5534 | |
5535 | CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers()); |
5536 | |
5537 | auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent()); |
5538 | |
5539 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
5540 | InitializationContext = |
5541 | OutermostDeclarationWithDelayedImmediateInvocations(); |
5542 | if (!InitializationContext.has_value()) |
5543 | InitializationContext.emplace(args&: Loc, args&: Field, args&: CurContext); |
5544 | |
5545 | Expr *Init = nullptr; |
5546 | |
5547 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
5548 | |
5549 | EnterExpressionEvaluationContext EvalContext( |
5550 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); |
5551 | |
5552 | if (!Field->getInClassInitializer()) { |
5553 | // Maybe we haven't instantiated the in-class initializer. Go check the |
5554 | // pattern FieldDecl to see if it has one. |
5555 | if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) { |
5556 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); |
5557 | DeclContext::lookup_result Lookup = |
5558 | ClassPattern->lookup(Name: Field->getDeclName()); |
5559 | |
5560 | FieldDecl *Pattern = nullptr; |
5561 | for (auto *L : Lookup) { |
5562 | if ((Pattern = dyn_cast<FieldDecl>(Val: L))) |
5563 | break; |
5564 | } |
5565 | assert(Pattern && "We must have set the Pattern!" ); |
5566 | if (!Pattern->hasInClassInitializer() || |
5567 | InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern, |
5568 | TemplateArgs: getTemplateInstantiationArgs(D: Field))) { |
5569 | Field->setInvalidDecl(); |
5570 | return ExprError(); |
5571 | } |
5572 | } |
5573 | } |
5574 | |
5575 | // CWG2631 |
5576 | // An immediate invocation that is not evaluated where it appears is |
5577 | // evaluated and checked for whether it is a constant expression at the |
5578 | // point where the enclosing initializer is used in a [...] a constructor |
5579 | // definition, or an aggregate initialization. |
5580 | ImmediateCallVisitor V(getASTContext()); |
5581 | if (!NestedDefaultChecking) |
5582 | V.TraverseDecl(D: Field); |
5583 | if (V.HasImmediateCalls) { |
5584 | ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, |
5585 | CurContext}; |
5586 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
5587 | NestedDefaultChecking; |
5588 | |
5589 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
5590 | ExprResult Res; |
5591 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5592 | Res = Immediate.TransformInitializer(Init: Field->getInClassInitializer(), |
5593 | /*CXXDirectInit=*/NotCopyInit: false); |
5594 | }); |
5595 | if (!Res.isInvalid()) |
5596 | Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc); |
5597 | if (Res.isInvalid()) { |
5598 | Field->setInvalidDecl(); |
5599 | return ExprError(); |
5600 | } |
5601 | Init = Res.get(); |
5602 | } |
5603 | |
5604 | if (Field->getInClassInitializer()) { |
5605 | Expr *E = Init ? Init : Field->getInClassInitializer(); |
5606 | if (!NestedDefaultChecking) |
5607 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5608 | MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); |
5609 | }); |
5610 | // C++11 [class.base.init]p7: |
5611 | // The initialization of each base and member constitutes a |
5612 | // full-expression. |
5613 | ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false); |
5614 | if (Res.isInvalid()) { |
5615 | Field->setInvalidDecl(); |
5616 | return ExprError(); |
5617 | } |
5618 | Init = Res.get(); |
5619 | |
5620 | return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc, |
5621 | Field, UsedContext: InitializationContext->Context, |
5622 | RewrittenInitExpr: Init); |
5623 | } |
5624 | |
5625 | // DR1351: |
5626 | // If the brace-or-equal-initializer of a non-static data member |
5627 | // invokes a defaulted default constructor of its class or of an |
5628 | // enclosing class in a potentially evaluated subexpression, the |
5629 | // program is ill-formed. |
5630 | // |
5631 | // This resolution is unworkable: the exception specification of the |
5632 | // default constructor can be needed in an unevaluated context, in |
5633 | // particular, in the operand of a noexcept-expression, and we can be |
5634 | // unable to compute an exception specification for an enclosed class. |
5635 | // |
5636 | // Any attempt to resolve the exception specification of a defaulted default |
5637 | // constructor before the initializer is lexically complete will ultimately |
5638 | // come here at which point we can diagnose it. |
5639 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); |
5640 | Diag(Loc, DiagID: diag::err_default_member_initializer_not_yet_parsed) |
5641 | << OutermostClass << Field; |
5642 | Diag(Loc: Field->getEndLoc(), |
5643 | DiagID: diag::note_default_member_initializer_not_yet_parsed); |
5644 | // Recover by marking the field invalid, unless we're in a SFINAE context. |
5645 | if (!isSFINAEContext()) |
5646 | Field->setInvalidDecl(); |
5647 | return ExprError(); |
5648 | } |
5649 | |
5650 | Sema::VariadicCallType |
5651 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, |
5652 | Expr *Fn) { |
5653 | if (Proto && Proto->isVariadic()) { |
5654 | if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl)) |
5655 | return VariadicConstructor; |
5656 | else if (Fn && Fn->getType()->isBlockPointerType()) |
5657 | return VariadicBlock; |
5658 | else if (FDecl) { |
5659 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl)) |
5660 | if (Method->isInstance()) |
5661 | return VariadicMethod; |
5662 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) |
5663 | return VariadicMethod; |
5664 | return VariadicFunction; |
5665 | } |
5666 | return VariadicDoesNotApply; |
5667 | } |
5668 | |
5669 | namespace { |
5670 | class FunctionCallCCC final : public FunctionCallFilterCCC { |
5671 | public: |
5672 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, |
5673 | unsigned NumArgs, MemberExpr *ME) |
5674 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), |
5675 | FunctionName(FuncName) {} |
5676 | |
5677 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
5678 | if (!candidate.getCorrectionSpecifier() || |
5679 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { |
5680 | return false; |
5681 | } |
5682 | |
5683 | return FunctionCallFilterCCC::ValidateCandidate(candidate); |
5684 | } |
5685 | |
5686 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
5687 | return std::make_unique<FunctionCallCCC>(args&: *this); |
5688 | } |
5689 | |
5690 | private: |
5691 | const IdentifierInfo *const FunctionName; |
5692 | }; |
5693 | } |
5694 | |
5695 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, |
5696 | FunctionDecl *FDecl, |
5697 | ArrayRef<Expr *> Args) { |
5698 | MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn); |
5699 | DeclarationName FuncName = FDecl->getDeclName(); |
5700 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); |
5701 | |
5702 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); |
5703 | if (TypoCorrection Corrected = S.CorrectTypo( |
5704 | Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName, |
5705 | S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC, |
5706 | Mode: Sema::CTK_ErrorRecovery)) { |
5707 | if (NamedDecl *ND = Corrected.getFoundDecl()) { |
5708 | if (Corrected.isOverloaded()) { |
5709 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); |
5710 | OverloadCandidateSet::iterator Best; |
5711 | for (NamedDecl *CD : Corrected) { |
5712 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD)) |
5713 | S.AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: AS_none), Args, |
5714 | CandidateSet&: OCS); |
5715 | } |
5716 | switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) { |
5717 | case OR_Success: |
5718 | ND = Best->FoundDecl; |
5719 | Corrected.setCorrectionDecl(ND); |
5720 | break; |
5721 | default: |
5722 | break; |
5723 | } |
5724 | } |
5725 | ND = ND->getUnderlyingDecl(); |
5726 | if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND)) |
5727 | return Corrected; |
5728 | } |
5729 | } |
5730 | return TypoCorrection(); |
5731 | } |
5732 | |
5733 | // [C++26][[expr.unary.op]/p4 |
5734 | // A pointer to member is only formed when an explicit & |
5735 | // is used and its operand is a qualified-id not enclosed in parentheses. |
5736 | static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) { |
5737 | if (!isa<ParenExpr>(Val: Fn)) |
5738 | return false; |
5739 | |
5740 | Fn = Fn->IgnoreParens(); |
5741 | |
5742 | auto *UO = dyn_cast<UnaryOperator>(Val: Fn); |
5743 | if (!UO || UO->getOpcode() != clang::UO_AddrOf) |
5744 | return false; |
5745 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) { |
5746 | return DRE->hasQualifier(); |
5747 | } |
5748 | if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens())) |
5749 | return OVL->getQualifier(); |
5750 | return false; |
5751 | } |
5752 | |
5753 | bool |
5754 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
5755 | FunctionDecl *FDecl, |
5756 | const FunctionProtoType *Proto, |
5757 | ArrayRef<Expr *> Args, |
5758 | SourceLocation RParenLoc, |
5759 | bool IsExecConfig) { |
5760 | // Bail out early if calling a builtin with custom typechecking. |
5761 | if (FDecl) |
5762 | if (unsigned ID = FDecl->getBuiltinID()) |
5763 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) |
5764 | return false; |
5765 | |
5766 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by |
5767 | // assignment, to the types of the corresponding parameter, ... |
5768 | |
5769 | bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn); |
5770 | bool HasExplicitObjectParameter = |
5771 | !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter(); |
5772 | unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0; |
5773 | unsigned NumParams = Proto->getNumParams(); |
5774 | bool Invalid = false; |
5775 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; |
5776 | unsigned FnKind = Fn->getType()->isBlockPointerType() |
5777 | ? 1 /* block */ |
5778 | : (IsExecConfig ? 3 /* kernel function (exec config) */ |
5779 | : 0 /* function */); |
5780 | |
5781 | // If too few arguments are available (and we don't have default |
5782 | // arguments for the remaining parameters), don't make the call. |
5783 | if (Args.size() < NumParams) { |
5784 | if (Args.size() < MinArgs) { |
5785 | TypoCorrection TC; |
5786 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
5787 | unsigned diag_id = |
5788 | MinArgs == NumParams && !Proto->isVariadic() |
5789 | ? diag::err_typecheck_call_too_few_args_suggest |
5790 | : diag::err_typecheck_call_too_few_args_at_least_suggest; |
5791 | diagnoseTypo( |
5792 | Correction: TC, TypoDiag: PDiag(DiagID: diag_id) |
5793 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
5794 | << static_cast<unsigned>(Args.size()) - |
5795 | ExplicitObjectParameterOffset |
5796 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
5797 | } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl && |
5798 | FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
5799 | ->getDeclName()) |
5800 | Diag(Loc: RParenLoc, |
5801 | DiagID: MinArgs == NumParams && !Proto->isVariadic() |
5802 | ? diag::err_typecheck_call_too_few_args_one |
5803 | : diag::err_typecheck_call_too_few_args_at_least_one) |
5804 | << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
5805 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
5806 | else |
5807 | Diag(Loc: RParenLoc, DiagID: MinArgs == NumParams && !Proto->isVariadic() |
5808 | ? diag::err_typecheck_call_too_few_args |
5809 | : diag::err_typecheck_call_too_few_args_at_least) |
5810 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
5811 | << static_cast<unsigned>(Args.size()) - |
5812 | ExplicitObjectParameterOffset |
5813 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
5814 | |
5815 | // Emit the location of the prototype. |
5816 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
5817 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) |
5818 | << FDecl << FDecl->getParametersSourceRange(); |
5819 | |
5820 | return true; |
5821 | } |
5822 | // We reserve space for the default arguments when we create |
5823 | // the call expression, before calling ConvertArgumentsForCall. |
5824 | assert((Call->getNumArgs() == NumParams) && |
5825 | "We should have reserved space for the default arguments before!" ); |
5826 | } |
5827 | |
5828 | // If too many are passed and not variadic, error on the extras and drop |
5829 | // them. |
5830 | if (Args.size() > NumParams) { |
5831 | if (!Proto->isVariadic()) { |
5832 | TypoCorrection TC; |
5833 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
5834 | unsigned diag_id = |
5835 | MinArgs == NumParams && !Proto->isVariadic() |
5836 | ? diag::err_typecheck_call_too_many_args_suggest |
5837 | : diag::err_typecheck_call_too_many_args_at_most_suggest; |
5838 | diagnoseTypo( |
5839 | Correction: TC, TypoDiag: PDiag(DiagID: diag_id) |
5840 | << FnKind << NumParams - ExplicitObjectParameterOffset |
5841 | << static_cast<unsigned>(Args.size()) - |
5842 | ExplicitObjectParameterOffset |
5843 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
5844 | } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl && |
5845 | FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
5846 | ->getDeclName()) |
5847 | Diag(Loc: Args[NumParams]->getBeginLoc(), |
5848 | DiagID: MinArgs == NumParams |
5849 | ? diag::err_typecheck_call_too_many_args_one |
5850 | : diag::err_typecheck_call_too_many_args_at_most_one) |
5851 | << FnKind << FDecl->getParamDecl(i: ExplicitObjectParameterOffset) |
5852 | << static_cast<unsigned>(Args.size()) - |
5853 | ExplicitObjectParameterOffset |
5854 | << HasExplicitObjectParameter << Fn->getSourceRange() |
5855 | << SourceRange(Args[NumParams]->getBeginLoc(), |
5856 | Args.back()->getEndLoc()); |
5857 | else |
5858 | Diag(Loc: Args[NumParams]->getBeginLoc(), |
5859 | DiagID: MinArgs == NumParams |
5860 | ? diag::err_typecheck_call_too_many_args |
5861 | : diag::err_typecheck_call_too_many_args_at_most) |
5862 | << FnKind << NumParams - ExplicitObjectParameterOffset |
5863 | << static_cast<unsigned>(Args.size()) - |
5864 | ExplicitObjectParameterOffset |
5865 | << HasExplicitObjectParameter << Fn->getSourceRange() |
5866 | << SourceRange(Args[NumParams]->getBeginLoc(), |
5867 | Args.back()->getEndLoc()); |
5868 | |
5869 | // Emit the location of the prototype. |
5870 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
5871 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) |
5872 | << FDecl << FDecl->getParametersSourceRange(); |
5873 | |
5874 | // This deletes the extra arguments. |
5875 | Call->shrinkNumArgs(NewNumArgs: NumParams); |
5876 | return true; |
5877 | } |
5878 | } |
5879 | SmallVector<Expr *, 8> AllArgs; |
5880 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); |
5881 | |
5882 | Invalid = GatherArgumentsForCall(CallLoc: Call->getBeginLoc(), FDecl, Proto, FirstParam: 0, Args, |
5883 | AllArgs, CallType); |
5884 | if (Invalid) |
5885 | return true; |
5886 | unsigned TotalNumArgs = AllArgs.size(); |
5887 | for (unsigned i = 0; i < TotalNumArgs; ++i) |
5888 | Call->setArg(Arg: i, ArgExpr: AllArgs[i]); |
5889 | |
5890 | Call->computeDependence(); |
5891 | return false; |
5892 | } |
5893 | |
5894 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
5895 | const FunctionProtoType *Proto, |
5896 | unsigned FirstParam, ArrayRef<Expr *> Args, |
5897 | SmallVectorImpl<Expr *> &AllArgs, |
5898 | VariadicCallType CallType, bool AllowExplicit, |
5899 | bool IsListInitialization) { |
5900 | unsigned NumParams = Proto->getNumParams(); |
5901 | bool Invalid = false; |
5902 | size_t ArgIx = 0; |
5903 | // Continue to check argument types (even if we have too few/many args). |
5904 | for (unsigned i = FirstParam; i < NumParams; i++) { |
5905 | QualType ProtoArgType = Proto->getParamType(i); |
5906 | |
5907 | Expr *Arg; |
5908 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; |
5909 | if (ArgIx < Args.size()) { |
5910 | Arg = Args[ArgIx++]; |
5911 | |
5912 | if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: ProtoArgType, |
5913 | DiagID: diag::err_call_incomplete_argument, Args: Arg)) |
5914 | return true; |
5915 | |
5916 | // Strip the unbridged-cast placeholder expression off, if applicable. |
5917 | bool CFAudited = false; |
5918 | if (Arg->getType() == Context.ARCUnbridgedCastTy && |
5919 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
5920 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
5921 | Arg = ObjC().stripARCUnbridgedCast(e: Arg); |
5922 | else if (getLangOpts().ObjCAutoRefCount && |
5923 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
5924 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
5925 | CFAudited = true; |
5926 | |
5927 | if (Proto->getExtParameterInfo(I: i).isNoEscape() && |
5928 | ProtoArgType->isBlockPointerType()) |
5929 | if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context))) |
5930 | BE->getBlockDecl()->setDoesNotEscape(); |
5931 | |
5932 | InitializedEntity Entity = |
5933 | Param ? InitializedEntity::InitializeParameter(Context, Parm: Param, |
5934 | Type: ProtoArgType) |
5935 | : InitializedEntity::InitializeParameter( |
5936 | Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i)); |
5937 | |
5938 | // Remember that parameter belongs to a CF audited API. |
5939 | if (CFAudited) |
5940 | Entity.setParameterCFAudited(); |
5941 | |
5942 | ExprResult ArgE = PerformCopyInitialization( |
5943 | Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit); |
5944 | if (ArgE.isInvalid()) |
5945 | return true; |
5946 | |
5947 | Arg = ArgE.getAs<Expr>(); |
5948 | } else { |
5949 | assert(Param && "can't use default arguments without a known callee" ); |
5950 | |
5951 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param); |
5952 | if (ArgExpr.isInvalid()) |
5953 | return true; |
5954 | |
5955 | Arg = ArgExpr.getAs<Expr>(); |
5956 | } |
5957 | |
5958 | // Check for array bounds violations for each argument to the call. This |
5959 | // check only triggers warnings when the argument isn't a more complex Expr |
5960 | // with its own checking, such as a BinaryOperator. |
5961 | CheckArrayAccess(E: Arg); |
5962 | |
5963 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). |
5964 | CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg); |
5965 | |
5966 | AllArgs.push_back(Elt: Arg); |
5967 | } |
5968 | |
5969 | // If this is a variadic call, handle args passed through "...". |
5970 | if (CallType != VariadicDoesNotApply) { |
5971 | // Assume that extern "C" functions with variadic arguments that |
5972 | // return __unknown_anytype aren't *really* variadic. |
5973 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && |
5974 | FDecl->isExternC()) { |
5975 | for (Expr *A : Args.slice(N: ArgIx)) { |
5976 | QualType paramType; // ignored |
5977 | ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType); |
5978 | Invalid |= arg.isInvalid(); |
5979 | AllArgs.push_back(Elt: arg.get()); |
5980 | } |
5981 | |
5982 | // Otherwise do argument promotion, (C99 6.5.2.2p7). |
5983 | } else { |
5984 | for (Expr *A : Args.slice(N: ArgIx)) { |
5985 | ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl); |
5986 | Invalid |= Arg.isInvalid(); |
5987 | AllArgs.push_back(Elt: Arg.get()); |
5988 | } |
5989 | } |
5990 | |
5991 | // Check for array bounds violations. |
5992 | for (Expr *A : Args.slice(N: ArgIx)) |
5993 | CheckArrayAccess(E: A); |
5994 | } |
5995 | return Invalid; |
5996 | } |
5997 | |
5998 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { |
5999 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); |
6000 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) |
6001 | TL = DTL.getOriginalLoc(); |
6002 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) |
6003 | S.Diag(Loc: PVD->getLocation(), DiagID: diag::note_callee_static_array) |
6004 | << ATL.getLocalSourceRange(); |
6005 | } |
6006 | |
6007 | void |
6008 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, |
6009 | ParmVarDecl *Param, |
6010 | const Expr *ArgExpr) { |
6011 | // Static array parameters are not supported in C++. |
6012 | if (!Param || getLangOpts().CPlusPlus) |
6013 | return; |
6014 | |
6015 | QualType OrigTy = Param->getOriginalType(); |
6016 | |
6017 | const ArrayType *AT = Context.getAsArrayType(T: OrigTy); |
6018 | if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static) |
6019 | return; |
6020 | |
6021 | if (ArgExpr->isNullPointerConstant(Ctx&: Context, |
6022 | NPC: Expr::NPC_NeverValueDependent)) { |
6023 | Diag(Loc: CallLoc, DiagID: diag::warn_null_arg) << ArgExpr->getSourceRange(); |
6024 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6025 | return; |
6026 | } |
6027 | |
6028 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT); |
6029 | if (!CAT) |
6030 | return; |
6031 | |
6032 | const ConstantArrayType *ArgCAT = |
6033 | Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType()); |
6034 | if (!ArgCAT) |
6035 | return; |
6036 | |
6037 | if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(), |
6038 | T2: ArgCAT->getElementType())) { |
6039 | if (ArgCAT->getSize().ult(RHS: CAT->getSize())) { |
6040 | Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small) |
6041 | << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize() |
6042 | << (unsigned)CAT->getZExtSize() << 0; |
6043 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6044 | } |
6045 | return; |
6046 | } |
6047 | |
6048 | std::optional<CharUnits> ArgSize = |
6049 | getASTContext().getTypeSizeInCharsIfKnown(Ty: ArgCAT); |
6050 | std::optional<CharUnits> ParmSize = |
6051 | getASTContext().getTypeSizeInCharsIfKnown(Ty: CAT); |
6052 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { |
6053 | Diag(Loc: CallLoc, DiagID: diag::warn_static_array_too_small) |
6054 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() |
6055 | << (unsigned)ParmSize->getQuantity() << 1; |
6056 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6057 | } |
6058 | } |
6059 | |
6060 | /// Given a function expression of unknown-any type, try to rebuild it |
6061 | /// to have a function type. |
6062 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); |
6063 | |
6064 | /// Is the given type a placeholder that we need to lower out |
6065 | /// immediately during argument processing? |
6066 | static bool isPlaceholderToRemoveAsArg(QualType type) { |
6067 | // Placeholders are never sugared. |
6068 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type); |
6069 | if (!placeholder) return false; |
6070 | |
6071 | switch (placeholder->getKind()) { |
6072 | // Ignore all the non-placeholder types. |
6073 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6074 | case BuiltinType::Id: |
6075 | #include "clang/Basic/OpenCLImageTypes.def" |
6076 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6077 | case BuiltinType::Id: |
6078 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6079 | // In practice we'll never use this, since all SVE types are sugared |
6080 | // via TypedefTypes rather than exposed directly as BuiltinTypes. |
6081 | #define SVE_TYPE(Name, Id, SingletonId) \ |
6082 | case BuiltinType::Id: |
6083 | #include "clang/Basic/AArch64SVEACLETypes.def" |
6084 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
6085 | case BuiltinType::Id: |
6086 | #include "clang/Basic/PPCTypes.def" |
6087 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6088 | #include "clang/Basic/RISCVVTypes.def" |
6089 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6090 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
6091 | #define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6092 | #include "clang/Basic/AMDGPUTypes.def" |
6093 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) |
6094 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: |
6095 | #include "clang/AST/BuiltinTypes.def" |
6096 | return false; |
6097 | |
6098 | case BuiltinType::UnresolvedTemplate: |
6099 | // We cannot lower out overload sets; they might validly be resolved |
6100 | // by the call machinery. |
6101 | case BuiltinType::Overload: |
6102 | return false; |
6103 | |
6104 | // Unbridged casts in ARC can be handled in some call positions and |
6105 | // should be left in place. |
6106 | case BuiltinType::ARCUnbridgedCast: |
6107 | return false; |
6108 | |
6109 | // Pseudo-objects should be converted as soon as possible. |
6110 | case BuiltinType::PseudoObject: |
6111 | return true; |
6112 | |
6113 | // The debugger mode could theoretically but currently does not try |
6114 | // to resolve unknown-typed arguments based on known parameter types. |
6115 | case BuiltinType::UnknownAny: |
6116 | return true; |
6117 | |
6118 | // These are always invalid as call arguments and should be reported. |
6119 | case BuiltinType::BoundMember: |
6120 | case BuiltinType::BuiltinFn: |
6121 | case BuiltinType::IncompleteMatrixIdx: |
6122 | case BuiltinType::ArraySection: |
6123 | case BuiltinType::OMPArrayShaping: |
6124 | case BuiltinType::OMPIterator: |
6125 | return true; |
6126 | |
6127 | } |
6128 | llvm_unreachable("bad builtin type kind" ); |
6129 | } |
6130 | |
6131 | bool Sema::CheckArgsForPlaceholders(MultiExprArg args) { |
6132 | // Apply this processing to all the arguments at once instead of |
6133 | // dying at the first failure. |
6134 | bool hasInvalid = false; |
6135 | for (size_t i = 0, e = args.size(); i != e; i++) { |
6136 | if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) { |
6137 | ExprResult result = CheckPlaceholderExpr(E: args[i]); |
6138 | if (result.isInvalid()) hasInvalid = true; |
6139 | else args[i] = result.get(); |
6140 | } |
6141 | } |
6142 | return hasInvalid; |
6143 | } |
6144 | |
6145 | /// If a builtin function has a pointer argument with no explicit address |
6146 | /// space, then it should be able to accept a pointer to any address |
6147 | /// space as input. In order to do this, we need to replace the |
6148 | /// standard builtin declaration with one that uses the same address space |
6149 | /// as the call. |
6150 | /// |
6151 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. |
6152 | /// it does not contain any pointer arguments without |
6153 | /// an address space qualifer. Otherwise the rewritten |
6154 | /// FunctionDecl is returned. |
6155 | /// TODO: Handle pointer return types. |
6156 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, |
6157 | FunctionDecl *FDecl, |
6158 | MultiExprArg ArgExprs) { |
6159 | |
6160 | QualType DeclType = FDecl->getType(); |
6161 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType); |
6162 | |
6163 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT || |
6164 | ArgExprs.size() < FT->getNumParams()) |
6165 | return nullptr; |
6166 | |
6167 | bool NeedsNewDecl = false; |
6168 | unsigned i = 0; |
6169 | SmallVector<QualType, 8> OverloadParams; |
6170 | |
6171 | for (QualType ParamType : FT->param_types()) { |
6172 | |
6173 | // Convert array arguments to pointer to simplify type lookup. |
6174 | ExprResult ArgRes = |
6175 | Sema->DefaultFunctionArrayLvalueConversion(E: ArgExprs[i++]); |
6176 | if (ArgRes.isInvalid()) |
6177 | return nullptr; |
6178 | Expr *Arg = ArgRes.get(); |
6179 | QualType ArgType = Arg->getType(); |
6180 | if (!ParamType->isPointerType() || ParamType.hasAddressSpace() || |
6181 | !ArgType->isPointerType() || |
6182 | !ArgType->getPointeeType().hasAddressSpace() || |
6183 | isPtrSizeAddressSpace(AS: ArgType->getPointeeType().getAddressSpace())) { |
6184 | OverloadParams.push_back(Elt: ParamType); |
6185 | continue; |
6186 | } |
6187 | |
6188 | QualType PointeeType = ParamType->getPointeeType(); |
6189 | if (PointeeType.hasAddressSpace()) |
6190 | continue; |
6191 | |
6192 | NeedsNewDecl = true; |
6193 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); |
6194 | |
6195 | PointeeType = Context.getAddrSpaceQualType(T: PointeeType, AddressSpace: AS); |
6196 | OverloadParams.push_back(Elt: Context.getPointerType(T: PointeeType)); |
6197 | } |
6198 | |
6199 | if (!NeedsNewDecl) |
6200 | return nullptr; |
6201 | |
6202 | FunctionProtoType::ExtProtoInfo EPI; |
6203 | EPI.Variadic = FT->isVariadic(); |
6204 | QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(), |
6205 | Args: OverloadParams, EPI); |
6206 | DeclContext *Parent = FDecl->getParent(); |
6207 | FunctionDecl *OverloadDecl = FunctionDecl::Create( |
6208 | C&: Context, DC: Parent, StartLoc: FDecl->getLocation(), NLoc: FDecl->getLocation(), |
6209 | N: FDecl->getIdentifier(), T: OverloadTy, |
6210 | /*TInfo=*/nullptr, SC: SC_Extern, UsesFPIntrin: Sema->getCurFPFeatures().isFPConstrained(), |
6211 | isInlineSpecified: false, |
6212 | /*hasPrototype=*/hasWrittenPrototype: true); |
6213 | SmallVector<ParmVarDecl*, 16> Params; |
6214 | FT = cast<FunctionProtoType>(Val&: OverloadTy); |
6215 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
6216 | QualType ParamType = FT->getParamType(i); |
6217 | ParmVarDecl *Parm = |
6218 | ParmVarDecl::Create(C&: Context, DC: OverloadDecl, StartLoc: SourceLocation(), |
6219 | IdLoc: SourceLocation(), Id: nullptr, T: ParamType, |
6220 | /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr); |
6221 | Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i); |
6222 | Params.push_back(Elt: Parm); |
6223 | } |
6224 | OverloadDecl->setParams(Params); |
6225 | Sema->mergeDeclAttributes(New: OverloadDecl, Old: FDecl); |
6226 | return OverloadDecl; |
6227 | } |
6228 | |
6229 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, |
6230 | FunctionDecl *Callee, |
6231 | MultiExprArg ArgExprs) { |
6232 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and |
6233 | // similar attributes) really don't like it when functions are called with an |
6234 | // invalid number of args. |
6235 | if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(), |
6236 | /*PartialOverloading=*/false) && |
6237 | !Callee->isVariadic()) |
6238 | return; |
6239 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) |
6240 | return; |
6241 | |
6242 | if (const EnableIfAttr *Attr = |
6243 | S.CheckEnableIf(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: true)) { |
6244 | S.Diag(Loc: Fn->getBeginLoc(), |
6245 | DiagID: isa<CXXMethodDecl>(Val: Callee) |
6246 | ? diag::err_ovl_no_viable_member_function_in_call |
6247 | : diag::err_ovl_no_viable_function_in_call) |
6248 | << Callee << Callee->getSourceRange(); |
6249 | S.Diag(Loc: Callee->getLocation(), |
6250 | DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr) |
6251 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
6252 | return; |
6253 | } |
6254 | } |
6255 | |
6256 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( |
6257 | const UnresolvedMemberExpr *const UME, Sema &S) { |
6258 | |
6259 | const auto GetFunctionLevelDCIfCXXClass = |
6260 | [](Sema &S) -> const CXXRecordDecl * { |
6261 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); |
6262 | if (!DC || !DC->getParent()) |
6263 | return nullptr; |
6264 | |
6265 | // If the call to some member function was made from within a member |
6266 | // function body 'M' return return 'M's parent. |
6267 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC)) |
6268 | return MD->getParent()->getCanonicalDecl(); |
6269 | // else the call was made from within a default member initializer of a |
6270 | // class, so return the class. |
6271 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) |
6272 | return RD->getCanonicalDecl(); |
6273 | return nullptr; |
6274 | }; |
6275 | // If our DeclContext is neither a member function nor a class (in the |
6276 | // case of a lambda in a default member initializer), we can't have an |
6277 | // enclosing 'this'. |
6278 | |
6279 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); |
6280 | if (!CurParentClass) |
6281 | return false; |
6282 | |
6283 | // The naming class for implicit member functions call is the class in which |
6284 | // name lookup starts. |
6285 | const CXXRecordDecl *const NamingClass = |
6286 | UME->getNamingClass()->getCanonicalDecl(); |
6287 | assert(NamingClass && "Must have naming class even for implicit access" ); |
6288 | |
6289 | // If the unresolved member functions were found in a 'naming class' that is |
6290 | // related (either the same or derived from) to the class that contains the |
6291 | // member function that itself contained the implicit member access. |
6292 | |
6293 | return CurParentClass == NamingClass || |
6294 | CurParentClass->isDerivedFrom(Base: NamingClass); |
6295 | } |
6296 | |
6297 | static void |
6298 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
6299 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { |
6300 | |
6301 | if (!UME) |
6302 | return; |
6303 | |
6304 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); |
6305 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't |
6306 | // already been captured, or if this is an implicit member function call (if |
6307 | // it isn't, an attempt to capture 'this' should already have been made). |
6308 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || |
6309 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) |
6310 | return; |
6311 | |
6312 | // Check if the naming class in which the unresolved members were found is |
6313 | // related (same as or is a base of) to the enclosing class. |
6314 | |
6315 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) |
6316 | return; |
6317 | |
6318 | |
6319 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); |
6320 | // If the enclosing function is not dependent, then this lambda is |
6321 | // capture ready, so if we can capture this, do so. |
6322 | if (!EnclosingFunctionCtx->isDependentContext()) { |
6323 | // If the current lambda and all enclosing lambdas can capture 'this' - |
6324 | // then go ahead and capture 'this' (since our unresolved overload set |
6325 | // contains at least one non-static member function). |
6326 | if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false)) |
6327 | S.CheckCXXThisCapture(Loc: CallLoc); |
6328 | } else if (S.CurContext->isDependentContext()) { |
6329 | // ... since this is an implicit member reference, that might potentially |
6330 | // involve a 'this' capture, mark 'this' for potential capture in |
6331 | // enclosing lambdas. |
6332 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) |
6333 | CurLSI->addPotentialThisCapture(Loc: CallLoc); |
6334 | } |
6335 | } |
6336 | |
6337 | // Once a call is fully resolved, warn for unqualified calls to specific |
6338 | // C++ standard functions, like move and forward. |
6339 | static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, |
6340 | const CallExpr *Call) { |
6341 | // We are only checking unary move and forward so exit early here. |
6342 | if (Call->getNumArgs() != 1) |
6343 | return; |
6344 | |
6345 | const Expr *E = Call->getCallee()->IgnoreParenImpCasts(); |
6346 | if (!E || isa<UnresolvedLookupExpr>(Val: E)) |
6347 | return; |
6348 | const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E); |
6349 | if (!DRE || !DRE->getLocation().isValid()) |
6350 | return; |
6351 | |
6352 | if (DRE->getQualifier()) |
6353 | return; |
6354 | |
6355 | const FunctionDecl *FD = Call->getDirectCallee(); |
6356 | if (!FD) |
6357 | return; |
6358 | |
6359 | // Only warn for some functions deemed more frequent or problematic. |
6360 | unsigned BuiltinID = FD->getBuiltinID(); |
6361 | if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) |
6362 | return; |
6363 | |
6364 | S.Diag(Loc: DRE->getLocation(), DiagID: diag::warn_unqualified_call_to_std_cast_function) |
6365 | << FD->getQualifiedNameAsString() |
6366 | << FixItHint::CreateInsertion(InsertionLoc: DRE->getLocation(), Code: "std::" ); |
6367 | } |
6368 | |
6369 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
6370 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6371 | Expr *ExecConfig) { |
6372 | ExprResult Call = |
6373 | BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, |
6374 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); |
6375 | if (Call.isInvalid()) |
6376 | return Call; |
6377 | |
6378 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier |
6379 | // language modes. |
6380 | if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn); |
6381 | ULE && ULE->hasExplicitTemplateArgs() && |
6382 | ULE->decls_begin() == ULE->decls_end()) { |
6383 | Diag(Loc: Fn->getExprLoc(), DiagID: getLangOpts().CPlusPlus20 |
6384 | ? diag::warn_cxx17_compat_adl_only_template_id |
6385 | : diag::ext_adl_only_template_id) |
6386 | << ULE->getName(); |
6387 | } |
6388 | |
6389 | if (LangOpts.OpenMP) |
6390 | Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, |
6391 | ExecConfig); |
6392 | if (LangOpts.CPlusPlus) { |
6393 | if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get())) |
6394 | DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE); |
6395 | |
6396 | // If we previously found that the id-expression of this call refers to a |
6397 | // consteval function but the call is dependent, we should not treat is an |
6398 | // an invalid immediate call. |
6399 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens()); |
6400 | DRE && Call.get()->isValueDependent()) { |
6401 | currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE); |
6402 | } |
6403 | } |
6404 | return Call; |
6405 | } |
6406 | |
6407 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
6408 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6409 | Expr *ExecConfig, bool IsExecConfig, |
6410 | bool AllowRecovery) { |
6411 | // Since this might be a postfix expression, get rid of ParenListExprs. |
6412 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn); |
6413 | if (Result.isInvalid()) return ExprError(); |
6414 | Fn = Result.get(); |
6415 | |
6416 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
6417 | return ExprError(); |
6418 | |
6419 | if (getLangOpts().CPlusPlus) { |
6420 | // If this is a pseudo-destructor expression, build the call immediately. |
6421 | if (isa<CXXPseudoDestructorExpr>(Val: Fn)) { |
6422 | if (!ArgExprs.empty()) { |
6423 | // Pseudo-destructor calls should not have any arguments. |
6424 | Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_pseudo_dtor_call_with_args) |
6425 | << FixItHint::CreateRemoval( |
6426 | RemoveRange: SourceRange(ArgExprs.front()->getBeginLoc(), |
6427 | ArgExprs.back()->getEndLoc())); |
6428 | } |
6429 | |
6430 | return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy, |
6431 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6432 | } |
6433 | if (Fn->getType() == Context.PseudoObjectTy) { |
6434 | ExprResult result = CheckPlaceholderExpr(E: Fn); |
6435 | if (result.isInvalid()) return ExprError(); |
6436 | Fn = result.get(); |
6437 | } |
6438 | |
6439 | // Determine whether this is a dependent call inside a C++ template, |
6440 | // in which case we won't do any semantic analysis now. |
6441 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) { |
6442 | if (ExecConfig) { |
6443 | return CUDAKernelCallExpr::Create(Ctx: Context, Fn, |
6444 | Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs, |
6445 | Ty: Context.DependentTy, VK: VK_PRValue, |
6446 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6447 | } else { |
6448 | |
6449 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
6450 | S&: *this, UME: dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()), |
6451 | CallLoc: Fn->getBeginLoc()); |
6452 | |
6453 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6454 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6455 | } |
6456 | } |
6457 | |
6458 | // Determine whether this is a call to an object (C++ [over.call.object]). |
6459 | if (Fn->getType()->isRecordType()) |
6460 | return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs, |
6461 | RParenLoc); |
6462 | |
6463 | if (Fn->getType() == Context.UnknownAnyTy) { |
6464 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6465 | if (result.isInvalid()) return ExprError(); |
6466 | Fn = result.get(); |
6467 | } |
6468 | |
6469 | if (Fn->getType() == Context.BoundMemberTy) { |
6470 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
6471 | RParenLoc, ExecConfig, IsExecConfig, |
6472 | AllowRecovery); |
6473 | } |
6474 | } |
6475 | |
6476 | // Check for overloaded calls. This can happen even in C due to extensions. |
6477 | if (Fn->getType() == Context.OverloadTy) { |
6478 | OverloadExpr::FindResult find = OverloadExpr::find(E: Fn); |
6479 | |
6480 | // We aren't supposed to apply this logic if there's an '&' involved. |
6481 | if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) { |
6482 | if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) |
6483 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6484 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6485 | OverloadExpr *ovl = find.Expression; |
6486 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl)) |
6487 | return BuildOverloadedCallExpr( |
6488 | S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig, |
6489 | /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand); |
6490 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
6491 | RParenLoc, ExecConfig, IsExecConfig, |
6492 | AllowRecovery); |
6493 | } |
6494 | } |
6495 | |
6496 | // If we're directly calling a function, get the appropriate declaration. |
6497 | if (Fn->getType() == Context.UnknownAnyTy) { |
6498 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6499 | if (result.isInvalid()) return ExprError(); |
6500 | Fn = result.get(); |
6501 | } |
6502 | |
6503 | Expr *NakedFn = Fn->IgnoreParens(); |
6504 | |
6505 | bool CallingNDeclIndirectly = false; |
6506 | NamedDecl *NDecl = nullptr; |
6507 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) { |
6508 | if (UnOp->getOpcode() == UO_AddrOf) { |
6509 | CallingNDeclIndirectly = true; |
6510 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); |
6511 | } |
6512 | } |
6513 | |
6514 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) { |
6515 | NDecl = DRE->getDecl(); |
6516 | |
6517 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl); |
6518 | if (FDecl && FDecl->getBuiltinID()) { |
6519 | // Rewrite the function decl for this builtin by replacing parameters |
6520 | // with no explicit address space with the address space of the arguments |
6521 | // in ArgExprs. |
6522 | if ((FDecl = |
6523 | rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) { |
6524 | NDecl = FDecl; |
6525 | Fn = DeclRefExpr::Create( |
6526 | Context, QualifierLoc: FDecl->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: FDecl, RefersToEnclosingVariableOrCapture: false, |
6527 | NameLoc: SourceLocation(), T: FDecl->getType(), VK: Fn->getValueKind(), FoundD: FDecl, |
6528 | TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse()); |
6529 | } |
6530 | } |
6531 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn)) |
6532 | NDecl = ME->getMemberDecl(); |
6533 | |
6534 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) { |
6535 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( |
6536 | Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc())) |
6537 | return ExprError(); |
6538 | |
6539 | checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs); |
6540 | |
6541 | // If this expression is a call to a builtin function in HIP device |
6542 | // compilation, allow a pointer-type argument to default address space to be |
6543 | // passed as a pointer-type parameter to a non-default address space. |
6544 | // If Arg is declared in the default address space and Param is declared |
6545 | // in a non-default address space, perform an implicit address space cast to |
6546 | // the parameter type. |
6547 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && |
6548 | FD->getBuiltinID()) { |
6549 | for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size(); |
6550 | ++Idx) { |
6551 | ParmVarDecl *Param = FD->getParamDecl(i: Idx); |
6552 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || |
6553 | !ArgExprs[Idx]->getType()->isPointerType()) |
6554 | continue; |
6555 | |
6556 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); |
6557 | auto ArgTy = ArgExprs[Idx]->getType(); |
6558 | auto ArgPtTy = ArgTy->getPointeeType(); |
6559 | auto ArgAS = ArgPtTy.getAddressSpace(); |
6560 | |
6561 | // Add address space cast if target address spaces are different |
6562 | bool NeedImplicitASC = |
6563 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. |
6564 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS |
6565 | // or from specific AS which has target AS matching that of Param. |
6566 | getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS)); |
6567 | if (!NeedImplicitASC) |
6568 | continue; |
6569 | |
6570 | // First, ensure that the Arg is an RValue. |
6571 | if (ArgExprs[Idx]->isGLValue()) { |
6572 | ArgExprs[Idx] = ImplicitCastExpr::Create( |
6573 | Context, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx], |
6574 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
6575 | } |
6576 | |
6577 | // Construct a new arg type with address space of Param |
6578 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); |
6579 | ArgPtQuals.setAddressSpace(ParamAS); |
6580 | auto NewArgPtTy = |
6581 | Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals); |
6582 | auto NewArgTy = |
6583 | Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy), |
6584 | Qs: ArgTy.getQualifiers()); |
6585 | |
6586 | // Finally perform an implicit address space cast |
6587 | ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy, |
6588 | CK: CK_AddressSpaceConversion) |
6589 | .get(); |
6590 | } |
6591 | } |
6592 | } |
6593 | |
6594 | if (Context.isDependenceAllowed() && |
6595 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) { |
6596 | assert(!getLangOpts().CPlusPlus); |
6597 | assert((Fn->containsErrors() || |
6598 | llvm::any_of(ArgExprs, |
6599 | [](clang::Expr *E) { return E->containsErrors(); })) && |
6600 | "should only occur in error-recovery path." ); |
6601 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6602 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6603 | } |
6604 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc, |
6605 | Config: ExecConfig, IsExecConfig); |
6606 | } |
6607 | |
6608 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, |
6609 | MultiExprArg CallArgs) { |
6610 | StringRef Name = Context.BuiltinInfo.getName(ID: Id); |
6611 | LookupResult R(*this, &Context.Idents.get(Name), Loc, |
6612 | Sema::LookupOrdinaryName); |
6613 | LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true); |
6614 | |
6615 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); |
6616 | assert(BuiltInDecl && "failed to find builtin declaration" ); |
6617 | |
6618 | ExprResult DeclRef = |
6619 | BuildDeclRefExpr(D: BuiltInDecl, Ty: BuiltInDecl->getType(), VK: VK_LValue, Loc); |
6620 | assert(DeclRef.isUsable() && "Builtin reference cannot fail" ); |
6621 | |
6622 | ExprResult Call = |
6623 | BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc); |
6624 | |
6625 | assert(!Call.isInvalid() && "Call to builtin cannot fail!" ); |
6626 | return Call.get(); |
6627 | } |
6628 | |
6629 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
6630 | SourceLocation BuiltinLoc, |
6631 | SourceLocation RParenLoc) { |
6632 | QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy); |
6633 | return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc); |
6634 | } |
6635 | |
6636 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, |
6637 | SourceLocation BuiltinLoc, |
6638 | SourceLocation RParenLoc) { |
6639 | ExprValueKind VK = VK_PRValue; |
6640 | ExprObjectKind OK = OK_Ordinary; |
6641 | QualType SrcTy = E->getType(); |
6642 | if (!SrcTy->isDependentType() && |
6643 | Context.getTypeSize(T: DestTy) != Context.getTypeSize(T: SrcTy)) |
6644 | return ExprError( |
6645 | Diag(Loc: BuiltinLoc, DiagID: diag::err_invalid_astype_of_different_size) |
6646 | << DestTy << SrcTy << E->getSourceRange()); |
6647 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); |
6648 | } |
6649 | |
6650 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
6651 | SourceLocation BuiltinLoc, |
6652 | SourceLocation RParenLoc) { |
6653 | TypeSourceInfo *TInfo; |
6654 | GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo); |
6655 | return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); |
6656 | } |
6657 | |
6658 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, |
6659 | SourceLocation LParenLoc, |
6660 | ArrayRef<Expr *> Args, |
6661 | SourceLocation RParenLoc, Expr *Config, |
6662 | bool IsExecConfig, ADLCallKind UsesADL) { |
6663 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl); |
6664 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); |
6665 | |
6666 | // Functions with 'interrupt' attribute cannot be called directly. |
6667 | if (FDecl) { |
6668 | if (FDecl->hasAttr<AnyX86InterruptAttr>()) { |
6669 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_anyx86_interrupt_called); |
6670 | return ExprError(); |
6671 | } |
6672 | if (FDecl->hasAttr<ARMInterruptAttr>()) { |
6673 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::err_arm_interrupt_called); |
6674 | return ExprError(); |
6675 | } |
6676 | } |
6677 | |
6678 | // X86 interrupt handlers may only call routines with attribute |
6679 | // no_caller_saved_registers since there is no efficient way to |
6680 | // save and restore the non-GPR state. |
6681 | if (auto *Caller = getCurFunctionDecl()) { |
6682 | if (Caller->hasAttr<AnyX86InterruptAttr>() || |
6683 | Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) { |
6684 | const TargetInfo &TI = Context.getTargetInfo(); |
6685 | bool HasNonGPRRegisters = |
6686 | TI.hasFeature(Feature: "sse" ) || TI.hasFeature(Feature: "x87" ) || TI.hasFeature(Feature: "mmx" ); |
6687 | if (HasNonGPRRegisters && |
6688 | (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) { |
6689 | Diag(Loc: Fn->getExprLoc(), DiagID: diag::warn_anyx86_excessive_regsave) |
6690 | << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1); |
6691 | if (FDecl) |
6692 | Diag(Loc: FDecl->getLocation(), DiagID: diag::note_callee_decl) << FDecl; |
6693 | } |
6694 | } |
6695 | } |
6696 | |
6697 | // Promote the function operand. |
6698 | // We special-case function promotion here because we only allow promoting |
6699 | // builtin functions to function pointers in the callee of a call. |
6700 | ExprResult Result; |
6701 | QualType ResultTy; |
6702 | if (BuiltinID && |
6703 | Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) { |
6704 | // Extract the return type from the (builtin) function pointer type. |
6705 | // FIXME Several builtins still have setType in |
6706 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in |
6707 | // Builtins.td to ensure they are correct before removing setType calls. |
6708 | QualType FnPtrTy = Context.getPointerType(T: FDecl->getType()); |
6709 | Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get(); |
6710 | ResultTy = FDecl->getCallResultType(); |
6711 | } else { |
6712 | Result = CallExprUnaryConversions(E: Fn); |
6713 | ResultTy = Context.BoolTy; |
6714 | } |
6715 | if (Result.isInvalid()) |
6716 | return ExprError(); |
6717 | Fn = Result.get(); |
6718 | |
6719 | // Check for a valid function type, but only if it is not a builtin which |
6720 | // requires custom type checking. These will be handled by |
6721 | // CheckBuiltinFunctionCall below just after creation of the call expression. |
6722 | const FunctionType *FuncT = nullptr; |
6723 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
6724 | retry: |
6725 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { |
6726 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall |
6727 | // have type pointer to function". |
6728 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); |
6729 | if (!FuncT) |
6730 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function) |
6731 | << Fn->getType() << Fn->getSourceRange()); |
6732 | } else if (const BlockPointerType *BPT = |
6733 | Fn->getType()->getAs<BlockPointerType>()) { |
6734 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); |
6735 | } else { |
6736 | // Handle calls to expressions of unknown-any type. |
6737 | if (Fn->getType() == Context.UnknownAnyTy) { |
6738 | ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6739 | if (rewrite.isInvalid()) |
6740 | return ExprError(); |
6741 | Fn = rewrite.get(); |
6742 | goto retry; |
6743 | } |
6744 | |
6745 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_typecheck_call_not_function) |
6746 | << Fn->getType() << Fn->getSourceRange()); |
6747 | } |
6748 | } |
6749 | |
6750 | // Get the number of parameters in the function prototype, if any. |
6751 | // We will allocate space for max(Args.size(), NumParams) arguments |
6752 | // in the call expression. |
6753 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT); |
6754 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; |
6755 | |
6756 | CallExpr *TheCall; |
6757 | if (Config) { |
6758 | assert(UsesADL == ADLCallKind::NotADL && |
6759 | "CUDAKernelCallExpr should not use ADL" ); |
6760 | TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), |
6761 | Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc, |
6762 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams); |
6763 | } else { |
6764 | TheCall = |
6765 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc, |
6766 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL); |
6767 | } |
6768 | |
6769 | if (!Context.isDependenceAllowed()) { |
6770 | // Forget about the nulled arguments since typo correction |
6771 | // do not handle them well. |
6772 | TheCall->shrinkNumArgs(NewNumArgs: Args.size()); |
6773 | // C cannot always handle TypoExpr nodes in builtin calls and direct |
6774 | // function calls as their argument checking don't necessarily handle |
6775 | // dependent types properly, so make sure any TypoExprs have been |
6776 | // dealt with. |
6777 | ExprResult Result = CorrectDelayedTyposInExpr(E: TheCall); |
6778 | if (!Result.isUsable()) return ExprError(); |
6779 | CallExpr *TheOldCall = TheCall; |
6780 | TheCall = dyn_cast<CallExpr>(Val: Result.get()); |
6781 | bool CorrectedTypos = TheCall != TheOldCall; |
6782 | if (!TheCall) return Result; |
6783 | Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); |
6784 | |
6785 | // A new call expression node was created if some typos were corrected. |
6786 | // However it may not have been constructed with enough storage. In this |
6787 | // case, rebuild the node with enough storage. The waste of space is |
6788 | // immaterial since this only happens when some typos were corrected. |
6789 | if (CorrectedTypos && Args.size() < NumParams) { |
6790 | if (Config) |
6791 | TheCall = CUDAKernelCallExpr::Create( |
6792 | Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), Args, Ty: ResultTy, VK: VK_PRValue, |
6793 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams); |
6794 | else |
6795 | TheCall = |
6796 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc, |
6797 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL); |
6798 | } |
6799 | // We can now handle the nulled arguments for the default arguments. |
6800 | TheCall->setNumArgsUnsafe(std::max<unsigned>(a: Args.size(), b: NumParams)); |
6801 | } |
6802 | |
6803 | // Bail out early if calling a builtin with custom type checking. |
6804 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
6805 | ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
6806 | if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID)) |
6807 | E = CheckForImmediateInvocation(E, Decl: FDecl); |
6808 | return E; |
6809 | } |
6810 | |
6811 | if (getLangOpts().CUDA) { |
6812 | if (Config) { |
6813 | // CUDA: Kernel calls must be to global functions |
6814 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) |
6815 | return ExprError(Diag(Loc: LParenLoc,DiagID: diag::err_kern_call_not_global_function) |
6816 | << FDecl << Fn->getSourceRange()); |
6817 | |
6818 | // CUDA: Kernel function must have 'void' return type |
6819 | if (!FuncT->getReturnType()->isVoidType() && |
6820 | !FuncT->getReturnType()->getAs<AutoType>() && |
6821 | !FuncT->getReturnType()->isInstantiationDependentType()) |
6822 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_kern_type_not_void_return) |
6823 | << Fn->getType() << Fn->getSourceRange()); |
6824 | } else { |
6825 | // CUDA: Calls to global functions must be configured |
6826 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) |
6827 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_global_call_not_config) |
6828 | << FDecl << Fn->getSourceRange()); |
6829 | } |
6830 | } |
6831 | |
6832 | // Check for a valid return type |
6833 | if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall, |
6834 | FD: FDecl)) |
6835 | return ExprError(); |
6836 | |
6837 | // We know the result type of the call, set it. |
6838 | TheCall->setType(FuncT->getCallResultType(Context)); |
6839 | TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType())); |
6840 | |
6841 | // WebAssembly tables can't be used as arguments. |
6842 | if (Context.getTargetInfo().getTriple().isWasm()) { |
6843 | for (const Expr *Arg : Args) { |
6844 | if (Arg && Arg->getType()->isWebAssemblyTableType()) { |
6845 | return ExprError(Diag(Loc: Arg->getExprLoc(), |
6846 | DiagID: diag::err_wasm_table_as_function_parameter)); |
6847 | } |
6848 | } |
6849 | } |
6850 | |
6851 | if (Proto) { |
6852 | if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc, |
6853 | IsExecConfig)) |
6854 | return ExprError(); |
6855 | } else { |
6856 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ); |
6857 | |
6858 | if (FDecl) { |
6859 | // Check if we have too few/too many template arguments, based |
6860 | // on our knowledge of the function definition. |
6861 | const FunctionDecl *Def = nullptr; |
6862 | if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) { |
6863 | Proto = Def->getType()->getAs<FunctionProtoType>(); |
6864 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) |
6865 | Diag(Loc: RParenLoc, DiagID: diag::warn_call_wrong_number_of_arguments) |
6866 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); |
6867 | } |
6868 | |
6869 | // If the function we're calling isn't a function prototype, but we have |
6870 | // a function prototype from a prior declaratiom, use that prototype. |
6871 | if (!FDecl->hasPrototype()) |
6872 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); |
6873 | } |
6874 | |
6875 | // If we still haven't found a prototype to use but there are arguments to |
6876 | // the call, diagnose this as calling a function without a prototype. |
6877 | // However, if we found a function declaration, check to see if |
6878 | // -Wdeprecated-non-prototype was disabled where the function was declared. |
6879 | // If so, we will silence the diagnostic here on the assumption that this |
6880 | // interface is intentional and the user knows what they're doing. We will |
6881 | // also silence the diagnostic if there is a function declaration but it |
6882 | // was implicitly defined (the user already gets diagnostics about the |
6883 | // creation of the implicit function declaration, so the additional warning |
6884 | // is not helpful). |
6885 | if (!Proto && !Args.empty() && |
6886 | (!FDecl || (!FDecl->isImplicit() && |
6887 | !Diags.isIgnored(DiagID: diag::warn_strict_uses_without_prototype, |
6888 | Loc: FDecl->getLocation())))) |
6889 | Diag(Loc: LParenLoc, DiagID: diag::warn_strict_uses_without_prototype) |
6890 | << (FDecl != nullptr) << FDecl; |
6891 | |
6892 | // Promote the arguments (C99 6.5.2.2p6). |
6893 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
6894 | Expr *Arg = Args[i]; |
6895 | |
6896 | if (Proto && i < Proto->getNumParams()) { |
6897 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
6898 | Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i)); |
6899 | ExprResult ArgE = |
6900 | PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg); |
6901 | if (ArgE.isInvalid()) |
6902 | return true; |
6903 | |
6904 | Arg = ArgE.getAs<Expr>(); |
6905 | |
6906 | } else { |
6907 | ExprResult ArgE = DefaultArgumentPromotion(E: Arg); |
6908 | |
6909 | if (ArgE.isInvalid()) |
6910 | return true; |
6911 | |
6912 | Arg = ArgE.getAs<Expr>(); |
6913 | } |
6914 | |
6915 | if (RequireCompleteType(Loc: Arg->getBeginLoc(), T: Arg->getType(), |
6916 | DiagID: diag::err_call_incomplete_argument, Args: Arg)) |
6917 | return ExprError(); |
6918 | |
6919 | TheCall->setArg(Arg: i, ArgExpr: Arg); |
6920 | } |
6921 | TheCall->computeDependence(); |
6922 | } |
6923 | |
6924 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl)) |
6925 | if (!isa<RequiresExprBodyDecl>(Val: CurContext) && |
6926 | Method->isImplicitObjectMemberFunction()) |
6927 | return ExprError(Diag(Loc: LParenLoc, DiagID: diag::err_member_call_without_object) |
6928 | << Fn->getSourceRange() << 0); |
6929 | |
6930 | // Check for sentinels |
6931 | if (NDecl) |
6932 | DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args); |
6933 | |
6934 | // Warn for unions passing across security boundary (CMSE). |
6935 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { |
6936 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
6937 | if (const auto *RT = |
6938 | dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) { |
6939 | if (RT->getDecl()->isOrContainsUnion()) |
6940 | Diag(Loc: Args[i]->getBeginLoc(), DiagID: diag::warn_cmse_nonsecure_union) |
6941 | << 0 << i; |
6942 | } |
6943 | } |
6944 | } |
6945 | |
6946 | // Do special checking on direct calls to functions. |
6947 | if (FDecl) { |
6948 | if (CheckFunctionCall(FDecl, TheCall, Proto)) |
6949 | return ExprError(); |
6950 | |
6951 | checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall); |
6952 | |
6953 | if (BuiltinID) |
6954 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
6955 | } else if (NDecl) { |
6956 | if (CheckPointerCall(NDecl, TheCall, Proto)) |
6957 | return ExprError(); |
6958 | } else { |
6959 | if (CheckOtherCall(TheCall, Proto)) |
6960 | return ExprError(); |
6961 | } |
6962 | |
6963 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FDecl); |
6964 | } |
6965 | |
6966 | ExprResult |
6967 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, |
6968 | SourceLocation RParenLoc, Expr *InitExpr) { |
6969 | assert(Ty && "ActOnCompoundLiteral(): missing type" ); |
6970 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression" ); |
6971 | |
6972 | TypeSourceInfo *TInfo; |
6973 | QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo); |
6974 | if (!TInfo) |
6975 | TInfo = Context.getTrivialTypeSourceInfo(T: literalType); |
6976 | |
6977 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr); |
6978 | } |
6979 | |
6980 | ExprResult |
6981 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, |
6982 | SourceLocation RParenLoc, Expr *LiteralExpr) { |
6983 | QualType literalType = TInfo->getType(); |
6984 | |
6985 | if (literalType->isArrayType()) { |
6986 | if (RequireCompleteSizedType( |
6987 | Loc: LParenLoc, T: Context.getBaseElementType(QT: literalType), |
6988 | DiagID: diag::err_array_incomplete_or_sizeless_type, |
6989 | Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
6990 | return ExprError(); |
6991 | if (literalType->isVariableArrayType()) { |
6992 | // C23 6.7.10p4: An entity of variable length array type shall not be |
6993 | // initialized except by an empty initializer. |
6994 | // |
6995 | // The C extension warnings are issued from ParseBraceInitializer() and |
6996 | // do not need to be issued here. However, we continue to issue an error |
6997 | // in the case there are initializers or we are compiling C++. We allow |
6998 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
6999 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
7000 | // FIXME: should we allow this construct in C++ when it makes sense to do |
7001 | // so? |
7002 | // |
7003 | // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name |
7004 | // shall specify an object type or an array of unknown size, but not a |
7005 | // variable length array type. This seems odd, as it allows 'int a[size] = |
7006 | // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard |
7007 | // says, this is what's implemented here for C (except for the extension |
7008 | // that permits constant foldable size arrays) |
7009 | |
7010 | auto diagID = LangOpts.CPlusPlus |
7011 | ? diag::err_variable_object_no_init |
7012 | : diag::err_compound_literal_with_vla_type; |
7013 | if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc, |
7014 | FailedFoldDiagID: diagID)) |
7015 | return ExprError(); |
7016 | } |
7017 | } else if (!literalType->isDependentType() && |
7018 | RequireCompleteType(Loc: LParenLoc, T: literalType, |
7019 | DiagID: diag::err_typecheck_decl_incomplete_type, |
7020 | Args: SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
7021 | return ExprError(); |
7022 | |
7023 | InitializedEntity Entity |
7024 | = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo); |
7025 | InitializationKind Kind |
7026 | = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc, |
7027 | TypeRange: SourceRange(LParenLoc, RParenLoc), |
7028 | /*InitList=*/true); |
7029 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); |
7030 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr, |
7031 | ResultType: &literalType); |
7032 | if (Result.isInvalid()) |
7033 | return ExprError(); |
7034 | LiteralExpr = Result.get(); |
7035 | |
7036 | bool isFileScope = !CurContext->isFunctionOrMethod(); |
7037 | |
7038 | // In C, compound literals are l-values for some reason. |
7039 | // For GCC compatibility, in C++, file-scope array compound literals with |
7040 | // constant initializers are also l-values, and compound literals are |
7041 | // otherwise prvalues. |
7042 | // |
7043 | // (GCC also treats C++ list-initialized file-scope array prvalues with |
7044 | // constant initializers as l-values, but that's non-conforming, so we don't |
7045 | // follow it there.) |
7046 | // |
7047 | // FIXME: It would be better to handle the lvalue cases as materializing and |
7048 | // lifetime-extending a temporary object, but our materialized temporaries |
7049 | // representation only supports lifetime extension from a variable, not "out |
7050 | // of thin air". |
7051 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer |
7052 | // is bound to the result of applying array-to-pointer decay to the compound |
7053 | // literal. |
7054 | // FIXME: GCC supports compound literals of reference type, which should |
7055 | // obviously have a value kind derived from the kind of reference involved. |
7056 | ExprValueKind VK = |
7057 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) |
7058 | ? VK_PRValue |
7059 | : VK_LValue; |
7060 | |
7061 | if (isFileScope) |
7062 | if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) |
7063 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { |
7064 | Expr *Init = ILE->getInit(Init: i); |
7065 | ILE->setInit(Init: i, expr: ConstantExpr::Create(Context, E: Init)); |
7066 | } |
7067 | |
7068 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, |
7069 | VK, LiteralExpr, isFileScope); |
7070 | if (isFileScope) { |
7071 | if (!LiteralExpr->isTypeDependent() && |
7072 | !LiteralExpr->isValueDependent() && |
7073 | !literalType->isDependentType()) // C99 6.5.2.5p3 |
7074 | if (CheckForConstantInitializer(Init: LiteralExpr)) |
7075 | return ExprError(); |
7076 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && |
7077 | literalType.getAddressSpace() != LangAS::Default) { |
7078 | // Embedded-C extensions to C99 6.5.2.5: |
7079 | // "If the compound literal occurs inside the body of a function, the |
7080 | // type name shall not be qualified by an address-space qualifier." |
7081 | Diag(Loc: LParenLoc, DiagID: diag::err_compound_literal_with_address_space) |
7082 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); |
7083 | return ExprError(); |
7084 | } |
7085 | |
7086 | if (!isFileScope && !getLangOpts().CPlusPlus) { |
7087 | // Compound literals that have automatic storage duration are destroyed at |
7088 | // the end of the scope in C; in C++, they're just temporaries. |
7089 | |
7090 | // Emit diagnostics if it is or contains a C union type that is non-trivial |
7091 | // to destruct. |
7092 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) |
7093 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
7094 | UseContext: NTCUC_CompoundLiteral, NonTrivialKind: NTCUK_Destruct); |
7095 | |
7096 | // Diagnose jumps that enter or exit the lifetime of the compound literal. |
7097 | if (literalType.isDestructedType()) { |
7098 | Cleanup.setExprNeedsCleanups(true); |
7099 | ExprCleanupObjects.push_back(Elt: E); |
7100 | getCurFunction()->setHasBranchProtectedScope(); |
7101 | } |
7102 | } |
7103 | |
7104 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
7105 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
7106 | checkNonTrivialCUnionInInitializer(Init: E->getInitializer(), |
7107 | Loc: E->getInitializer()->getExprLoc()); |
7108 | |
7109 | return MaybeBindToTemporary(E); |
7110 | } |
7111 | |
7112 | ExprResult |
7113 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7114 | SourceLocation RBraceLoc) { |
7115 | // Only produce each kind of designated initialization diagnostic once. |
7116 | SourceLocation FirstDesignator; |
7117 | bool DiagnosedArrayDesignator = false; |
7118 | bool DiagnosedNestedDesignator = false; |
7119 | bool DiagnosedMixedDesignator = false; |
7120 | |
7121 | // Check that any designated initializers are syntactically valid in the |
7122 | // current language mode. |
7123 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
7124 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) { |
7125 | if (FirstDesignator.isInvalid()) |
7126 | FirstDesignator = DIE->getBeginLoc(); |
7127 | |
7128 | if (!getLangOpts().CPlusPlus) |
7129 | break; |
7130 | |
7131 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { |
7132 | DiagnosedNestedDesignator = true; |
7133 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_nested) |
7134 | << DIE->getDesignatorsSourceRange(); |
7135 | } |
7136 | |
7137 | for (auto &Desig : DIE->designators()) { |
7138 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { |
7139 | DiagnosedArrayDesignator = true; |
7140 | Diag(Loc: Desig.getBeginLoc(), DiagID: diag::ext_designated_init_array) |
7141 | << Desig.getSourceRange(); |
7142 | } |
7143 | } |
7144 | |
7145 | if (!DiagnosedMixedDesignator && |
7146 | !isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
7147 | DiagnosedMixedDesignator = true; |
7148 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed) |
7149 | << DIE->getSourceRange(); |
7150 | Diag(Loc: InitArgList[0]->getBeginLoc(), DiagID: diag::note_designated_init_mixed) |
7151 | << InitArgList[0]->getSourceRange(); |
7152 | } |
7153 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && |
7154 | isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
7155 | DiagnosedMixedDesignator = true; |
7156 | auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]); |
7157 | Diag(Loc: DIE->getBeginLoc(), DiagID: diag::ext_designated_init_mixed) |
7158 | << DIE->getSourceRange(); |
7159 | Diag(Loc: InitArgList[I]->getBeginLoc(), DiagID: diag::note_designated_init_mixed) |
7160 | << InitArgList[I]->getSourceRange(); |
7161 | } |
7162 | } |
7163 | |
7164 | if (FirstDesignator.isValid()) { |
7165 | // Only diagnose designated initiaization as a C++20 extension if we didn't |
7166 | // already diagnose use of (non-C++20) C99 designator syntax. |
7167 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && |
7168 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { |
7169 | Diag(Loc: FirstDesignator, DiagID: getLangOpts().CPlusPlus20 |
7170 | ? diag::warn_cxx17_compat_designated_init |
7171 | : diag::ext_cxx_designated_init); |
7172 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { |
7173 | Diag(Loc: FirstDesignator, DiagID: diag::ext_designated_init); |
7174 | } |
7175 | } |
7176 | |
7177 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); |
7178 | } |
7179 | |
7180 | ExprResult |
7181 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7182 | SourceLocation RBraceLoc) { |
7183 | // Semantic analysis for initializers is done by ActOnDeclarator() and |
7184 | // CheckInitializer() - it requires knowledge of the object being initialized. |
7185 | |
7186 | // Immediately handle non-overload placeholders. Overloads can be |
7187 | // resolved contextually, but everything else here can't. |
7188 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
7189 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { |
7190 | ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]); |
7191 | |
7192 | // Ignore failures; dropping the entire initializer list because |
7193 | // of one failure would be terrible for indexing/etc. |
7194 | if (result.isInvalid()) continue; |
7195 | |
7196 | InitArgList[I] = result.get(); |
7197 | } |
7198 | } |
7199 | |
7200 | InitListExpr *E = |
7201 | new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc); |
7202 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. |
7203 | return E; |
7204 | } |
7205 | |
7206 | void Sema::maybeExtendBlockObject(ExprResult &E) { |
7207 | assert(E.get()->getType()->isBlockPointerType()); |
7208 | assert(E.get()->isPRValue()); |
7209 | |
7210 | // Only do this in an r-value context. |
7211 | if (!getLangOpts().ObjCAutoRefCount) return; |
7212 | |
7213 | E = ImplicitCastExpr::Create( |
7214 | Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(), |
7215 | /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
7216 | Cleanup.setExprNeedsCleanups(true); |
7217 | } |
7218 | |
7219 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { |
7220 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. |
7221 | // Also, callers should have filtered out the invalid cases with |
7222 | // pointers. Everything else should be possible. |
7223 | |
7224 | QualType SrcTy = Src.get()->getType(); |
7225 | if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy)) |
7226 | return CK_NoOp; |
7227 | |
7228 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { |
7229 | case Type::STK_MemberPointer: |
7230 | llvm_unreachable("member pointer type in C" ); |
7231 | |
7232 | case Type::STK_CPointer: |
7233 | case Type::STK_BlockPointer: |
7234 | case Type::STK_ObjCObjectPointer: |
7235 | switch (DestTy->getScalarTypeKind()) { |
7236 | case Type::STK_CPointer: { |
7237 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); |
7238 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); |
7239 | if (SrcAS != DestAS) |
7240 | return CK_AddressSpaceConversion; |
7241 | if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy)) |
7242 | return CK_NoOp; |
7243 | return CK_BitCast; |
7244 | } |
7245 | case Type::STK_BlockPointer: |
7246 | return (SrcKind == Type::STK_BlockPointer |
7247 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); |
7248 | case Type::STK_ObjCObjectPointer: |
7249 | if (SrcKind == Type::STK_ObjCObjectPointer) |
7250 | return CK_BitCast; |
7251 | if (SrcKind == Type::STK_CPointer) |
7252 | return CK_CPointerToObjCPointerCast; |
7253 | maybeExtendBlockObject(E&: Src); |
7254 | return CK_BlockPointerToObjCPointerCast; |
7255 | case Type::STK_Bool: |
7256 | return CK_PointerToBoolean; |
7257 | case Type::STK_Integral: |
7258 | return CK_PointerToIntegral; |
7259 | case Type::STK_Floating: |
7260 | case Type::STK_FloatingComplex: |
7261 | case Type::STK_IntegralComplex: |
7262 | case Type::STK_MemberPointer: |
7263 | case Type::STK_FixedPoint: |
7264 | llvm_unreachable("illegal cast from pointer" ); |
7265 | } |
7266 | llvm_unreachable("Should have returned before this" ); |
7267 | |
7268 | case Type::STK_FixedPoint: |
7269 | switch (DestTy->getScalarTypeKind()) { |
7270 | case Type::STK_FixedPoint: |
7271 | return CK_FixedPointCast; |
7272 | case Type::STK_Bool: |
7273 | return CK_FixedPointToBoolean; |
7274 | case Type::STK_Integral: |
7275 | return CK_FixedPointToIntegral; |
7276 | case Type::STK_Floating: |
7277 | return CK_FixedPointToFloating; |
7278 | case Type::STK_IntegralComplex: |
7279 | case Type::STK_FloatingComplex: |
7280 | Diag(Loc: Src.get()->getExprLoc(), |
7281 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
7282 | << DestTy; |
7283 | return CK_IntegralCast; |
7284 | case Type::STK_CPointer: |
7285 | case Type::STK_ObjCObjectPointer: |
7286 | case Type::STK_BlockPointer: |
7287 | case Type::STK_MemberPointer: |
7288 | llvm_unreachable("illegal cast to pointer type" ); |
7289 | } |
7290 | llvm_unreachable("Should have returned before this" ); |
7291 | |
7292 | case Type::STK_Bool: // casting from bool is like casting from an integer |
7293 | case Type::STK_Integral: |
7294 | switch (DestTy->getScalarTypeKind()) { |
7295 | case Type::STK_CPointer: |
7296 | case Type::STK_ObjCObjectPointer: |
7297 | case Type::STK_BlockPointer: |
7298 | if (Src.get()->isNullPointerConstant(Ctx&: Context, |
7299 | NPC: Expr::NPC_ValueDependentIsNull)) |
7300 | return CK_NullToPointer; |
7301 | return CK_IntegralToPointer; |
7302 | case Type::STK_Bool: |
7303 | return CK_IntegralToBoolean; |
7304 | case Type::STK_Integral: |
7305 | return CK_IntegralCast; |
7306 | case Type::STK_Floating: |
7307 | return CK_IntegralToFloating; |
7308 | case Type::STK_IntegralComplex: |
7309 | Src = ImpCastExprToType(E: Src.get(), |
7310 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7311 | CK: CK_IntegralCast); |
7312 | return CK_IntegralRealToComplex; |
7313 | case Type::STK_FloatingComplex: |
7314 | Src = ImpCastExprToType(E: Src.get(), |
7315 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7316 | CK: CK_IntegralToFloating); |
7317 | return CK_FloatingRealToComplex; |
7318 | case Type::STK_MemberPointer: |
7319 | llvm_unreachable("member pointer type in C" ); |
7320 | case Type::STK_FixedPoint: |
7321 | return CK_IntegralToFixedPoint; |
7322 | } |
7323 | llvm_unreachable("Should have returned before this" ); |
7324 | |
7325 | case Type::STK_Floating: |
7326 | switch (DestTy->getScalarTypeKind()) { |
7327 | case Type::STK_Floating: |
7328 | return CK_FloatingCast; |
7329 | case Type::STK_Bool: |
7330 | return CK_FloatingToBoolean; |
7331 | case Type::STK_Integral: |
7332 | return CK_FloatingToIntegral; |
7333 | case Type::STK_FloatingComplex: |
7334 | Src = ImpCastExprToType(E: Src.get(), |
7335 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7336 | CK: CK_FloatingCast); |
7337 | return CK_FloatingRealToComplex; |
7338 | case Type::STK_IntegralComplex: |
7339 | Src = ImpCastExprToType(E: Src.get(), |
7340 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7341 | CK: CK_FloatingToIntegral); |
7342 | return CK_IntegralRealToComplex; |
7343 | case Type::STK_CPointer: |
7344 | case Type::STK_ObjCObjectPointer: |
7345 | case Type::STK_BlockPointer: |
7346 | llvm_unreachable("valid float->pointer cast?" ); |
7347 | case Type::STK_MemberPointer: |
7348 | llvm_unreachable("member pointer type in C" ); |
7349 | case Type::STK_FixedPoint: |
7350 | return CK_FloatingToFixedPoint; |
7351 | } |
7352 | llvm_unreachable("Should have returned before this" ); |
7353 | |
7354 | case Type::STK_FloatingComplex: |
7355 | switch (DestTy->getScalarTypeKind()) { |
7356 | case Type::STK_FloatingComplex: |
7357 | return CK_FloatingComplexCast; |
7358 | case Type::STK_IntegralComplex: |
7359 | return CK_FloatingComplexToIntegralComplex; |
7360 | case Type::STK_Floating: { |
7361 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
7362 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
7363 | return CK_FloatingComplexToReal; |
7364 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal); |
7365 | return CK_FloatingCast; |
7366 | } |
7367 | case Type::STK_Bool: |
7368 | return CK_FloatingComplexToBoolean; |
7369 | case Type::STK_Integral: |
7370 | Src = ImpCastExprToType(E: Src.get(), |
7371 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
7372 | CK: CK_FloatingComplexToReal); |
7373 | return CK_FloatingToIntegral; |
7374 | case Type::STK_CPointer: |
7375 | case Type::STK_ObjCObjectPointer: |
7376 | case Type::STK_BlockPointer: |
7377 | llvm_unreachable("valid complex float->pointer cast?" ); |
7378 | case Type::STK_MemberPointer: |
7379 | llvm_unreachable("member pointer type in C" ); |
7380 | case Type::STK_FixedPoint: |
7381 | Diag(Loc: Src.get()->getExprLoc(), |
7382 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
7383 | << SrcTy; |
7384 | return CK_IntegralCast; |
7385 | } |
7386 | llvm_unreachable("Should have returned before this" ); |
7387 | |
7388 | case Type::STK_IntegralComplex: |
7389 | switch (DestTy->getScalarTypeKind()) { |
7390 | case Type::STK_FloatingComplex: |
7391 | return CK_IntegralComplexToFloatingComplex; |
7392 | case Type::STK_IntegralComplex: |
7393 | return CK_IntegralComplexCast; |
7394 | case Type::STK_Integral: { |
7395 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
7396 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
7397 | return CK_IntegralComplexToReal; |
7398 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal); |
7399 | return CK_IntegralCast; |
7400 | } |
7401 | case Type::STK_Bool: |
7402 | return CK_IntegralComplexToBoolean; |
7403 | case Type::STK_Floating: |
7404 | Src = ImpCastExprToType(E: Src.get(), |
7405 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
7406 | CK: CK_IntegralComplexToReal); |
7407 | return CK_IntegralToFloating; |
7408 | case Type::STK_CPointer: |
7409 | case Type::STK_ObjCObjectPointer: |
7410 | case Type::STK_BlockPointer: |
7411 | llvm_unreachable("valid complex int->pointer cast?" ); |
7412 | case Type::STK_MemberPointer: |
7413 | llvm_unreachable("member pointer type in C" ); |
7414 | case Type::STK_FixedPoint: |
7415 | Diag(Loc: Src.get()->getExprLoc(), |
7416 | DiagID: diag::err_unimplemented_conversion_with_fixed_point_type) |
7417 | << SrcTy; |
7418 | return CK_IntegralCast; |
7419 | } |
7420 | llvm_unreachable("Should have returned before this" ); |
7421 | } |
7422 | |
7423 | llvm_unreachable("Unhandled scalar cast" ); |
7424 | } |
7425 | |
7426 | static bool breakDownVectorType(QualType type, uint64_t &len, |
7427 | QualType &eltType) { |
7428 | // Vectors are simple. |
7429 | if (const VectorType *vecType = type->getAs<VectorType>()) { |
7430 | len = vecType->getNumElements(); |
7431 | eltType = vecType->getElementType(); |
7432 | assert(eltType->isScalarType()); |
7433 | return true; |
7434 | } |
7435 | |
7436 | // We allow lax conversion to and from non-vector types, but only if |
7437 | // they're real types (i.e. non-complex, non-pointer scalar types). |
7438 | if (!type->isRealType()) return false; |
7439 | |
7440 | len = 1; |
7441 | eltType = type; |
7442 | return true; |
7443 | } |
7444 | |
7445 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { |
7446 | assert(srcTy->isVectorType() || destTy->isVectorType()); |
7447 | |
7448 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { |
7449 | if (!FirstType->isSVESizelessBuiltinType()) |
7450 | return false; |
7451 | |
7452 | const auto *VecTy = SecondType->getAs<VectorType>(); |
7453 | return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData; |
7454 | }; |
7455 | |
7456 | return ValidScalableConversion(srcTy, destTy) || |
7457 | ValidScalableConversion(destTy, srcTy); |
7458 | } |
7459 | |
7460 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { |
7461 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) |
7462 | return false; |
7463 | |
7464 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); |
7465 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); |
7466 | |
7467 | return matSrcType->getNumRows() == matDestType->getNumRows() && |
7468 | matSrcType->getNumColumns() == matDestType->getNumColumns(); |
7469 | } |
7470 | |
7471 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { |
7472 | assert(DestTy->isVectorType() || SrcTy->isVectorType()); |
7473 | |
7474 | uint64_t SrcLen, DestLen; |
7475 | QualType SrcEltTy, DestEltTy; |
7476 | if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy)) |
7477 | return false; |
7478 | if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy)) |
7479 | return false; |
7480 | |
7481 | // ASTContext::getTypeSize will return the size rounded up to a |
7482 | // power of 2, so instead of using that, we need to use the raw |
7483 | // element size multiplied by the element count. |
7484 | uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy); |
7485 | uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy); |
7486 | |
7487 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); |
7488 | } |
7489 | |
7490 | bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { |
7491 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) && |
7492 | "expected at least one type to be a vector here" ); |
7493 | |
7494 | bool IsSrcTyAltivec = |
7495 | SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() == |
7496 | VectorKind::AltiVecVector) || |
7497 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
7498 | VectorKind::AltiVecBool) || |
7499 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
7500 | VectorKind::AltiVecPixel)); |
7501 | |
7502 | bool IsDestTyAltivec = DestTy->isVectorType() && |
7503 | ((DestTy->castAs<VectorType>()->getVectorKind() == |
7504 | VectorKind::AltiVecVector) || |
7505 | (DestTy->castAs<VectorType>()->getVectorKind() == |
7506 | VectorKind::AltiVecBool) || |
7507 | (DestTy->castAs<VectorType>()->getVectorKind() == |
7508 | VectorKind::AltiVecPixel)); |
7509 | |
7510 | return (IsSrcTyAltivec || IsDestTyAltivec); |
7511 | } |
7512 | |
7513 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { |
7514 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
7515 | |
7516 | // Disallow lax conversions between scalars and ExtVectors (these |
7517 | // conversions are allowed for other vector types because common headers |
7518 | // depend on them). Most scalar OP ExtVector cases are handled by the |
7519 | // splat path anyway, which does what we want (convert, not bitcast). |
7520 | // What this rules out for ExtVectors is crazy things like char4*float. |
7521 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; |
7522 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; |
7523 | |
7524 | return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy); |
7525 | } |
7526 | |
7527 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { |
7528 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
7529 | |
7530 | switch (Context.getLangOpts().getLaxVectorConversions()) { |
7531 | case LangOptions::LaxVectorConversionKind::None: |
7532 | return false; |
7533 | |
7534 | case LangOptions::LaxVectorConversionKind::Integer: |
7535 | if (!srcTy->isIntegralOrEnumerationType()) { |
7536 | auto *Vec = srcTy->getAs<VectorType>(); |
7537 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
7538 | return false; |
7539 | } |
7540 | if (!destTy->isIntegralOrEnumerationType()) { |
7541 | auto *Vec = destTy->getAs<VectorType>(); |
7542 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
7543 | return false; |
7544 | } |
7545 | // OK, integer (vector) -> integer (vector) bitcast. |
7546 | break; |
7547 | |
7548 | case LangOptions::LaxVectorConversionKind::All: |
7549 | break; |
7550 | } |
7551 | |
7552 | return areLaxCompatibleVectorTypes(srcTy, destTy); |
7553 | } |
7554 | |
7555 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, |
7556 | CastKind &Kind) { |
7557 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { |
7558 | if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) { |
7559 | return Diag(Loc: R.getBegin(), DiagID: diag::err_invalid_conversion_between_matrixes) |
7560 | << DestTy << SrcTy << R; |
7561 | } |
7562 | } else if (SrcTy->isMatrixType()) { |
7563 | return Diag(Loc: R.getBegin(), |
7564 | DiagID: diag::err_invalid_conversion_between_matrix_and_type) |
7565 | << SrcTy << DestTy << R; |
7566 | } else if (DestTy->isMatrixType()) { |
7567 | return Diag(Loc: R.getBegin(), |
7568 | DiagID: diag::err_invalid_conversion_between_matrix_and_type) |
7569 | << DestTy << SrcTy << R; |
7570 | } |
7571 | |
7572 | Kind = CK_MatrixCast; |
7573 | return false; |
7574 | } |
7575 | |
7576 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
7577 | CastKind &Kind) { |
7578 | assert(VectorTy->isVectorType() && "Not a vector type!" ); |
7579 | |
7580 | if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) { |
7581 | if (!areLaxCompatibleVectorTypes(srcTy: Ty, destTy: VectorTy)) |
7582 | return Diag(Loc: R.getBegin(), |
7583 | DiagID: Ty->isVectorType() ? |
7584 | diag::err_invalid_conversion_between_vectors : |
7585 | diag::err_invalid_conversion_between_vector_and_integer) |
7586 | << VectorTy << Ty << R; |
7587 | } else |
7588 | return Diag(Loc: R.getBegin(), |
7589 | DiagID: diag::err_invalid_conversion_between_vector_and_scalar) |
7590 | << VectorTy << Ty << R; |
7591 | |
7592 | Kind = CK_BitCast; |
7593 | return false; |
7594 | } |
7595 | |
7596 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { |
7597 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); |
7598 | |
7599 | if (DestElemTy == SplattedExpr->getType()) |
7600 | return SplattedExpr; |
7601 | |
7602 | assert(DestElemTy->isFloatingType() || |
7603 | DestElemTy->isIntegralOrEnumerationType()); |
7604 | |
7605 | CastKind CK; |
7606 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { |
7607 | // OpenCL requires that we convert `true` boolean expressions to -1, but |
7608 | // only when splatting vectors. |
7609 | if (DestElemTy->isFloatingType()) { |
7610 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast |
7611 | // in two steps: boolean to signed integral, then to floating. |
7612 | ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy, |
7613 | CK: CK_BooleanToSignedIntegral); |
7614 | SplattedExpr = CastExprRes.get(); |
7615 | CK = CK_IntegralToFloating; |
7616 | } else { |
7617 | CK = CK_BooleanToSignedIntegral; |
7618 | } |
7619 | } else { |
7620 | ExprResult CastExprRes = SplattedExpr; |
7621 | CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy); |
7622 | if (CastExprRes.isInvalid()) |
7623 | return ExprError(); |
7624 | SplattedExpr = CastExprRes.get(); |
7625 | } |
7626 | return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK); |
7627 | } |
7628 | |
7629 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, |
7630 | Expr *CastExpr, CastKind &Kind) { |
7631 | assert(DestTy->isExtVectorType() && "Not an extended vector type!" ); |
7632 | |
7633 | QualType SrcTy = CastExpr->getType(); |
7634 | |
7635 | // If SrcTy is a VectorType, the total size must match to explicitly cast to |
7636 | // an ExtVectorType. |
7637 | // In OpenCL, casts between vectors of different types are not allowed. |
7638 | // (See OpenCL 6.2). |
7639 | if (SrcTy->isVectorType()) { |
7640 | if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) || |
7641 | (getLangOpts().OpenCL && |
7642 | !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy))) { |
7643 | Diag(Loc: R.getBegin(),DiagID: diag::err_invalid_conversion_between_ext_vectors) |
7644 | << DestTy << SrcTy << R; |
7645 | return ExprError(); |
7646 | } |
7647 | Kind = CK_BitCast; |
7648 | return CastExpr; |
7649 | } |
7650 | |
7651 | // All non-pointer scalars can be cast to ExtVector type. The appropriate |
7652 | // conversion will take place first from scalar to elt type, and then |
7653 | // splat from elt type to vector. |
7654 | if (SrcTy->isPointerType()) |
7655 | return Diag(Loc: R.getBegin(), |
7656 | DiagID: diag::err_invalid_conversion_between_vector_and_scalar) |
7657 | << DestTy << SrcTy << R; |
7658 | |
7659 | Kind = CK_VectorSplat; |
7660 | return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr); |
7661 | } |
7662 | |
7663 | ExprResult |
7664 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
7665 | Declarator &D, ParsedType &Ty, |
7666 | SourceLocation RParenLoc, Expr *CastExpr) { |
7667 | assert(!D.isInvalidType() && (CastExpr != nullptr) && |
7668 | "ActOnCastExpr(): missing type or expr" ); |
7669 | |
7670 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType()); |
7671 | if (D.isInvalidType()) |
7672 | return ExprError(); |
7673 | |
7674 | if (getLangOpts().CPlusPlus) { |
7675 | // Check that there are no default arguments (C++ only). |
7676 | CheckExtraCXXDefaultArguments(D); |
7677 | } else { |
7678 | // Make sure any TypoExprs have been dealt with. |
7679 | ExprResult Res = CorrectDelayedTyposInExpr(E: CastExpr); |
7680 | if (!Res.isUsable()) |
7681 | return ExprError(); |
7682 | CastExpr = Res.get(); |
7683 | } |
7684 | |
7685 | checkUnusedDeclAttributes(D); |
7686 | |
7687 | QualType castType = castTInfo->getType(); |
7688 | Ty = CreateParsedType(T: castType, TInfo: castTInfo); |
7689 | |
7690 | bool isVectorLiteral = false; |
7691 | |
7692 | // Check for an altivec or OpenCL literal, |
7693 | // i.e. all the elements are integer constants. |
7694 | ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr); |
7695 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr); |
7696 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) |
7697 | && castType->isVectorType() && (PE || PLE)) { |
7698 | if (PLE && PLE->getNumExprs() == 0) { |
7699 | Diag(Loc: PLE->getExprLoc(), DiagID: diag::err_altivec_empty_initializer); |
7700 | return ExprError(); |
7701 | } |
7702 | if (PE || PLE->getNumExprs() == 1) { |
7703 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0)); |
7704 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) |
7705 | isVectorLiteral = true; |
7706 | } |
7707 | else |
7708 | isVectorLiteral = true; |
7709 | } |
7710 | |
7711 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' |
7712 | // then handle it as such. |
7713 | if (isVectorLiteral) |
7714 | return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo); |
7715 | |
7716 | // If the Expr being casted is a ParenListExpr, handle it specially. |
7717 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a |
7718 | // sequence of BinOp comma operators. |
7719 | if (isa<ParenListExpr>(Val: CastExpr)) { |
7720 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr); |
7721 | if (Result.isInvalid()) return ExprError(); |
7722 | CastExpr = Result.get(); |
7723 | } |
7724 | |
7725 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) |
7726 | Diag(Loc: LParenLoc, DiagID: diag::warn_old_style_cast) << CastExpr->getSourceRange(); |
7727 | |
7728 | ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr); |
7729 | |
7730 | ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr); |
7731 | |
7732 | DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr); |
7733 | |
7734 | return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr); |
7735 | } |
7736 | |
7737 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, |
7738 | SourceLocation RParenLoc, Expr *E, |
7739 | TypeSourceInfo *TInfo) { |
7740 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && |
7741 | "Expected paren or paren list expression" ); |
7742 | |
7743 | Expr **exprs; |
7744 | unsigned numExprs; |
7745 | Expr *subExpr; |
7746 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; |
7747 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) { |
7748 | LiteralLParenLoc = PE->getLParenLoc(); |
7749 | LiteralRParenLoc = PE->getRParenLoc(); |
7750 | exprs = PE->getExprs(); |
7751 | numExprs = PE->getNumExprs(); |
7752 | } else { // isa<ParenExpr> by assertion at function entrance |
7753 | LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen(); |
7754 | LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen(); |
7755 | subExpr = cast<ParenExpr>(Val: E)->getSubExpr(); |
7756 | exprs = &subExpr; |
7757 | numExprs = 1; |
7758 | } |
7759 | |
7760 | QualType Ty = TInfo->getType(); |
7761 | assert(Ty->isVectorType() && "Expected vector type" ); |
7762 | |
7763 | SmallVector<Expr *, 8> initExprs; |
7764 | const VectorType *VTy = Ty->castAs<VectorType>(); |
7765 | unsigned numElems = VTy->getNumElements(); |
7766 | |
7767 | // '(...)' form of vector initialization in AltiVec: the number of |
7768 | // initializers must be one or must match the size of the vector. |
7769 | // If a single value is specified in the initializer then it will be |
7770 | // replicated to all the components of the vector |
7771 | if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty, |
7772 | SrcTy: VTy->getElementType())) |
7773 | return ExprError(); |
7774 | if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) { |
7775 | // The number of initializers must be one or must match the size of the |
7776 | // vector. If a single value is specified in the initializer then it will |
7777 | // be replicated to all the components of the vector |
7778 | if (numExprs == 1) { |
7779 | QualType ElemTy = VTy->getElementType(); |
7780 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
7781 | if (Literal.isInvalid()) |
7782 | return ExprError(); |
7783 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
7784 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
7785 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
7786 | } |
7787 | else if (numExprs < numElems) { |
7788 | Diag(Loc: E->getExprLoc(), |
7789 | DiagID: diag::err_incorrect_number_of_vector_initializers); |
7790 | return ExprError(); |
7791 | } |
7792 | else |
7793 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
7794 | } |
7795 | else { |
7796 | // For OpenCL, when the number of initializers is a single value, |
7797 | // it will be replicated to all components of the vector. |
7798 | if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic && |
7799 | numExprs == 1) { |
7800 | QualType ElemTy = VTy->getElementType(); |
7801 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
7802 | if (Literal.isInvalid()) |
7803 | return ExprError(); |
7804 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
7805 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
7806 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
7807 | } |
7808 | |
7809 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
7810 | } |
7811 | // FIXME: This means that pretty-printing the final AST will produce curly |
7812 | // braces instead of the original commas. |
7813 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, |
7814 | initExprs, LiteralRParenLoc); |
7815 | initE->setType(Ty); |
7816 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: initE); |
7817 | } |
7818 | |
7819 | ExprResult |
7820 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { |
7821 | ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr); |
7822 | if (!E) |
7823 | return OrigExpr; |
7824 | |
7825 | ExprResult Result(E->getExpr(Init: 0)); |
7826 | |
7827 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) |
7828 | Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(), |
7829 | RHSExpr: E->getExpr(Init: i)); |
7830 | |
7831 | if (Result.isInvalid()) return ExprError(); |
7832 | |
7833 | return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get()); |
7834 | } |
7835 | |
7836 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, |
7837 | SourceLocation R, |
7838 | MultiExprArg Val) { |
7839 | return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R); |
7840 | } |
7841 | |
7842 | bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, |
7843 | SourceLocation QuestionLoc) { |
7844 | const Expr *NullExpr = LHSExpr; |
7845 | const Expr *NonPointerExpr = RHSExpr; |
7846 | Expr::NullPointerConstantKind NullKind = |
7847 | NullExpr->isNullPointerConstant(Ctx&: Context, |
7848 | NPC: Expr::NPC_ValueDependentIsNotNull); |
7849 | |
7850 | if (NullKind == Expr::NPCK_NotNull) { |
7851 | NullExpr = RHSExpr; |
7852 | NonPointerExpr = LHSExpr; |
7853 | NullKind = |
7854 | NullExpr->isNullPointerConstant(Ctx&: Context, |
7855 | NPC: Expr::NPC_ValueDependentIsNotNull); |
7856 | } |
7857 | |
7858 | if (NullKind == Expr::NPCK_NotNull) |
7859 | return false; |
7860 | |
7861 | if (NullKind == Expr::NPCK_ZeroExpression) |
7862 | return false; |
7863 | |
7864 | if (NullKind == Expr::NPCK_ZeroLiteral) { |
7865 | // In this case, check to make sure that we got here from a "NULL" |
7866 | // string in the source code. |
7867 | NullExpr = NullExpr->IgnoreParenImpCasts(); |
7868 | SourceLocation loc = NullExpr->getExprLoc(); |
7869 | if (!findMacroSpelling(loc, name: "NULL" )) |
7870 | return false; |
7871 | } |
7872 | |
7873 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); |
7874 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands_null) |
7875 | << NonPointerExpr->getType() << DiagType |
7876 | << NonPointerExpr->getSourceRange(); |
7877 | return true; |
7878 | } |
7879 | |
7880 | /// Return false if the condition expression is valid, true otherwise. |
7881 | static bool checkCondition(Sema &S, const Expr *Cond, |
7882 | SourceLocation QuestionLoc) { |
7883 | QualType CondTy = Cond->getType(); |
7884 | |
7885 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. |
7886 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { |
7887 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat) |
7888 | << CondTy << Cond->getSourceRange(); |
7889 | return true; |
7890 | } |
7891 | |
7892 | // C99 6.5.15p2 |
7893 | if (CondTy->isScalarType()) return false; |
7894 | |
7895 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_scalar) |
7896 | << CondTy << Cond->getSourceRange(); |
7897 | return true; |
7898 | } |
7899 | |
7900 | /// Return false if the NullExpr can be promoted to PointerTy, |
7901 | /// true otherwise. |
7902 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, |
7903 | QualType PointerTy) { |
7904 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || |
7905 | !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context, |
7906 | NPC: Expr::NPC_ValueDependentIsNull)) |
7907 | return true; |
7908 | |
7909 | NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer); |
7910 | return false; |
7911 | } |
7912 | |
7913 | /// Checks compatibility between two pointers and return the resulting |
7914 | /// type. |
7915 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, |
7916 | ExprResult &RHS, |
7917 | SourceLocation Loc) { |
7918 | QualType LHSTy = LHS.get()->getType(); |
7919 | QualType RHSTy = RHS.get()->getType(); |
7920 | |
7921 | if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) { |
7922 | // Two identical pointers types are always compatible. |
7923 | return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
7924 | } |
7925 | |
7926 | QualType lhptee, rhptee; |
7927 | |
7928 | // Get the pointee types. |
7929 | bool IsBlockPointer = false; |
7930 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { |
7931 | lhptee = LHSBTy->getPointeeType(); |
7932 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); |
7933 | IsBlockPointer = true; |
7934 | } else { |
7935 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
7936 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
7937 | } |
7938 | |
7939 | // C99 6.5.15p6: If both operands are pointers to compatible types or to |
7940 | // differently qualified versions of compatible types, the result type is |
7941 | // a pointer to an appropriately qualified version of the composite |
7942 | // type. |
7943 | |
7944 | // Only CVR-qualifiers exist in the standard, and the differently-qualified |
7945 | // clause doesn't make sense for our extensions. E.g. address space 2 should |
7946 | // be incompatible with address space 3: they may live on different devices or |
7947 | // anything. |
7948 | Qualifiers lhQual = lhptee.getQualifiers(); |
7949 | Qualifiers rhQual = rhptee.getQualifiers(); |
7950 | |
7951 | LangAS ResultAddrSpace = LangAS::Default; |
7952 | LangAS LAddrSpace = lhQual.getAddressSpace(); |
7953 | LangAS RAddrSpace = rhQual.getAddressSpace(); |
7954 | |
7955 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address |
7956 | // spaces is disallowed. |
7957 | if (lhQual.isAddressSpaceSupersetOf(other: rhQual)) |
7958 | ResultAddrSpace = LAddrSpace; |
7959 | else if (rhQual.isAddressSpaceSupersetOf(other: lhQual)) |
7960 | ResultAddrSpace = RAddrSpace; |
7961 | else { |
7962 | S.Diag(Loc, DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
7963 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() |
7964 | << RHS.get()->getSourceRange(); |
7965 | return QualType(); |
7966 | } |
7967 | |
7968 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); |
7969 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; |
7970 | lhQual.removeCVRQualifiers(); |
7971 | rhQual.removeCVRQualifiers(); |
7972 | |
7973 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers |
7974 | // (C99 6.7.3) for address spaces. We assume that the check should behave in |
7975 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two |
7976 | // qual types are compatible iff |
7977 | // * corresponded types are compatible |
7978 | // * CVR qualifiers are equal |
7979 | // * address spaces are equal |
7980 | // Thus for conditional operator we merge CVR and address space unqualified |
7981 | // pointees and if there is a composite type we return a pointer to it with |
7982 | // merged qualifiers. |
7983 | LHSCastKind = |
7984 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
7985 | RHSCastKind = |
7986 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
7987 | lhQual.removeAddressSpace(); |
7988 | rhQual.removeAddressSpace(); |
7989 | |
7990 | lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual); |
7991 | rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual); |
7992 | |
7993 | QualType CompositeTy = S.Context.mergeTypes( |
7994 | lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, |
7995 | /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); |
7996 | |
7997 | if (CompositeTy.isNull()) { |
7998 | // In this situation, we assume void* type. No especially good |
7999 | // reason, but this is what gcc does, and we do have to pick |
8000 | // to get a consistent AST. |
8001 | QualType incompatTy; |
8002 | incompatTy = S.Context.getPointerType( |
8003 | T: S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace)); |
8004 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind); |
8005 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind); |
8006 | |
8007 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room |
8008 | // for casts between types with incompatible address space qualifiers. |
8009 | // For the following code the compiler produces casts between global and |
8010 | // local address spaces of the corresponded innermost pointees: |
8011 | // local int *global *a; |
8012 | // global int *global *b; |
8013 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. |
8014 | S.Diag(Loc, DiagID: diag::ext_typecheck_cond_incompatible_pointers) |
8015 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8016 | << RHS.get()->getSourceRange(); |
8017 | |
8018 | return incompatTy; |
8019 | } |
8020 | |
8021 | // The pointer types are compatible. |
8022 | // In case of OpenCL ResultTy should have the address space qualifier |
8023 | // which is a superset of address spaces of both the 2nd and the 3rd |
8024 | // operands of the conditional operator. |
8025 | QualType ResultTy = [&, ResultAddrSpace]() { |
8026 | if (S.getLangOpts().OpenCL) { |
8027 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); |
8028 | CompositeQuals.setAddressSpace(ResultAddrSpace); |
8029 | return S.Context |
8030 | .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals) |
8031 | .withCVRQualifiers(CVR: MergedCVRQual); |
8032 | } |
8033 | return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual); |
8034 | }(); |
8035 | if (IsBlockPointer) |
8036 | ResultTy = S.Context.getBlockPointerType(T: ResultTy); |
8037 | else |
8038 | ResultTy = S.Context.getPointerType(T: ResultTy); |
8039 | |
8040 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind); |
8041 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind); |
8042 | return ResultTy; |
8043 | } |
8044 | |
8045 | /// Return the resulting type when the operands are both block pointers. |
8046 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, |
8047 | ExprResult &LHS, |
8048 | ExprResult &RHS, |
8049 | SourceLocation Loc) { |
8050 | QualType LHSTy = LHS.get()->getType(); |
8051 | QualType RHSTy = RHS.get()->getType(); |
8052 | |
8053 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { |
8054 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { |
8055 | QualType destType = S.Context.getPointerType(T: S.Context.VoidTy); |
8056 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
8057 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
8058 | return destType; |
8059 | } |
8060 | S.Diag(Loc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
8061 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8062 | << RHS.get()->getSourceRange(); |
8063 | return QualType(); |
8064 | } |
8065 | |
8066 | // We have 2 block pointer types. |
8067 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
8068 | } |
8069 | |
8070 | /// Return the resulting type when the operands are both pointers. |
8071 | static QualType |
8072 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, |
8073 | ExprResult &RHS, |
8074 | SourceLocation Loc) { |
8075 | // get the pointer types |
8076 | QualType LHSTy = LHS.get()->getType(); |
8077 | QualType RHSTy = RHS.get()->getType(); |
8078 | |
8079 | // get the "pointed to" types |
8080 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
8081 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
8082 | |
8083 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) |
8084 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { |
8085 | // Figure out necessary qualifiers (C99 6.5.15p6) |
8086 | QualType destPointee |
8087 | = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers()); |
8088 | QualType destType = S.Context.getPointerType(T: destPointee); |
8089 | // Add qualifiers if necessary. |
8090 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp); |
8091 | // Promote to void*. |
8092 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
8093 | return destType; |
8094 | } |
8095 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { |
8096 | QualType destPointee |
8097 | = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers()); |
8098 | QualType destType = S.Context.getPointerType(T: destPointee); |
8099 | // Add qualifiers if necessary. |
8100 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp); |
8101 | // Promote to void*. |
8102 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
8103 | return destType; |
8104 | } |
8105 | |
8106 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
8107 | } |
8108 | |
8109 | /// Return false if the first expression is not an integer and the second |
8110 | /// expression is not a pointer, true otherwise. |
8111 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, |
8112 | Expr* PointerExpr, SourceLocation Loc, |
8113 | bool IsIntFirstExpr) { |
8114 | if (!PointerExpr->getType()->isPointerType() || |
8115 | !Int.get()->getType()->isIntegerType()) |
8116 | return false; |
8117 | |
8118 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; |
8119 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); |
8120 | |
8121 | S.Diag(Loc, DiagID: diag::ext_typecheck_cond_pointer_integer_mismatch) |
8122 | << Expr1->getType() << Expr2->getType() |
8123 | << Expr1->getSourceRange() << Expr2->getSourceRange(); |
8124 | Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(), |
8125 | CK: CK_IntegralToPointer); |
8126 | return true; |
8127 | } |
8128 | |
8129 | /// Simple conversion between integer and floating point types. |
8130 | /// |
8131 | /// Used when handling the OpenCL conditional operator where the |
8132 | /// condition is a vector while the other operands are scalar. |
8133 | /// |
8134 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar |
8135 | /// types are either integer or floating type. Between the two |
8136 | /// operands, the type with the higher rank is defined as the "result |
8137 | /// type". The other operand needs to be promoted to the same type. No |
8138 | /// other type promotion is allowed. We cannot use |
8139 | /// UsualArithmeticConversions() for this purpose, since it always |
8140 | /// promotes promotable types. |
8141 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, |
8142 | ExprResult &RHS, |
8143 | SourceLocation QuestionLoc) { |
8144 | LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
8145 | if (LHS.isInvalid()) |
8146 | return QualType(); |
8147 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
8148 | if (RHS.isInvalid()) |
8149 | return QualType(); |
8150 | |
8151 | // For conversion purposes, we ignore any qualifiers. |
8152 | // For example, "const float" and "float" are equivalent. |
8153 | QualType LHSType = |
8154 | S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType(); |
8155 | QualType RHSType = |
8156 | S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType(); |
8157 | |
8158 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { |
8159 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float) |
8160 | << LHSType << LHS.get()->getSourceRange(); |
8161 | return QualType(); |
8162 | } |
8163 | |
8164 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { |
8165 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_int_float) |
8166 | << RHSType << RHS.get()->getSourceRange(); |
8167 | return QualType(); |
8168 | } |
8169 | |
8170 | // If both types are identical, no conversion is needed. |
8171 | if (LHSType == RHSType) |
8172 | return LHSType; |
8173 | |
8174 | // Now handle "real" floating types (i.e. float, double, long double). |
8175 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
8176 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, |
8177 | /*IsCompAssign = */ false); |
8178 | |
8179 | // Finally, we have two differing integer types. |
8180 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
8181 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); |
8182 | } |
8183 | |
8184 | /// Convert scalar operands to a vector that matches the |
8185 | /// condition in length. |
8186 | /// |
8187 | /// Used when handling the OpenCL conditional operator where the |
8188 | /// condition is a vector while the other operands are scalar. |
8189 | /// |
8190 | /// We first compute the "result type" for the scalar operands |
8191 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted |
8192 | /// into a vector of that type where the length matches the condition |
8193 | /// vector type. s6.11.6 requires that the element types of the result |
8194 | /// and the condition must have the same number of bits. |
8195 | static QualType |
8196 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, |
8197 | QualType CondTy, SourceLocation QuestionLoc) { |
8198 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); |
8199 | if (ResTy.isNull()) return QualType(); |
8200 | |
8201 | const VectorType *CV = CondTy->getAs<VectorType>(); |
8202 | assert(CV); |
8203 | |
8204 | // Determine the vector result type |
8205 | unsigned NumElements = CV->getNumElements(); |
8206 | QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements); |
8207 | |
8208 | // Ensure that all types have the same number of bits |
8209 | if (S.Context.getTypeSize(T: CV->getElementType()) |
8210 | != S.Context.getTypeSize(T: ResTy)) { |
8211 | // Since VectorTy is created internally, it does not pretty print |
8212 | // with an OpenCL name. Instead, we just print a description. |
8213 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); |
8214 | SmallString<64> Str; |
8215 | llvm::raw_svector_ostream OS(Str); |
8216 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)" ; |
8217 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size) |
8218 | << CondTy << OS.str(); |
8219 | return QualType(); |
8220 | } |
8221 | |
8222 | // Convert operands to the vector result type |
8223 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
8224 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
8225 | |
8226 | return VectorTy; |
8227 | } |
8228 | |
8229 | /// Return false if this is a valid OpenCL condition vector |
8230 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, |
8231 | SourceLocation QuestionLoc) { |
8232 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of |
8233 | // integral type. |
8234 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); |
8235 | assert(CondTy); |
8236 | QualType EleTy = CondTy->getElementType(); |
8237 | if (EleTy->isIntegerType()) return false; |
8238 | |
8239 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_expect_nonfloat) |
8240 | << Cond->getType() << Cond->getSourceRange(); |
8241 | return true; |
8242 | } |
8243 | |
8244 | /// Return false if the vector condition type and the vector |
8245 | /// result type are compatible. |
8246 | /// |
8247 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same |
8248 | /// number of elements, and their element types have the same number |
8249 | /// of bits. |
8250 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, |
8251 | SourceLocation QuestionLoc) { |
8252 | const VectorType *CV = CondTy->getAs<VectorType>(); |
8253 | const VectorType *RV = VecResTy->getAs<VectorType>(); |
8254 | assert(CV && RV); |
8255 | |
8256 | if (CV->getNumElements() != RV->getNumElements()) { |
8257 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size) |
8258 | << CondTy << VecResTy; |
8259 | return true; |
8260 | } |
8261 | |
8262 | QualType CVE = CV->getElementType(); |
8263 | QualType RVE = RV->getElementType(); |
8264 | |
8265 | if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE)) { |
8266 | S.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size) |
8267 | << CondTy << VecResTy; |
8268 | return true; |
8269 | } |
8270 | |
8271 | return false; |
8272 | } |
8273 | |
8274 | /// Return the resulting type for the conditional operator in |
8275 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 |
8276 | /// s6.3.i) when the condition is a vector type. |
8277 | static QualType |
8278 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, |
8279 | ExprResult &LHS, ExprResult &RHS, |
8280 | SourceLocation QuestionLoc) { |
8281 | Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get()); |
8282 | if (Cond.isInvalid()) |
8283 | return QualType(); |
8284 | QualType CondTy = Cond.get()->getType(); |
8285 | |
8286 | if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc)) |
8287 | return QualType(); |
8288 | |
8289 | // If either operand is a vector then find the vector type of the |
8290 | // result as specified in OpenCL v1.1 s6.3.i. |
8291 | if (LHS.get()->getType()->isVectorType() || |
8292 | RHS.get()->getType()->isVectorType()) { |
8293 | bool IsBoolVecLang = |
8294 | !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; |
8295 | QualType VecResTy = |
8296 | S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, |
8297 | /*isCompAssign*/ IsCompAssign: false, |
8298 | /*AllowBothBool*/ true, |
8299 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
8300 | /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang, |
8301 | /*ReportInvalid*/ true); |
8302 | if (VecResTy.isNull()) |
8303 | return QualType(); |
8304 | // The result type must match the condition type as specified in |
8305 | // OpenCL v1.1 s6.11.6. |
8306 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) |
8307 | return QualType(); |
8308 | return VecResTy; |
8309 | } |
8310 | |
8311 | // Both operands are scalar. |
8312 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); |
8313 | } |
8314 | |
8315 | /// Return true if the Expr is block type |
8316 | static bool checkBlockType(Sema &S, const Expr *E) { |
8317 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
8318 | QualType Ty = CE->getCallee()->getType(); |
8319 | if (Ty->isBlockPointerType()) { |
8320 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_opencl_ternary_with_block); |
8321 | return true; |
8322 | } |
8323 | } |
8324 | return false; |
8325 | } |
8326 | |
8327 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. |
8328 | /// In that case, LHS = cond. |
8329 | /// C99 6.5.15 |
8330 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
8331 | ExprResult &RHS, ExprValueKind &VK, |
8332 | ExprObjectKind &OK, |
8333 | SourceLocation QuestionLoc) { |
8334 | |
8335 | ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get()); |
8336 | if (!LHSResult.isUsable()) return QualType(); |
8337 | LHS = LHSResult; |
8338 | |
8339 | ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get()); |
8340 | if (!RHSResult.isUsable()) return QualType(); |
8341 | RHS = RHSResult; |
8342 | |
8343 | // C++ is sufficiently different to merit its own checker. |
8344 | if (getLangOpts().CPlusPlus) |
8345 | return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc); |
8346 | |
8347 | VK = VK_PRValue; |
8348 | OK = OK_Ordinary; |
8349 | |
8350 | if (Context.isDependenceAllowed() && |
8351 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || |
8352 | RHS.get()->isTypeDependent())) { |
8353 | assert(!getLangOpts().CPlusPlus); |
8354 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || |
8355 | RHS.get()->containsErrors()) && |
8356 | "should only occur in error-recovery path." ); |
8357 | return Context.DependentTy; |
8358 | } |
8359 | |
8360 | // The OpenCL operator with a vector condition is sufficiently |
8361 | // different to merit its own checker. |
8362 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || |
8363 | Cond.get()->getType()->isExtVectorType()) |
8364 | return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc); |
8365 | |
8366 | // First, check the condition. |
8367 | Cond = UsualUnaryConversions(E: Cond.get()); |
8368 | if (Cond.isInvalid()) |
8369 | return QualType(); |
8370 | if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc)) |
8371 | return QualType(); |
8372 | |
8373 | // Handle vectors. |
8374 | if (LHS.get()->getType()->isVectorType() || |
8375 | RHS.get()->getType()->isVectorType()) |
8376 | return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, |
8377 | /*AllowBothBool*/ true, |
8378 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
8379 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
8380 | /*ReportInvalid*/ true); |
8381 | |
8382 | QualType ResTy = |
8383 | UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, ACK: ACK_Conditional); |
8384 | if (LHS.isInvalid() || RHS.isInvalid()) |
8385 | return QualType(); |
8386 | |
8387 | // WebAssembly tables are not allowed as conditional LHS or RHS. |
8388 | QualType LHSTy = LHS.get()->getType(); |
8389 | QualType RHSTy = RHS.get()->getType(); |
8390 | if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) { |
8391 | Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression) |
8392 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
8393 | return QualType(); |
8394 | } |
8395 | |
8396 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
8397 | // where such conversions currently can't be handled. |
8398 | if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) { |
8399 | Diag(Loc: QuestionLoc, |
8400 | DiagID: diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy |
8401 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
8402 | return QualType(); |
8403 | } |
8404 | |
8405 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary |
8406 | // selection operator (?:). |
8407 | if (getLangOpts().OpenCL && |
8408 | ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) { |
8409 | return QualType(); |
8410 | } |
8411 | |
8412 | // If both operands have arithmetic type, do the usual arithmetic conversions |
8413 | // to find a common type: C99 6.5.15p3,5. |
8414 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { |
8415 | // Disallow invalid arithmetic conversions, such as those between bit- |
8416 | // precise integers types of different sizes, or between a bit-precise |
8417 | // integer and another type. |
8418 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { |
8419 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
8420 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8421 | << RHS.get()->getSourceRange(); |
8422 | return QualType(); |
8423 | } |
8424 | |
8425 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy)); |
8426 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy)); |
8427 | |
8428 | return ResTy; |
8429 | } |
8430 | |
8431 | // If both operands are the same structure or union type, the result is that |
8432 | // type. |
8433 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 |
8434 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) |
8435 | if (LHSRT->getDecl() == RHSRT->getDecl()) |
8436 | // "If both the operands have structure or union type, the result has |
8437 | // that type." This implies that CV qualifiers are dropped. |
8438 | return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(), |
8439 | Y: RHSTy.getUnqualifiedType()); |
8440 | // FIXME: Type of conditional expression must be complete in C mode. |
8441 | } |
8442 | |
8443 | // C99 6.5.15p5: "If both operands have void type, the result has void type." |
8444 | // The following || allows only one side to be void (a GCC-ism). |
8445 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { |
8446 | QualType ResTy; |
8447 | if (LHSTy->isVoidType() && RHSTy->isVoidType()) { |
8448 | ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
8449 | } else if (RHSTy->isVoidType()) { |
8450 | ResTy = RHSTy; |
8451 | Diag(Loc: RHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void) |
8452 | << RHS.get()->getSourceRange(); |
8453 | } else { |
8454 | ResTy = LHSTy; |
8455 | Diag(Loc: LHS.get()->getBeginLoc(), DiagID: diag::ext_typecheck_cond_one_void) |
8456 | << LHS.get()->getSourceRange(); |
8457 | } |
8458 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid); |
8459 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid); |
8460 | return ResTy; |
8461 | } |
8462 | |
8463 | // C23 6.5.15p7: |
8464 | // ... if both the second and third operands have nullptr_t type, the |
8465 | // result also has that type. |
8466 | if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
8467 | return ResTy; |
8468 | |
8469 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has |
8470 | // the type of the other operand." |
8471 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy; |
8472 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy; |
8473 | |
8474 | // All objective-c pointer type analysis is done here. |
8475 | QualType compositeType = |
8476 | ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
8477 | if (LHS.isInvalid() || RHS.isInvalid()) |
8478 | return QualType(); |
8479 | if (!compositeType.isNull()) |
8480 | return compositeType; |
8481 | |
8482 | |
8483 | // Handle block pointer types. |
8484 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) |
8485 | return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS, |
8486 | Loc: QuestionLoc); |
8487 | |
8488 | // Check constraints for C object pointers types (C99 6.5.15p3,6). |
8489 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) |
8490 | return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS, |
8491 | Loc: QuestionLoc); |
8492 | |
8493 | // GCC compatibility: soften pointer/integer mismatch. Note that |
8494 | // null pointers have been filtered out by this point. |
8495 | if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc, |
8496 | /*IsIntFirstExpr=*/true)) |
8497 | return RHSTy; |
8498 | if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc, |
8499 | /*IsIntFirstExpr=*/false)) |
8500 | return LHSTy; |
8501 | |
8502 | // Emit a better diagnostic if one of the expressions is a null pointer |
8503 | // constant and the other is not a pointer type. In this case, the user most |
8504 | // likely forgot to take the address of the other expression. |
8505 | if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
8506 | return QualType(); |
8507 | |
8508 | // Finally, if the LHS and RHS types are canonically the same type, we can |
8509 | // use the common sugared type. |
8510 | if (Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
8511 | return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
8512 | |
8513 | // Otherwise, the operands are not compatible. |
8514 | Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands) |
8515 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8516 | << RHS.get()->getSourceRange(); |
8517 | return QualType(); |
8518 | } |
8519 | |
8520 | /// SuggestParentheses - Emit a note with a fixit hint that wraps |
8521 | /// ParenRange in parentheses. |
8522 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, |
8523 | const PartialDiagnostic &Note, |
8524 | SourceRange ParenRange) { |
8525 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd()); |
8526 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && |
8527 | EndLoc.isValid()) { |
8528 | Self.Diag(Loc, PD: Note) |
8529 | << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(" ) |
8530 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")" ); |
8531 | } else { |
8532 | // We can't display the parentheses, so just show the bare note. |
8533 | Self.Diag(Loc, PD: Note) << ParenRange; |
8534 | } |
8535 | } |
8536 | |
8537 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { |
8538 | return BinaryOperator::isAdditiveOp(Opc) || |
8539 | BinaryOperator::isMultiplicativeOp(Opc) || |
8540 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; |
8541 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and |
8542 | // not any of the logical operators. Bitwise-xor is commonly used as a |
8543 | // logical-xor because there is no logical-xor operator. The logical |
8544 | // operators, including uses of xor, have a high false positive rate for |
8545 | // precedence warnings. |
8546 | } |
8547 | |
8548 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary |
8549 | /// expression, either using a built-in or overloaded operator, |
8550 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side |
8551 | /// expression. |
8552 | static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, |
8553 | const Expr **RHSExprs) { |
8554 | // Don't strip parenthesis: we should not warn if E is in parenthesis. |
8555 | E = E->IgnoreImpCasts(); |
8556 | E = E->IgnoreConversionOperatorSingleStep(); |
8557 | E = E->IgnoreImpCasts(); |
8558 | if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) { |
8559 | E = MTE->getSubExpr(); |
8560 | E = E->IgnoreImpCasts(); |
8561 | } |
8562 | |
8563 | // Built-in binary operator. |
8564 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E); |
8565 | OP && IsArithmeticOp(Opc: OP->getOpcode())) { |
8566 | *Opcode = OP->getOpcode(); |
8567 | *RHSExprs = OP->getRHS(); |
8568 | return true; |
8569 | } |
8570 | |
8571 | // Overloaded operator. |
8572 | if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
8573 | if (Call->getNumArgs() != 2) |
8574 | return false; |
8575 | |
8576 | // Make sure this is really a binary operator that is safe to pass into |
8577 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. |
8578 | OverloadedOperatorKind OO = Call->getOperator(); |
8579 | if (OO < OO_Plus || OO > OO_Arrow || |
8580 | OO == OO_PlusPlus || OO == OO_MinusMinus) |
8581 | return false; |
8582 | |
8583 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); |
8584 | if (IsArithmeticOp(Opc: OpKind)) { |
8585 | *Opcode = OpKind; |
8586 | *RHSExprs = Call->getArg(Arg: 1); |
8587 | return true; |
8588 | } |
8589 | } |
8590 | |
8591 | return false; |
8592 | } |
8593 | |
8594 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type |
8595 | /// or is a logical expression such as (x==y) which has int type, but is |
8596 | /// commonly interpreted as boolean. |
8597 | static bool ExprLooksBoolean(const Expr *E) { |
8598 | E = E->IgnoreParenImpCasts(); |
8599 | |
8600 | if (E->getType()->isBooleanType()) |
8601 | return true; |
8602 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E)) |
8603 | return OP->isComparisonOp() || OP->isLogicalOp(); |
8604 | if (const auto *OP = dyn_cast<UnaryOperator>(Val: E)) |
8605 | return OP->getOpcode() == UO_LNot; |
8606 | if (E->getType()->isPointerType()) |
8607 | return true; |
8608 | // FIXME: What about overloaded operator calls returning "unspecified boolean |
8609 | // type"s (commonly pointer-to-members)? |
8610 | |
8611 | return false; |
8612 | } |
8613 | |
8614 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator |
8615 | /// and binary operator are mixed in a way that suggests the programmer assumed |
8616 | /// the conditional operator has higher precedence, for example: |
8617 | /// "int x = a + someBinaryCondition ? 1 : 2". |
8618 | static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, |
8619 | Expr *Condition, const Expr *LHSExpr, |
8620 | const Expr *RHSExpr) { |
8621 | BinaryOperatorKind CondOpcode; |
8622 | const Expr *CondRHS; |
8623 | |
8624 | if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS)) |
8625 | return; |
8626 | if (!ExprLooksBoolean(E: CondRHS)) |
8627 | return; |
8628 | |
8629 | // The condition is an arithmetic binary expression, with a right- |
8630 | // hand side that looks boolean, so warn. |
8631 | |
8632 | unsigned DiagID = BinaryOperator::isBitwiseOp(Opc: CondOpcode) |
8633 | ? diag::warn_precedence_bitwise_conditional |
8634 | : diag::warn_precedence_conditional; |
8635 | |
8636 | Self.Diag(Loc: OpLoc, DiagID) |
8637 | << Condition->getSourceRange() |
8638 | << BinaryOperator::getOpcodeStr(Op: CondOpcode); |
8639 | |
8640 | SuggestParentheses( |
8641 | Self, Loc: OpLoc, |
8642 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) |
8643 | << BinaryOperator::getOpcodeStr(Op: CondOpcode), |
8644 | ParenRange: SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); |
8645 | |
8646 | SuggestParentheses(Self, Loc: OpLoc, |
8647 | Note: Self.PDiag(DiagID: diag::note_precedence_conditional_first), |
8648 | ParenRange: SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); |
8649 | } |
8650 | |
8651 | /// Compute the nullability of a conditional expression. |
8652 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, |
8653 | QualType LHSTy, QualType RHSTy, |
8654 | ASTContext &Ctx) { |
8655 | if (!ResTy->isAnyPointerType()) |
8656 | return ResTy; |
8657 | |
8658 | auto GetNullability = [](QualType Ty) { |
8659 | std::optional<NullabilityKind> Kind = Ty->getNullability(); |
8660 | if (Kind) { |
8661 | // For our purposes, treat _Nullable_result as _Nullable. |
8662 | if (*Kind == NullabilityKind::NullableResult) |
8663 | return NullabilityKind::Nullable; |
8664 | return *Kind; |
8665 | } |
8666 | return NullabilityKind::Unspecified; |
8667 | }; |
8668 | |
8669 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); |
8670 | NullabilityKind MergedKind; |
8671 | |
8672 | // Compute nullability of a binary conditional expression. |
8673 | if (IsBin) { |
8674 | if (LHSKind == NullabilityKind::NonNull) |
8675 | MergedKind = NullabilityKind::NonNull; |
8676 | else |
8677 | MergedKind = RHSKind; |
8678 | // Compute nullability of a normal conditional expression. |
8679 | } else { |
8680 | if (LHSKind == NullabilityKind::Nullable || |
8681 | RHSKind == NullabilityKind::Nullable) |
8682 | MergedKind = NullabilityKind::Nullable; |
8683 | else if (LHSKind == NullabilityKind::NonNull) |
8684 | MergedKind = RHSKind; |
8685 | else if (RHSKind == NullabilityKind::NonNull) |
8686 | MergedKind = LHSKind; |
8687 | else |
8688 | MergedKind = NullabilityKind::Unspecified; |
8689 | } |
8690 | |
8691 | // Return if ResTy already has the correct nullability. |
8692 | if (GetNullability(ResTy) == MergedKind) |
8693 | return ResTy; |
8694 | |
8695 | // Strip all nullability from ResTy. |
8696 | while (ResTy->getNullability()) |
8697 | ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx); |
8698 | |
8699 | // Create a new AttributedType with the new nullability kind. |
8700 | auto NewAttr = AttributedType::getNullabilityAttrKind(kind: MergedKind); |
8701 | return Ctx.getAttributedType(attrKind: NewAttr, modifiedType: ResTy, equivalentType: ResTy); |
8702 | } |
8703 | |
8704 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, |
8705 | SourceLocation ColonLoc, |
8706 | Expr *CondExpr, Expr *LHSExpr, |
8707 | Expr *RHSExpr) { |
8708 | if (!Context.isDependenceAllowed()) { |
8709 | // C cannot handle TypoExpr nodes in the condition because it |
8710 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
8711 | // been dealt with before checking the operands. |
8712 | ExprResult CondResult = CorrectDelayedTyposInExpr(E: CondExpr); |
8713 | ExprResult LHSResult = CorrectDelayedTyposInExpr(E: LHSExpr); |
8714 | ExprResult RHSResult = CorrectDelayedTyposInExpr(E: RHSExpr); |
8715 | |
8716 | if (!CondResult.isUsable()) |
8717 | return ExprError(); |
8718 | |
8719 | if (LHSExpr) { |
8720 | if (!LHSResult.isUsable()) |
8721 | return ExprError(); |
8722 | } |
8723 | |
8724 | if (!RHSResult.isUsable()) |
8725 | return ExprError(); |
8726 | |
8727 | CondExpr = CondResult.get(); |
8728 | LHSExpr = LHSResult.get(); |
8729 | RHSExpr = RHSResult.get(); |
8730 | } |
8731 | |
8732 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS |
8733 | // was the condition. |
8734 | OpaqueValueExpr *opaqueValue = nullptr; |
8735 | Expr *commonExpr = nullptr; |
8736 | if (!LHSExpr) { |
8737 | commonExpr = CondExpr; |
8738 | // Lower out placeholder types first. This is important so that we don't |
8739 | // try to capture a placeholder. This happens in few cases in C++; such |
8740 | // as Objective-C++'s dictionary subscripting syntax. |
8741 | if (commonExpr->hasPlaceholderType()) { |
8742 | ExprResult result = CheckPlaceholderExpr(E: commonExpr); |
8743 | if (!result.isUsable()) return ExprError(); |
8744 | commonExpr = result.get(); |
8745 | } |
8746 | // We usually want to apply unary conversions *before* saving, except |
8747 | // in the special case of a C++ l-value conditional. |
8748 | if (!(getLangOpts().CPlusPlus |
8749 | && !commonExpr->isTypeDependent() |
8750 | && commonExpr->getValueKind() == RHSExpr->getValueKind() |
8751 | && commonExpr->isGLValue() |
8752 | && commonExpr->isOrdinaryOrBitFieldObject() |
8753 | && RHSExpr->isOrdinaryOrBitFieldObject() |
8754 | && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) { |
8755 | ExprResult commonRes = UsualUnaryConversions(E: commonExpr); |
8756 | if (commonRes.isInvalid()) |
8757 | return ExprError(); |
8758 | commonExpr = commonRes.get(); |
8759 | } |
8760 | |
8761 | // If the common expression is a class or array prvalue, materialize it |
8762 | // so that we can safely refer to it multiple times. |
8763 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || |
8764 | commonExpr->getType()->isArrayType())) { |
8765 | ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr); |
8766 | if (MatExpr.isInvalid()) |
8767 | return ExprError(); |
8768 | commonExpr = MatExpr.get(); |
8769 | } |
8770 | |
8771 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), |
8772 | commonExpr->getType(), |
8773 | commonExpr->getValueKind(), |
8774 | commonExpr->getObjectKind(), |
8775 | commonExpr); |
8776 | LHSExpr = CondExpr = opaqueValue; |
8777 | } |
8778 | |
8779 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); |
8780 | ExprValueKind VK = VK_PRValue; |
8781 | ExprObjectKind OK = OK_Ordinary; |
8782 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; |
8783 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, |
8784 | VK, OK, QuestionLoc); |
8785 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || |
8786 | RHS.isInvalid()) |
8787 | return ExprError(); |
8788 | |
8789 | DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(), |
8790 | RHSExpr: RHS.get()); |
8791 | |
8792 | CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc); |
8793 | |
8794 | result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy, |
8795 | Ctx&: Context); |
8796 | |
8797 | if (!commonExpr) |
8798 | return new (Context) |
8799 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, |
8800 | RHS.get(), result, VK, OK); |
8801 | |
8802 | return new (Context) BinaryConditionalOperator( |
8803 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, |
8804 | ColonLoc, result, VK, OK); |
8805 | } |
8806 | |
8807 | bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) { |
8808 | unsigned FromAttributes = 0, ToAttributes = 0; |
8809 | if (const auto *FromFn = |
8810 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType))) |
8811 | FromAttributes = |
8812 | FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
8813 | if (const auto *ToFn = |
8814 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType))) |
8815 | ToAttributes = |
8816 | ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
8817 | |
8818 | return FromAttributes != ToAttributes; |
8819 | } |
8820 | |
8821 | // Check if we have a conversion between incompatible cmse function pointer |
8822 | // types, that is, a conversion between a function pointer with the |
8823 | // cmse_nonsecure_call attribute and one without. |
8824 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, |
8825 | QualType ToType) { |
8826 | if (const auto *ToFn = |
8827 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: ToType))) { |
8828 | if (const auto *FromFn = |
8829 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: FromType))) { |
8830 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
8831 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
8832 | |
8833 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); |
8834 | } |
8835 | } |
8836 | return false; |
8837 | } |
8838 | |
8839 | // checkPointerTypesForAssignment - This is a very tricky routine (despite |
8840 | // being closely modeled after the C99 spec:-). The odd characteristic of this |
8841 | // routine is it effectively iqnores the qualifiers on the top level pointee. |
8842 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. |
8843 | // FIXME: add a couple examples in this comment. |
8844 | static Sema::AssignConvertType |
8845 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, |
8846 | SourceLocation Loc) { |
8847 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
8848 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
8849 | |
8850 | // get the "pointed to" type (ignoring qualifiers at the top level) |
8851 | const Type *lhptee, *rhptee; |
8852 | Qualifiers lhq, rhq; |
8853 | std::tie(args&: lhptee, args&: lhq) = |
8854 | cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair(); |
8855 | std::tie(args&: rhptee, args&: rhq) = |
8856 | cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair(); |
8857 | |
8858 | Sema::AssignConvertType ConvTy = Sema::Compatible; |
8859 | |
8860 | // C99 6.5.16.1p1: This following citation is common to constraints |
8861 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the |
8862 | // qualifiers of the type *pointed to* by the right; |
8863 | |
8864 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. |
8865 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && |
8866 | lhq.compatiblyIncludesObjCLifetime(other: rhq)) { |
8867 | // Ignore lifetime for further calculation. |
8868 | lhq.removeObjCLifetime(); |
8869 | rhq.removeObjCLifetime(); |
8870 | } |
8871 | |
8872 | if (!lhq.compatiblyIncludes(other: rhq)) { |
8873 | // Treat address-space mismatches as fatal. |
8874 | if (!lhq.isAddressSpaceSupersetOf(other: rhq)) |
8875 | return Sema::IncompatiblePointerDiscardsQualifiers; |
8876 | |
8877 | // It's okay to add or remove GC or lifetime qualifiers when converting to |
8878 | // and from void*. |
8879 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() |
8880 | .compatiblyIncludes( |
8881 | other: rhq.withoutObjCGCAttr().withoutObjCLifetime()) |
8882 | && (lhptee->isVoidType() || rhptee->isVoidType())) |
8883 | ; // keep old |
8884 | |
8885 | // Treat lifetime mismatches as fatal. |
8886 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) |
8887 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; |
8888 | |
8889 | // For GCC/MS compatibility, other qualifier mismatches are treated |
8890 | // as still compatible in C. |
8891 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; |
8892 | } |
8893 | |
8894 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or |
8895 | // incomplete type and the other is a pointer to a qualified or unqualified |
8896 | // version of void... |
8897 | if (lhptee->isVoidType()) { |
8898 | if (rhptee->isIncompleteOrObjectType()) |
8899 | return ConvTy; |
8900 | |
8901 | // As an extension, we allow cast to/from void* to function pointer. |
8902 | assert(rhptee->isFunctionType()); |
8903 | return Sema::FunctionVoidPointer; |
8904 | } |
8905 | |
8906 | if (rhptee->isVoidType()) { |
8907 | if (lhptee->isIncompleteOrObjectType()) |
8908 | return ConvTy; |
8909 | |
8910 | // As an extension, we allow cast to/from void* to function pointer. |
8911 | assert(lhptee->isFunctionType()); |
8912 | return Sema::FunctionVoidPointer; |
8913 | } |
8914 | |
8915 | if (!S.Diags.isIgnored( |
8916 | DiagID: diag::warn_typecheck_convert_incompatible_function_pointer_strict, |
8917 | Loc) && |
8918 | RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && |
8919 | !S.IsFunctionConversion(FromType: RHSType, ToType: LHSType, ResultTy&: RHSType)) |
8920 | return Sema::IncompatibleFunctionPointerStrict; |
8921 | |
8922 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or |
8923 | // unqualified versions of compatible types, ... |
8924 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); |
8925 | if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) { |
8926 | // Check if the pointee types are compatible ignoring the sign. |
8927 | // We explicitly check for char so that we catch "char" vs |
8928 | // "unsigned char" on systems where "char" is unsigned. |
8929 | if (lhptee->isCharType()) |
8930 | ltrans = S.Context.UnsignedCharTy; |
8931 | else if (lhptee->hasSignedIntegerRepresentation()) |
8932 | ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans); |
8933 | |
8934 | if (rhptee->isCharType()) |
8935 | rtrans = S.Context.UnsignedCharTy; |
8936 | else if (rhptee->hasSignedIntegerRepresentation()) |
8937 | rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans); |
8938 | |
8939 | if (ltrans == rtrans) { |
8940 | // Types are compatible ignoring the sign. Qualifier incompatibility |
8941 | // takes priority over sign incompatibility because the sign |
8942 | // warning can be disabled. |
8943 | if (ConvTy != Sema::Compatible) |
8944 | return ConvTy; |
8945 | |
8946 | return Sema::IncompatiblePointerSign; |
8947 | } |
8948 | |
8949 | // If we are a multi-level pointer, it's possible that our issue is simply |
8950 | // one of qualification - e.g. char ** -> const char ** is not allowed. If |
8951 | // the eventual target type is the same and the pointers have the same |
8952 | // level of indirection, this must be the issue. |
8953 | if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) { |
8954 | do { |
8955 | std::tie(args&: lhptee, args&: lhq) = |
8956 | cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair(); |
8957 | std::tie(args&: rhptee, args&: rhq) = |
8958 | cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair(); |
8959 | |
8960 | // Inconsistent address spaces at this point is invalid, even if the |
8961 | // address spaces would be compatible. |
8962 | // FIXME: This doesn't catch address space mismatches for pointers of |
8963 | // different nesting levels, like: |
8964 | // __local int *** a; |
8965 | // int ** b = a; |
8966 | // It's not clear how to actually determine when such pointers are |
8967 | // invalidly incompatible. |
8968 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) |
8969 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; |
8970 | |
8971 | } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)); |
8972 | |
8973 | if (lhptee == rhptee) |
8974 | return Sema::IncompatibleNestedPointerQualifiers; |
8975 | } |
8976 | |
8977 | // General pointer incompatibility takes priority over qualifiers. |
8978 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) |
8979 | return Sema::IncompatibleFunctionPointer; |
8980 | return Sema::IncompatiblePointer; |
8981 | } |
8982 | if (!S.getLangOpts().CPlusPlus && |
8983 | S.IsFunctionConversion(FromType: ltrans, ToType: rtrans, ResultTy&: ltrans)) |
8984 | return Sema::IncompatibleFunctionPointer; |
8985 | if (IsInvalidCmseNSCallConversion(S, FromType: ltrans, ToType: rtrans)) |
8986 | return Sema::IncompatibleFunctionPointer; |
8987 | if (S.IsInvalidSMECallConversion(FromType: rtrans, ToType: ltrans)) |
8988 | return Sema::IncompatibleFunctionPointer; |
8989 | return ConvTy; |
8990 | } |
8991 | |
8992 | /// checkBlockPointerTypesForAssignment - This routine determines whether two |
8993 | /// block pointer types are compatible or whether a block and normal pointer |
8994 | /// are compatible. It is more restrict than comparing two function pointer |
8995 | // types. |
8996 | static Sema::AssignConvertType |
8997 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, |
8998 | QualType RHSType) { |
8999 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
9000 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
9001 | |
9002 | QualType lhptee, rhptee; |
9003 | |
9004 | // get the "pointed to" type (ignoring qualifiers at the top level) |
9005 | lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType(); |
9006 | rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType(); |
9007 | |
9008 | // In C++, the types have to match exactly. |
9009 | if (S.getLangOpts().CPlusPlus) |
9010 | return Sema::IncompatibleBlockPointer; |
9011 | |
9012 | Sema::AssignConvertType ConvTy = Sema::Compatible; |
9013 | |
9014 | // For blocks we enforce that qualifiers are identical. |
9015 | Qualifiers LQuals = lhptee.getLocalQualifiers(); |
9016 | Qualifiers RQuals = rhptee.getLocalQualifiers(); |
9017 | if (S.getLangOpts().OpenCL) { |
9018 | LQuals.removeAddressSpace(); |
9019 | RQuals.removeAddressSpace(); |
9020 | } |
9021 | if (LQuals != RQuals) |
9022 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; |
9023 | |
9024 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block |
9025 | // assignment. |
9026 | // The current behavior is similar to C++ lambdas. A block might be |
9027 | // assigned to a variable iff its return type and parameters are compatible |
9028 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of |
9029 | // an assignment. Presumably it should behave in way that a function pointer |
9030 | // assignment does in C, so for each parameter and return type: |
9031 | // * CVR and address space of LHS should be a superset of CVR and address |
9032 | // space of RHS. |
9033 | // * unqualified types should be compatible. |
9034 | if (S.getLangOpts().OpenCL) { |
9035 | if (!S.Context.typesAreBlockPointerCompatible( |
9036 | S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals), |
9037 | S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals))) |
9038 | return Sema::IncompatibleBlockPointer; |
9039 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) |
9040 | return Sema::IncompatibleBlockPointer; |
9041 | |
9042 | return ConvTy; |
9043 | } |
9044 | |
9045 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types |
9046 | /// for assignment compatibility. |
9047 | static Sema::AssignConvertType |
9048 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, |
9049 | QualType RHSType) { |
9050 | assert(LHSType.isCanonical() && "LHS was not canonicalized!" ); |
9051 | assert(RHSType.isCanonical() && "RHS was not canonicalized!" ); |
9052 | |
9053 | if (LHSType->isObjCBuiltinType()) { |
9054 | // Class is not compatible with ObjC object pointers. |
9055 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && |
9056 | !RHSType->isObjCQualifiedClassType()) |
9057 | return Sema::IncompatiblePointer; |
9058 | return Sema::Compatible; |
9059 | } |
9060 | if (RHSType->isObjCBuiltinType()) { |
9061 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && |
9062 | !LHSType->isObjCQualifiedClassType()) |
9063 | return Sema::IncompatiblePointer; |
9064 | return Sema::Compatible; |
9065 | } |
9066 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
9067 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
9068 | |
9069 | if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee) && |
9070 | // make an exception for id<P> |
9071 | !LHSType->isObjCQualifiedIdType()) |
9072 | return Sema::CompatiblePointerDiscardsQualifiers; |
9073 | |
9074 | if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType)) |
9075 | return Sema::Compatible; |
9076 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) |
9077 | return Sema::IncompatibleObjCQualifiedId; |
9078 | return Sema::IncompatiblePointer; |
9079 | } |
9080 | |
9081 | Sema::AssignConvertType |
9082 | Sema::CheckAssignmentConstraints(SourceLocation Loc, |
9083 | QualType LHSType, QualType RHSType) { |
9084 | // Fake up an opaque expression. We don't actually care about what |
9085 | // cast operations are required, so if CheckAssignmentConstraints |
9086 | // adds casts to this they'll be wasted, but fortunately that doesn't |
9087 | // usually happen on valid code. |
9088 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); |
9089 | ExprResult RHSPtr = &RHSExpr; |
9090 | CastKind K; |
9091 | |
9092 | return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false); |
9093 | } |
9094 | |
9095 | /// This helper function returns true if QT is a vector type that has element |
9096 | /// type ElementType. |
9097 | static bool isVector(QualType QT, QualType ElementType) { |
9098 | if (const VectorType *VT = QT->getAs<VectorType>()) |
9099 | return VT->getElementType().getCanonicalType() == ElementType; |
9100 | return false; |
9101 | } |
9102 | |
9103 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently |
9104 | /// has code to accommodate several GCC extensions when type checking |
9105 | /// pointers. Here are some objectionable examples that GCC considers warnings: |
9106 | /// |
9107 | /// int a, *pint; |
9108 | /// short *pshort; |
9109 | /// struct foo *pfoo; |
9110 | /// |
9111 | /// pint = pshort; // warning: assignment from incompatible pointer type |
9112 | /// a = pint; // warning: assignment makes integer from pointer without a cast |
9113 | /// pint = a; // warning: assignment makes pointer from integer without a cast |
9114 | /// pint = pfoo; // warning: assignment from incompatible pointer type |
9115 | /// |
9116 | /// As a result, the code for dealing with pointers is more complex than the |
9117 | /// C99 spec dictates. |
9118 | /// |
9119 | /// Sets 'Kind' for any result kind except Incompatible. |
9120 | Sema::AssignConvertType |
9121 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, |
9122 | CastKind &Kind, bool ConvertRHS) { |
9123 | QualType RHSType = RHS.get()->getType(); |
9124 | QualType OrigLHSType = LHSType; |
9125 | |
9126 | // Get canonical types. We're not formatting these types, just comparing |
9127 | // them. |
9128 | LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType(); |
9129 | RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType(); |
9130 | |
9131 | // Common case: no conversion required. |
9132 | if (LHSType == RHSType) { |
9133 | Kind = CK_NoOp; |
9134 | return Compatible; |
9135 | } |
9136 | |
9137 | // If the LHS has an __auto_type, there are no additional type constraints |
9138 | // to be worried about. |
9139 | if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) { |
9140 | if (AT->isGNUAutoType()) { |
9141 | Kind = CK_NoOp; |
9142 | return Compatible; |
9143 | } |
9144 | } |
9145 | |
9146 | // If we have an atomic type, try a non-atomic assignment, then just add an |
9147 | // atomic qualification step. |
9148 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) { |
9149 | Sema::AssignConvertType result = |
9150 | CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind); |
9151 | if (result != Compatible) |
9152 | return result; |
9153 | if (Kind != CK_NoOp && ConvertRHS) |
9154 | RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind); |
9155 | Kind = CK_NonAtomicToAtomic; |
9156 | return Compatible; |
9157 | } |
9158 | |
9159 | // If the left-hand side is a reference type, then we are in a |
9160 | // (rare!) case where we've allowed the use of references in C, |
9161 | // e.g., as a parameter type in a built-in function. In this case, |
9162 | // just make sure that the type referenced is compatible with the |
9163 | // right-hand side type. The caller is responsible for adjusting |
9164 | // LHSType so that the resulting expression does not have reference |
9165 | // type. |
9166 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { |
9167 | if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) { |
9168 | Kind = CK_LValueBitCast; |
9169 | return Compatible; |
9170 | } |
9171 | return Incompatible; |
9172 | } |
9173 | |
9174 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type |
9175 | // to the same ExtVector type. |
9176 | if (LHSType->isExtVectorType()) { |
9177 | if (RHSType->isExtVectorType()) |
9178 | return Incompatible; |
9179 | if (RHSType->isArithmeticType()) { |
9180 | // CK_VectorSplat does T -> vector T, so first cast to the element type. |
9181 | if (ConvertRHS) |
9182 | RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get()); |
9183 | Kind = CK_VectorSplat; |
9184 | return Compatible; |
9185 | } |
9186 | } |
9187 | |
9188 | // Conversions to or from vector type. |
9189 | if (LHSType->isVectorType() || RHSType->isVectorType()) { |
9190 | if (LHSType->isVectorType() && RHSType->isVectorType()) { |
9191 | // Allow assignments of an AltiVec vector type to an equivalent GCC |
9192 | // vector type and vice versa |
9193 | if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
9194 | Kind = CK_BitCast; |
9195 | return Compatible; |
9196 | } |
9197 | |
9198 | // If we are allowing lax vector conversions, and LHS and RHS are both |
9199 | // vectors, the total size only needs to be the same. This is a bitcast; |
9200 | // no bits are changed but the result type is different. |
9201 | if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
9202 | // The default for lax vector conversions with Altivec vectors will |
9203 | // change, so if we are converting between vector types where |
9204 | // at least one is an Altivec vector, emit a warning. |
9205 | if (Context.getTargetInfo().getTriple().isPPC() && |
9206 | anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) && |
9207 | !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType)) |
9208 | Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all) |
9209 | << RHSType << LHSType; |
9210 | Kind = CK_BitCast; |
9211 | return IncompatibleVectors; |
9212 | } |
9213 | } |
9214 | |
9215 | // When the RHS comes from another lax conversion (e.g. binops between |
9216 | // scalars and vectors) the result is canonicalized as a vector. When the |
9217 | // LHS is also a vector, the lax is allowed by the condition above. Handle |
9218 | // the case where LHS is a scalar. |
9219 | if (LHSType->isScalarType()) { |
9220 | const VectorType *VecType = RHSType->getAs<VectorType>(); |
9221 | if (VecType && VecType->getNumElements() == 1 && |
9222 | isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
9223 | if (Context.getTargetInfo().getTriple().isPPC() && |
9224 | (VecType->getVectorKind() == VectorKind::AltiVecVector || |
9225 | VecType->getVectorKind() == VectorKind::AltiVecBool || |
9226 | VecType->getVectorKind() == VectorKind::AltiVecPixel)) |
9227 | Diag(Loc: RHS.get()->getExprLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all) |
9228 | << RHSType << LHSType; |
9229 | ExprResult *VecExpr = &RHS; |
9230 | *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast); |
9231 | Kind = CK_BitCast; |
9232 | return Compatible; |
9233 | } |
9234 | } |
9235 | |
9236 | // Allow assignments between fixed-length and sizeless SVE vectors. |
9237 | if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) || |
9238 | (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType())) |
9239 | if (Context.areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) || |
9240 | Context.areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) { |
9241 | Kind = CK_BitCast; |
9242 | return Compatible; |
9243 | } |
9244 | |
9245 | // Allow assignments between fixed-length and sizeless RVV vectors. |
9246 | if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) || |
9247 | (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) { |
9248 | if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) || |
9249 | Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) { |
9250 | Kind = CK_BitCast; |
9251 | return Compatible; |
9252 | } |
9253 | } |
9254 | |
9255 | return Incompatible; |
9256 | } |
9257 | |
9258 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
9259 | // where such conversions currently can't be handled. |
9260 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
9261 | return Incompatible; |
9262 | |
9263 | // Disallow assigning a _Complex to a real type in C++ mode since it simply |
9264 | // discards the imaginary part. |
9265 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && |
9266 | !LHSType->getAs<ComplexType>()) |
9267 | return Incompatible; |
9268 | |
9269 | // Arithmetic conversions. |
9270 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && |
9271 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { |
9272 | if (ConvertRHS) |
9273 | Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType); |
9274 | return Compatible; |
9275 | } |
9276 | |
9277 | // Conversions to normal pointers. |
9278 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) { |
9279 | // U* -> T* |
9280 | if (isa<PointerType>(Val: RHSType)) { |
9281 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
9282 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); |
9283 | if (AddrSpaceL != AddrSpaceR) |
9284 | Kind = CK_AddressSpaceConversion; |
9285 | else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType)) |
9286 | Kind = CK_NoOp; |
9287 | else |
9288 | Kind = CK_BitCast; |
9289 | return checkPointerTypesForAssignment(S&: *this, LHSType, RHSType, |
9290 | Loc: RHS.get()->getBeginLoc()); |
9291 | } |
9292 | |
9293 | // int -> T* |
9294 | if (RHSType->isIntegerType()) { |
9295 | Kind = CK_IntegralToPointer; // FIXME: null? |
9296 | return IntToPointer; |
9297 | } |
9298 | |
9299 | // C pointers are not compatible with ObjC object pointers, |
9300 | // with two exceptions: |
9301 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
9302 | // - conversions to void* |
9303 | if (LHSPointer->getPointeeType()->isVoidType()) { |
9304 | Kind = CK_BitCast; |
9305 | return Compatible; |
9306 | } |
9307 | |
9308 | // - conversions from 'Class' to the redefinition type |
9309 | if (RHSType->isObjCClassType() && |
9310 | Context.hasSameType(T1: LHSType, |
9311 | T2: Context.getObjCClassRedefinitionType())) { |
9312 | Kind = CK_BitCast; |
9313 | return Compatible; |
9314 | } |
9315 | |
9316 | Kind = CK_BitCast; |
9317 | return IncompatiblePointer; |
9318 | } |
9319 | |
9320 | // U^ -> void* |
9321 | if (RHSType->getAs<BlockPointerType>()) { |
9322 | if (LHSPointer->getPointeeType()->isVoidType()) { |
9323 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
9324 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
9325 | ->getPointeeType() |
9326 | .getAddressSpace(); |
9327 | Kind = |
9328 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
9329 | return Compatible; |
9330 | } |
9331 | } |
9332 | |
9333 | return Incompatible; |
9334 | } |
9335 | |
9336 | // Conversions to block pointers. |
9337 | if (isa<BlockPointerType>(Val: LHSType)) { |
9338 | // U^ -> T^ |
9339 | if (RHSType->isBlockPointerType()) { |
9340 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() |
9341 | ->getPointeeType() |
9342 | .getAddressSpace(); |
9343 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
9344 | ->getPointeeType() |
9345 | .getAddressSpace(); |
9346 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
9347 | return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
9348 | } |
9349 | |
9350 | // int or null -> T^ |
9351 | if (RHSType->isIntegerType()) { |
9352 | Kind = CK_IntegralToPointer; // FIXME: null |
9353 | return IntToBlockPointer; |
9354 | } |
9355 | |
9356 | // id -> T^ |
9357 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { |
9358 | Kind = CK_AnyPointerToBlockPointerCast; |
9359 | return Compatible; |
9360 | } |
9361 | |
9362 | // void* -> T^ |
9363 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) |
9364 | if (RHSPT->getPointeeType()->isVoidType()) { |
9365 | Kind = CK_AnyPointerToBlockPointerCast; |
9366 | return Compatible; |
9367 | } |
9368 | |
9369 | return Incompatible; |
9370 | } |
9371 | |
9372 | // Conversions to Objective-C pointers. |
9373 | if (isa<ObjCObjectPointerType>(Val: LHSType)) { |
9374 | // A* -> B* |
9375 | if (RHSType->isObjCObjectPointerType()) { |
9376 | Kind = CK_BitCast; |
9377 | Sema::AssignConvertType result = |
9378 | checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
9379 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
9380 | result == Compatible && |
9381 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType)) |
9382 | result = IncompatibleObjCWeakRef; |
9383 | return result; |
9384 | } |
9385 | |
9386 | // int or null -> A* |
9387 | if (RHSType->isIntegerType()) { |
9388 | Kind = CK_IntegralToPointer; // FIXME: null |
9389 | return IntToPointer; |
9390 | } |
9391 | |
9392 | // In general, C pointers are not compatible with ObjC object pointers, |
9393 | // with two exceptions: |
9394 | if (isa<PointerType>(Val: RHSType)) { |
9395 | Kind = CK_CPointerToObjCPointerCast; |
9396 | |
9397 | // - conversions from 'void*' |
9398 | if (RHSType->isVoidPointerType()) { |
9399 | return Compatible; |
9400 | } |
9401 | |
9402 | // - conversions to 'Class' from its redefinition type |
9403 | if (LHSType->isObjCClassType() && |
9404 | Context.hasSameType(T1: RHSType, |
9405 | T2: Context.getObjCClassRedefinitionType())) { |
9406 | return Compatible; |
9407 | } |
9408 | |
9409 | return IncompatiblePointer; |
9410 | } |
9411 | |
9412 | // Only under strict condition T^ is compatible with an Objective-C pointer. |
9413 | if (RHSType->isBlockPointerType() && |
9414 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
9415 | if (ConvertRHS) |
9416 | maybeExtendBlockObject(E&: RHS); |
9417 | Kind = CK_BlockPointerToObjCPointerCast; |
9418 | return Compatible; |
9419 | } |
9420 | |
9421 | return Incompatible; |
9422 | } |
9423 | |
9424 | // Conversion to nullptr_t (C23 only) |
9425 | if (getLangOpts().C23 && LHSType->isNullPtrType() && |
9426 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
9427 | NPC: Expr::NPC_ValueDependentIsNull)) { |
9428 | // null -> nullptr_t |
9429 | Kind = CK_NullToPointer; |
9430 | return Compatible; |
9431 | } |
9432 | |
9433 | // Conversions from pointers that are not covered by the above. |
9434 | if (isa<PointerType>(Val: RHSType)) { |
9435 | // T* -> _Bool |
9436 | if (LHSType == Context.BoolTy) { |
9437 | Kind = CK_PointerToBoolean; |
9438 | return Compatible; |
9439 | } |
9440 | |
9441 | // T* -> int |
9442 | if (LHSType->isIntegerType()) { |
9443 | Kind = CK_PointerToIntegral; |
9444 | return PointerToInt; |
9445 | } |
9446 | |
9447 | return Incompatible; |
9448 | } |
9449 | |
9450 | // Conversions from Objective-C pointers that are not covered by the above. |
9451 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
9452 | // T* -> _Bool |
9453 | if (LHSType == Context.BoolTy) { |
9454 | Kind = CK_PointerToBoolean; |
9455 | return Compatible; |
9456 | } |
9457 | |
9458 | // T* -> int |
9459 | if (LHSType->isIntegerType()) { |
9460 | Kind = CK_PointerToIntegral; |
9461 | return PointerToInt; |
9462 | } |
9463 | |
9464 | return Incompatible; |
9465 | } |
9466 | |
9467 | // struct A -> struct B |
9468 | if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) { |
9469 | if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
9470 | Kind = CK_NoOp; |
9471 | return Compatible; |
9472 | } |
9473 | } |
9474 | |
9475 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { |
9476 | Kind = CK_IntToOCLSampler; |
9477 | return Compatible; |
9478 | } |
9479 | |
9480 | return Incompatible; |
9481 | } |
9482 | |
9483 | /// Constructs a transparent union from an expression that is |
9484 | /// used to initialize the transparent union. |
9485 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, |
9486 | ExprResult &EResult, QualType UnionType, |
9487 | FieldDecl *Field) { |
9488 | // Build an initializer list that designates the appropriate member |
9489 | // of the transparent union. |
9490 | Expr *E = EResult.get(); |
9491 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), |
9492 | E, SourceLocation()); |
9493 | Initializer->setType(UnionType); |
9494 | Initializer->setInitializedFieldInUnion(Field); |
9495 | |
9496 | // Build a compound literal constructing a value of the transparent |
9497 | // union type from this initializer list. |
9498 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType); |
9499 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, |
9500 | VK_PRValue, Initializer, false); |
9501 | } |
9502 | |
9503 | Sema::AssignConvertType |
9504 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, |
9505 | ExprResult &RHS) { |
9506 | QualType RHSType = RHS.get()->getType(); |
9507 | |
9508 | // If the ArgType is a Union type, we want to handle a potential |
9509 | // transparent_union GCC extension. |
9510 | const RecordType *UT = ArgType->getAsUnionType(); |
9511 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
9512 | return Incompatible; |
9513 | |
9514 | // The field to initialize within the transparent union. |
9515 | RecordDecl *UD = UT->getDecl(); |
9516 | FieldDecl *InitField = nullptr; |
9517 | // It's compatible if the expression matches any of the fields. |
9518 | for (auto *it : UD->fields()) { |
9519 | if (it->getType()->isPointerType()) { |
9520 | // If the transparent union contains a pointer type, we allow: |
9521 | // 1) void pointer |
9522 | // 2) null pointer constant |
9523 | if (RHSType->isPointerType()) |
9524 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
9525 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: CK_BitCast); |
9526 | InitField = it; |
9527 | break; |
9528 | } |
9529 | |
9530 | if (RHS.get()->isNullPointerConstant(Ctx&: Context, |
9531 | NPC: Expr::NPC_ValueDependentIsNull)) { |
9532 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), |
9533 | CK: CK_NullToPointer); |
9534 | InitField = it; |
9535 | break; |
9536 | } |
9537 | } |
9538 | |
9539 | CastKind Kind; |
9540 | if (CheckAssignmentConstraints(LHSType: it->getType(), RHS, Kind) |
9541 | == Compatible) { |
9542 | RHS = ImpCastExprToType(E: RHS.get(), Type: it->getType(), CK: Kind); |
9543 | InitField = it; |
9544 | break; |
9545 | } |
9546 | } |
9547 | |
9548 | if (!InitField) |
9549 | return Incompatible; |
9550 | |
9551 | ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField); |
9552 | return Compatible; |
9553 | } |
9554 | |
9555 | Sema::AssignConvertType |
9556 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, |
9557 | bool Diagnose, |
9558 | bool DiagnoseCFAudited, |
9559 | bool ConvertRHS) { |
9560 | // We need to be able to tell the caller whether we diagnosed a problem, if |
9561 | // they ask us to issue diagnostics. |
9562 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ); |
9563 | |
9564 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, |
9565 | // we can't avoid *all* modifications at the moment, so we need some somewhere |
9566 | // to put the updated value. |
9567 | ExprResult LocalRHS = CallerRHS; |
9568 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; |
9569 | |
9570 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { |
9571 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { |
9572 | if (RHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) && |
9573 | !LHSPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) { |
9574 | Diag(Loc: RHS.get()->getExprLoc(), |
9575 | DiagID: diag::warn_noderef_to_dereferenceable_pointer) |
9576 | << RHS.get()->getSourceRange(); |
9577 | } |
9578 | } |
9579 | } |
9580 | |
9581 | if (getLangOpts().CPlusPlus) { |
9582 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { |
9583 | // C++ 5.17p3: If the left operand is not of class type, the |
9584 | // expression is implicitly converted (C++ 4) to the |
9585 | // cv-unqualified type of the left operand. |
9586 | QualType RHSType = RHS.get()->getType(); |
9587 | if (Diagnose) { |
9588 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9589 | Action: AA_Assigning); |
9590 | } else { |
9591 | ImplicitConversionSequence ICS = |
9592 | TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9593 | /*SuppressUserConversions=*/false, |
9594 | AllowExplicit: AllowedExplicit::None, |
9595 | /*InOverloadResolution=*/false, |
9596 | /*CStyle=*/false, |
9597 | /*AllowObjCWritebackConversion=*/false); |
9598 | if (ICS.isFailure()) |
9599 | return Incompatible; |
9600 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9601 | ICS, Action: AA_Assigning); |
9602 | } |
9603 | if (RHS.isInvalid()) |
9604 | return Incompatible; |
9605 | Sema::AssignConvertType result = Compatible; |
9606 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
9607 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType)) |
9608 | result = IncompatibleObjCWeakRef; |
9609 | return result; |
9610 | } |
9611 | |
9612 | // FIXME: Currently, we fall through and treat C++ classes like C |
9613 | // structures. |
9614 | // FIXME: We also fall through for atomics; not sure what should |
9615 | // happen there, though. |
9616 | } else if (RHS.get()->getType() == Context.OverloadTy) { |
9617 | // As a set of extensions to C, we support overloading on functions. These |
9618 | // functions need to be resolved here. |
9619 | DeclAccessPair DAP; |
9620 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( |
9621 | AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP)) |
9622 | RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD); |
9623 | else |
9624 | return Incompatible; |
9625 | } |
9626 | |
9627 | // This check seems unnatural, however it is necessary to ensure the proper |
9628 | // conversion of functions/arrays. If the conversion were done for all |
9629 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary |
9630 | // expressions that suppress this implicit conversion (&, sizeof). This needs |
9631 | // to happen before we check for null pointer conversions because C does not |
9632 | // undergo the same implicit conversions as C++ does above (by the calls to |
9633 | // TryImplicitConversion() and PerformImplicitConversion()) which insert the |
9634 | // lvalue to rvalue cast before checking for null pointer constraints. This |
9635 | // addresses code like: nullptr_t val; int *ptr; ptr = val; |
9636 | // |
9637 | // Suppress this for references: C++ 8.5.3p5. |
9638 | if (!LHSType->isReferenceType()) { |
9639 | // FIXME: We potentially allocate here even if ConvertRHS is false. |
9640 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose); |
9641 | if (RHS.isInvalid()) |
9642 | return Incompatible; |
9643 | } |
9644 | |
9645 | // The constraints are expressed in terms of the atomic, qualified, or |
9646 | // unqualified type of the LHS. |
9647 | QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType(); |
9648 | |
9649 | // C99 6.5.16.1p1: the left operand is a pointer and the right is |
9650 | // a null pointer constant <C23>or its type is nullptr_t;</C23>. |
9651 | if ((LHSTypeAfterConversion->isPointerType() || |
9652 | LHSTypeAfterConversion->isObjCObjectPointerType() || |
9653 | LHSTypeAfterConversion->isBlockPointerType()) && |
9654 | ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) || |
9655 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
9656 | NPC: Expr::NPC_ValueDependentIsNull))) { |
9657 | if (Diagnose || ConvertRHS) { |
9658 | CastKind Kind; |
9659 | CXXCastPath Path; |
9660 | CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path, |
9661 | /*IgnoreBaseAccess=*/false, Diagnose); |
9662 | if (ConvertRHS) |
9663 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path); |
9664 | } |
9665 | return Compatible; |
9666 | } |
9667 | // C23 6.5.16.1p1: the left operand has type atomic, qualified, or |
9668 | // unqualified bool, and the right operand is a pointer or its type is |
9669 | // nullptr_t. |
9670 | if (getLangOpts().C23 && LHSType->isBooleanType() && |
9671 | RHS.get()->getType()->isNullPtrType()) { |
9672 | // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only |
9673 | // only handles nullptr -> _Bool due to needing an extra conversion |
9674 | // step. |
9675 | // We model this by converting from nullptr -> void * and then let the |
9676 | // conversion from void * -> _Bool happen naturally. |
9677 | if (Diagnose || ConvertRHS) { |
9678 | CastKind Kind; |
9679 | CXXCastPath Path; |
9680 | CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path, |
9681 | /*IgnoreBaseAccess=*/false, Diagnose); |
9682 | if (ConvertRHS) |
9683 | RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue, |
9684 | BasePath: &Path); |
9685 | } |
9686 | } |
9687 | |
9688 | // OpenCL queue_t type assignment. |
9689 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( |
9690 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
9691 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
9692 | return Compatible; |
9693 | } |
9694 | |
9695 | CastKind Kind; |
9696 | Sema::AssignConvertType result = |
9697 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); |
9698 | |
9699 | // C99 6.5.16.1p2: The value of the right operand is converted to the |
9700 | // type of the assignment expression. |
9701 | // CheckAssignmentConstraints allows the left-hand side to be a reference, |
9702 | // so that we can use references in built-in functions even in C. |
9703 | // The getNonReferenceType() call makes sure that the resulting expression |
9704 | // does not have reference type. |
9705 | if (result != Incompatible && RHS.get()->getType() != LHSType) { |
9706 | QualType Ty = LHSType.getNonLValueExprType(Context); |
9707 | Expr *E = RHS.get(); |
9708 | |
9709 | // Check for various Objective-C errors. If we are not reporting |
9710 | // diagnostics and just checking for errors, e.g., during overload |
9711 | // resolution, return Incompatible to indicate the failure. |
9712 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
9713 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E, |
9714 | CCK: CheckedConversionKind::Implicit, Diagnose, |
9715 | DiagnoseCFAudited) != SemaObjC::ACR_okay) { |
9716 | if (!Diagnose) |
9717 | return Incompatible; |
9718 | } |
9719 | if (getLangOpts().ObjC && |
9720 | (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType, |
9721 | SrcType: E->getType(), SrcExpr&: E, Diagnose) || |
9722 | ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) { |
9723 | if (!Diagnose) |
9724 | return Incompatible; |
9725 | // Replace the expression with a corrected version and continue so we |
9726 | // can find further errors. |
9727 | RHS = E; |
9728 | return Compatible; |
9729 | } |
9730 | |
9731 | if (ConvertRHS) |
9732 | RHS = ImpCastExprToType(E, Type: Ty, CK: Kind); |
9733 | } |
9734 | |
9735 | return result; |
9736 | } |
9737 | |
9738 | namespace { |
9739 | /// The original operand to an operator, prior to the application of the usual |
9740 | /// arithmetic conversions and converting the arguments of a builtin operator |
9741 | /// candidate. |
9742 | struct OriginalOperand { |
9743 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { |
9744 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op)) |
9745 | Op = MTE->getSubExpr(); |
9746 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op)) |
9747 | Op = BTE->getSubExpr(); |
9748 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) { |
9749 | Orig = ICE->getSubExprAsWritten(); |
9750 | Conversion = ICE->getConversionFunction(); |
9751 | } |
9752 | } |
9753 | |
9754 | QualType getType() const { return Orig->getType(); } |
9755 | |
9756 | Expr *Orig; |
9757 | NamedDecl *Conversion; |
9758 | }; |
9759 | } |
9760 | |
9761 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
9762 | ExprResult &RHS) { |
9763 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); |
9764 | |
9765 | Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
9766 | << OrigLHS.getType() << OrigRHS.getType() |
9767 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
9768 | |
9769 | // If a user-defined conversion was applied to either of the operands prior |
9770 | // to applying the built-in operator rules, tell the user about it. |
9771 | if (OrigLHS.Conversion) { |
9772 | Diag(Loc: OrigLHS.Conversion->getLocation(), |
9773 | DiagID: diag::note_typecheck_invalid_operands_converted) |
9774 | << 0 << LHS.get()->getType(); |
9775 | } |
9776 | if (OrigRHS.Conversion) { |
9777 | Diag(Loc: OrigRHS.Conversion->getLocation(), |
9778 | DiagID: diag::note_typecheck_invalid_operands_converted) |
9779 | << 1 << RHS.get()->getType(); |
9780 | } |
9781 | |
9782 | return QualType(); |
9783 | } |
9784 | |
9785 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
9786 | ExprResult &RHS) { |
9787 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); |
9788 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); |
9789 | |
9790 | bool LHSNatVec = LHSType->isVectorType(); |
9791 | bool RHSNatVec = RHSType->isVectorType(); |
9792 | |
9793 | if (!(LHSNatVec && RHSNatVec)) { |
9794 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); |
9795 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); |
9796 | Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
9797 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() |
9798 | << Vector->getSourceRange(); |
9799 | return QualType(); |
9800 | } |
9801 | |
9802 | Diag(Loc, DiagID: diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
9803 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() |
9804 | << RHS.get()->getSourceRange(); |
9805 | |
9806 | return QualType(); |
9807 | } |
9808 | |
9809 | /// Try to convert a value of non-vector type to a vector type by converting |
9810 | /// the type to the element type of the vector and then performing a splat. |
9811 | /// If the language is OpenCL, we only use conversions that promote scalar |
9812 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except |
9813 | /// for float->int. |
9814 | /// |
9815 | /// OpenCL V2.0 6.2.6.p2: |
9816 | /// An error shall occur if any scalar operand type has greater rank |
9817 | /// than the type of the vector element. |
9818 | /// |
9819 | /// \param scalar - if non-null, actually perform the conversions |
9820 | /// \return true if the operation fails (but without diagnosing the failure) |
9821 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, |
9822 | QualType scalarTy, |
9823 | QualType vectorEltTy, |
9824 | QualType vectorTy, |
9825 | unsigned &DiagID) { |
9826 | // The conversion to apply to the scalar before splatting it, |
9827 | // if necessary. |
9828 | CastKind scalarCast = CK_NoOp; |
9829 | |
9830 | if (vectorEltTy->isIntegralType(Ctx: S.Context)) { |
9831 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || |
9832 | (scalarTy->isIntegerType() && |
9833 | S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) { |
9834 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
9835 | return true; |
9836 | } |
9837 | if (!scalarTy->isIntegralType(Ctx: S.Context)) |
9838 | return true; |
9839 | scalarCast = CK_IntegralCast; |
9840 | } else if (vectorEltTy->isRealFloatingType()) { |
9841 | if (scalarTy->isRealFloatingType()) { |
9842 | if (S.getLangOpts().OpenCL && |
9843 | S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) { |
9844 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
9845 | return true; |
9846 | } |
9847 | scalarCast = CK_FloatingCast; |
9848 | } |
9849 | else if (scalarTy->isIntegralType(Ctx: S.Context)) |
9850 | scalarCast = CK_IntegralToFloating; |
9851 | else |
9852 | return true; |
9853 | } else { |
9854 | return true; |
9855 | } |
9856 | |
9857 | // Adjust scalar if desired. |
9858 | if (scalar) { |
9859 | if (scalarCast != CK_NoOp) |
9860 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast); |
9861 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat); |
9862 | } |
9863 | return false; |
9864 | } |
9865 | |
9866 | /// Convert vector E to a vector with the same number of elements but different |
9867 | /// element type. |
9868 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { |
9869 | const auto *VecTy = E->getType()->getAs<VectorType>(); |
9870 | assert(VecTy && "Expression E must be a vector" ); |
9871 | QualType NewVecTy = |
9872 | VecTy->isExtVectorType() |
9873 | ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements()) |
9874 | : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(), |
9875 | VecKind: VecTy->getVectorKind()); |
9876 | |
9877 | // Look through the implicit cast. Return the subexpression if its type is |
9878 | // NewVecTy. |
9879 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
9880 | if (ICE->getSubExpr()->getType() == NewVecTy) |
9881 | return ICE->getSubExpr(); |
9882 | |
9883 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; |
9884 | return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast); |
9885 | } |
9886 | |
9887 | /// Test if a (constant) integer Int can be casted to another integer type |
9888 | /// IntTy without losing precision. |
9889 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, |
9890 | QualType OtherIntTy) { |
9891 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
9892 | |
9893 | // Reject cases where the value of the Int is unknown as that would |
9894 | // possibly cause truncation, but accept cases where the scalar can be |
9895 | // demoted without loss of precision. |
9896 | Expr::EvalResult EVResult; |
9897 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
9898 | int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy); |
9899 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); |
9900 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); |
9901 | |
9902 | if (CstInt) { |
9903 | // If the scalar is constant and is of a higher order and has more active |
9904 | // bits that the vector element type, reject it. |
9905 | llvm::APSInt Result = EVResult.Val.getInt(); |
9906 | unsigned NumBits = IntSigned |
9907 | ? (Result.isNegative() ? Result.getSignificantBits() |
9908 | : Result.getActiveBits()) |
9909 | : Result.getActiveBits(); |
9910 | if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits) |
9911 | return true; |
9912 | |
9913 | // If the signedness of the scalar type and the vector element type |
9914 | // differs and the number of bits is greater than that of the vector |
9915 | // element reject it. |
9916 | return (IntSigned != OtherIntSigned && |
9917 | NumBits > S.Context.getIntWidth(T: OtherIntTy)); |
9918 | } |
9919 | |
9920 | // Reject cases where the value of the scalar is not constant and it's |
9921 | // order is greater than that of the vector element type. |
9922 | return (Order < 0); |
9923 | } |
9924 | |
9925 | /// Test if a (constant) integer Int can be casted to floating point type |
9926 | /// FloatTy without losing precision. |
9927 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, |
9928 | QualType FloatTy) { |
9929 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
9930 | |
9931 | // Determine if the integer constant can be expressed as a floating point |
9932 | // number of the appropriate type. |
9933 | Expr::EvalResult EVResult; |
9934 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
9935 | |
9936 | uint64_t Bits = 0; |
9937 | if (CstInt) { |
9938 | // Reject constants that would be truncated if they were converted to |
9939 | // the floating point type. Test by simple to/from conversion. |
9940 | // FIXME: Ideally the conversion to an APFloat and from an APFloat |
9941 | // could be avoided if there was a convertFromAPInt method |
9942 | // which could signal back if implicit truncation occurred. |
9943 | llvm::APSInt Result = EVResult.Val.getInt(); |
9944 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy)); |
9945 | Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(), |
9946 | RM: llvm::APFloat::rmTowardZero); |
9947 | llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy), |
9948 | !IntTy->hasSignedIntegerRepresentation()); |
9949 | bool Ignored = false; |
9950 | Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven, |
9951 | IsExact: &Ignored); |
9952 | if (Result != ConvertBack) |
9953 | return true; |
9954 | } else { |
9955 | // Reject types that cannot be fully encoded into the mantissa of |
9956 | // the float. |
9957 | Bits = S.Context.getTypeSize(T: IntTy); |
9958 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( |
9959 | S.Context.getFloatTypeSemantics(T: FloatTy)); |
9960 | if (Bits > FloatPrec) |
9961 | return true; |
9962 | } |
9963 | |
9964 | return false; |
9965 | } |
9966 | |
9967 | /// Attempt to convert and splat Scalar into a vector whose types matches |
9968 | /// Vector following GCC conversion rules. The rule is that implicit |
9969 | /// conversion can occur when Scalar can be casted to match Vector's element |
9970 | /// type without causing truncation of Scalar. |
9971 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, |
9972 | ExprResult *Vector) { |
9973 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); |
9974 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); |
9975 | QualType VectorEltTy; |
9976 | |
9977 | if (const auto *VT = VectorTy->getAs<VectorType>()) { |
9978 | assert(!isa<ExtVectorType>(VT) && |
9979 | "ExtVectorTypes should not be handled here!" ); |
9980 | VectorEltTy = VT->getElementType(); |
9981 | } else if (VectorTy->isSveVLSBuiltinType()) { |
9982 | VectorEltTy = |
9983 | VectorTy->castAs<BuiltinType>()->getSveEltType(Ctx: S.getASTContext()); |
9984 | } else { |
9985 | llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here" ); |
9986 | } |
9987 | |
9988 | // Reject cases where the vector element type or the scalar element type are |
9989 | // not integral or floating point types. |
9990 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) |
9991 | return true; |
9992 | |
9993 | // The conversion to apply to the scalar before splatting it, |
9994 | // if necessary. |
9995 | CastKind ScalarCast = CK_NoOp; |
9996 | |
9997 | // Accept cases where the vector elements are integers and the scalar is |
9998 | // an integer. |
9999 | // FIXME: Notionally if the scalar was a floating point value with a precise |
10000 | // integral representation, we could cast it to an appropriate integer |
10001 | // type and then perform the rest of the checks here. GCC will perform |
10002 | // this conversion in some cases as determined by the input language. |
10003 | // We should accept it on a language independent basis. |
10004 | if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
10005 | ScalarTy->isIntegralType(Ctx: S.Context) && |
10006 | S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) { |
10007 | |
10008 | if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy)) |
10009 | return true; |
10010 | |
10011 | ScalarCast = CK_IntegralCast; |
10012 | } else if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
10013 | ScalarTy->isRealFloatingType()) { |
10014 | if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy)) |
10015 | ScalarCast = CK_FloatingToIntegral; |
10016 | else |
10017 | return true; |
10018 | } else if (VectorEltTy->isRealFloatingType()) { |
10019 | if (ScalarTy->isRealFloatingType()) { |
10020 | |
10021 | // Reject cases where the scalar type is not a constant and has a higher |
10022 | // Order than the vector element type. |
10023 | llvm::APFloat Result(0.0); |
10024 | |
10025 | // Determine whether this is a constant scalar. In the event that the |
10026 | // value is dependent (and thus cannot be evaluated by the constant |
10027 | // evaluator), skip the evaluation. This will then diagnose once the |
10028 | // expression is instantiated. |
10029 | bool CstScalar = Scalar->get()->isValueDependent() || |
10030 | Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context); |
10031 | int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy); |
10032 | if (!CstScalar && Order < 0) |
10033 | return true; |
10034 | |
10035 | // If the scalar cannot be safely casted to the vector element type, |
10036 | // reject it. |
10037 | if (CstScalar) { |
10038 | bool Truncated = false; |
10039 | Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy), |
10040 | RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated); |
10041 | if (Truncated) |
10042 | return true; |
10043 | } |
10044 | |
10045 | ScalarCast = CK_FloatingCast; |
10046 | } else if (ScalarTy->isIntegralType(Ctx: S.Context)) { |
10047 | if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy)) |
10048 | return true; |
10049 | |
10050 | ScalarCast = CK_IntegralToFloating; |
10051 | } else |
10052 | return true; |
10053 | } else if (ScalarTy->isEnumeralType()) |
10054 | return true; |
10055 | |
10056 | // Adjust scalar if desired. |
10057 | if (ScalarCast != CK_NoOp) |
10058 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast); |
10059 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat); |
10060 | return false; |
10061 | } |
10062 | |
10063 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
10064 | SourceLocation Loc, bool IsCompAssign, |
10065 | bool AllowBothBool, |
10066 | bool AllowBoolConversions, |
10067 | bool AllowBoolOperation, |
10068 | bool ReportInvalid) { |
10069 | if (!IsCompAssign) { |
10070 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
10071 | if (LHS.isInvalid()) |
10072 | return QualType(); |
10073 | } |
10074 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
10075 | if (RHS.isInvalid()) |
10076 | return QualType(); |
10077 | |
10078 | // For conversion purposes, we ignore any qualifiers. |
10079 | // For example, "const float" and "float" are equivalent. |
10080 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
10081 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
10082 | |
10083 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); |
10084 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); |
10085 | assert(LHSVecType || RHSVecType); |
10086 | |
10087 | // AltiVec-style "vector bool op vector bool" combinations are allowed |
10088 | // for some operators but not others. |
10089 | if (!AllowBothBool && LHSVecType && |
10090 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType && |
10091 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
10092 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
10093 | |
10094 | // This operation may not be performed on boolean vectors. |
10095 | if (!AllowBoolOperation && |
10096 | (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) |
10097 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
10098 | |
10099 | // If the vector types are identical, return. |
10100 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
10101 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
10102 | |
10103 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. |
10104 | if (LHSVecType && RHSVecType && |
10105 | Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
10106 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
10107 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
10108 | return LHSType; |
10109 | } |
10110 | |
10111 | if (!IsCompAssign) |
10112 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
10113 | return RHSType; |
10114 | } |
10115 | |
10116 | // AllowBoolConversions says that bool and non-bool AltiVec vectors |
10117 | // can be mixed, with the result being the non-bool type. The non-bool |
10118 | // operand must have integer element type. |
10119 | if (AllowBoolConversions && LHSVecType && RHSVecType && |
10120 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && |
10121 | (Context.getTypeSize(T: LHSVecType->getElementType()) == |
10122 | Context.getTypeSize(T: RHSVecType->getElementType()))) { |
10123 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
10124 | LHSVecType->getElementType()->isIntegerType() && |
10125 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) { |
10126 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
10127 | return LHSType; |
10128 | } |
10129 | if (!IsCompAssign && |
10130 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && |
10131 | RHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
10132 | RHSVecType->getElementType()->isIntegerType()) { |
10133 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
10134 | return RHSType; |
10135 | } |
10136 | } |
10137 | |
10138 | // Expressions containing fixed-length and sizeless SVE/RVV vectors are |
10139 | // invalid since the ambiguity can affect the ABI. |
10140 | auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType, |
10141 | unsigned &SVEorRVV) { |
10142 | const VectorType *VecType = SecondType->getAs<VectorType>(); |
10143 | SVEorRVV = 0; |
10144 | if (FirstType->isSizelessBuiltinType() && VecType) { |
10145 | if (VecType->getVectorKind() == VectorKind::SveFixedLengthData || |
10146 | VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate) |
10147 | return true; |
10148 | if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
10149 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) { |
10150 | SVEorRVV = 1; |
10151 | return true; |
10152 | } |
10153 | } |
10154 | |
10155 | return false; |
10156 | }; |
10157 | |
10158 | unsigned SVEorRVV; |
10159 | if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) || |
10160 | IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) { |
10161 | Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_ambiguous) |
10162 | << SVEorRVV << LHSType << RHSType; |
10163 | return QualType(); |
10164 | } |
10165 | |
10166 | // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are |
10167 | // invalid since the ambiguity can affect the ABI. |
10168 | auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType, |
10169 | unsigned &SVEorRVV) { |
10170 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); |
10171 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); |
10172 | |
10173 | SVEorRVV = 0; |
10174 | if (FirstVecType && SecondVecType) { |
10175 | if (FirstVecType->getVectorKind() == VectorKind::Generic) { |
10176 | if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData || |
10177 | SecondVecType->getVectorKind() == |
10178 | VectorKind::SveFixedLengthPredicate) |
10179 | return true; |
10180 | if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
10181 | SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) { |
10182 | SVEorRVV = 1; |
10183 | return true; |
10184 | } |
10185 | } |
10186 | return false; |
10187 | } |
10188 | |
10189 | if (SecondVecType && |
10190 | SecondVecType->getVectorKind() == VectorKind::Generic) { |
10191 | if (FirstType->isSVESizelessBuiltinType()) |
10192 | return true; |
10193 | if (FirstType->isRVVSizelessBuiltinType()) { |
10194 | SVEorRVV = 1; |
10195 | return true; |
10196 | } |
10197 | } |
10198 | |
10199 | return false; |
10200 | }; |
10201 | |
10202 | if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) || |
10203 | IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) { |
10204 | Diag(Loc, DiagID: diag::err_typecheck_sve_rvv_gnu_ambiguous) |
10205 | << SVEorRVV << LHSType << RHSType; |
10206 | return QualType(); |
10207 | } |
10208 | |
10209 | // If there's a vector type and a scalar, try to convert the scalar to |
10210 | // the vector element type and splat. |
10211 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; |
10212 | if (!RHSVecType) { |
10213 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
10214 | if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType, |
10215 | vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType, |
10216 | DiagID)) |
10217 | return LHSType; |
10218 | } else { |
10219 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
10220 | return LHSType; |
10221 | } |
10222 | } |
10223 | if (!LHSVecType) { |
10224 | if (isa<ExtVectorType>(Val: RHSVecType)) { |
10225 | if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS), |
10226 | scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(), |
10227 | vectorTy: RHSType, DiagID)) |
10228 | return RHSType; |
10229 | } else { |
10230 | if (LHS.get()->isLValue() || |
10231 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
10232 | return RHSType; |
10233 | } |
10234 | } |
10235 | |
10236 | // FIXME: The code below also handles conversion between vectors and |
10237 | // non-scalars, we should break this down into fine grained specific checks |
10238 | // and emit proper diagnostics. |
10239 | QualType VecType = LHSVecType ? LHSType : RHSType; |
10240 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; |
10241 | QualType OtherType = LHSVecType ? RHSType : LHSType; |
10242 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; |
10243 | if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) { |
10244 | if (Context.getTargetInfo().getTriple().isPPC() && |
10245 | anyAltivecTypes(SrcTy: RHSType, DestTy: LHSType) && |
10246 | !Context.areCompatibleVectorTypes(FirstVec: RHSType, SecondVec: LHSType)) |
10247 | Diag(Loc, DiagID: diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; |
10248 | // If we're allowing lax vector conversions, only the total (data) size |
10249 | // needs to be the same. For non compound assignment, if one of the types is |
10250 | // scalar, the result is always the vector type. |
10251 | if (!IsCompAssign) { |
10252 | *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast); |
10253 | return VecType; |
10254 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding |
10255 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' |
10256 | // type. Note that this is already done by non-compound assignments in |
10257 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for |
10258 | // <1 x T> -> T. The result is also a vector type. |
10259 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || |
10260 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { |
10261 | ExprResult *RHSExpr = &RHS; |
10262 | *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast); |
10263 | return VecType; |
10264 | } |
10265 | } |
10266 | |
10267 | // Okay, the expression is invalid. |
10268 | |
10269 | // If there's a non-vector, non-real operand, diagnose that. |
10270 | if ((!RHSVecType && !RHSType->isRealType()) || |
10271 | (!LHSVecType && !LHSType->isRealType())) { |
10272 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar) |
10273 | << LHSType << RHSType |
10274 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10275 | return QualType(); |
10276 | } |
10277 | |
10278 | // OpenCL V1.1 6.2.6.p1: |
10279 | // If the operands are of more than one vector type, then an error shall |
10280 | // occur. Implicit conversions between vector types are not permitted, per |
10281 | // section 6.2.1. |
10282 | if (getLangOpts().OpenCL && |
10283 | RHSVecType && isa<ExtVectorType>(Val: RHSVecType) && |
10284 | LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) { |
10285 | Diag(Loc, DiagID: diag::err_opencl_implicit_vector_conversion) << LHSType |
10286 | << RHSType; |
10287 | return QualType(); |
10288 | } |
10289 | |
10290 | |
10291 | // If there is a vector type that is not a ExtVector and a scalar, we reach |
10292 | // this point if scalar could not be converted to the vector's element type |
10293 | // without truncation. |
10294 | if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) || |
10295 | (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) { |
10296 | QualType Scalar = LHSVecType ? RHSType : LHSType; |
10297 | QualType Vector = LHSVecType ? LHSType : RHSType; |
10298 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; |
10299 | Diag(Loc, |
10300 | DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation) |
10301 | << ScalarOrVector << Scalar << Vector; |
10302 | |
10303 | return QualType(); |
10304 | } |
10305 | |
10306 | // Otherwise, use the generic diagnostic. |
10307 | Diag(Loc, DiagID) |
10308 | << LHSType << RHSType |
10309 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10310 | return QualType(); |
10311 | } |
10312 | |
10313 | QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, |
10314 | SourceLocation Loc, |
10315 | bool IsCompAssign, |
10316 | ArithConvKind OperationKind) { |
10317 | if (!IsCompAssign) { |
10318 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
10319 | if (LHS.isInvalid()) |
10320 | return QualType(); |
10321 | } |
10322 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
10323 | if (RHS.isInvalid()) |
10324 | return QualType(); |
10325 | |
10326 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
10327 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
10328 | |
10329 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
10330 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); |
10331 | |
10332 | unsigned DiagID = diag::err_typecheck_invalid_operands; |
10333 | if ((OperationKind == ACK_Arithmetic) && |
10334 | ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
10335 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { |
10336 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
10337 | << RHS.get()->getSourceRange(); |
10338 | return QualType(); |
10339 | } |
10340 | |
10341 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
10342 | return LHSType; |
10343 | |
10344 | if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) { |
10345 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
10346 | return LHSType; |
10347 | } |
10348 | if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) { |
10349 | if (LHS.get()->isLValue() || |
10350 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
10351 | return RHSType; |
10352 | } |
10353 | |
10354 | if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) || |
10355 | (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) { |
10356 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_non_scalar) |
10357 | << LHSType << RHSType << LHS.get()->getSourceRange() |
10358 | << RHS.get()->getSourceRange(); |
10359 | return QualType(); |
10360 | } |
10361 | |
10362 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
10363 | Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
10364 | Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) { |
10365 | Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
10366 | << LHSType << RHSType << LHS.get()->getSourceRange() |
10367 | << RHS.get()->getSourceRange(); |
10368 | return QualType(); |
10369 | } |
10370 | |
10371 | if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) { |
10372 | QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType; |
10373 | QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType; |
10374 | bool ScalarOrVector = |
10375 | LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType(); |
10376 | |
10377 | Diag(Loc, DiagID: diag::err_typecheck_vector_not_convertable_implict_truncation) |
10378 | << ScalarOrVector << Scalar << Vector; |
10379 | |
10380 | return QualType(); |
10381 | } |
10382 | |
10383 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
10384 | << RHS.get()->getSourceRange(); |
10385 | return QualType(); |
10386 | } |
10387 | |
10388 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an |
10389 | // expression. These are mainly cases where the null pointer is used as an |
10390 | // integer instead of a pointer. |
10391 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, |
10392 | SourceLocation Loc, bool IsCompare) { |
10393 | // The canonical way to check for a GNU null is with isNullPointerConstant, |
10394 | // but we use a bit of a hack here for speed; this is a relatively |
10395 | // hot path, and isNullPointerConstant is slow. |
10396 | bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts()); |
10397 | bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts()); |
10398 | |
10399 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); |
10400 | |
10401 | // Avoid analyzing cases where the result will either be invalid (and |
10402 | // diagnosed as such) or entirely valid and not something to warn about. |
10403 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || |
10404 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) |
10405 | return; |
10406 | |
10407 | // Comparison operations would not make sense with a null pointer no matter |
10408 | // what the other expression is. |
10409 | if (!IsCompare) { |
10410 | S.Diag(Loc, DiagID: diag::warn_null_in_arithmetic_operation) |
10411 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) |
10412 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); |
10413 | return; |
10414 | } |
10415 | |
10416 | // The rest of the operations only make sense with a null pointer |
10417 | // if the other expression is a pointer. |
10418 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || |
10419 | NonNullType->canDecayToPointerType()) |
10420 | return; |
10421 | |
10422 | S.Diag(Loc, DiagID: diag::warn_null_in_comparison_operation) |
10423 | << LHSNull /* LHS is NULL */ << NonNullType |
10424 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10425 | } |
10426 | |
10427 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, |
10428 | SourceLocation Loc) { |
10429 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS); |
10430 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS); |
10431 | if (!LUE || !RUE) |
10432 | return; |
10433 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || |
10434 | RUE->getKind() != UETT_SizeOf) |
10435 | return; |
10436 | |
10437 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); |
10438 | QualType LHSTy = LHSArg->getType(); |
10439 | QualType RHSTy; |
10440 | |
10441 | if (RUE->isArgumentType()) |
10442 | RHSTy = RUE->getArgumentType().getNonReferenceType(); |
10443 | else |
10444 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); |
10445 | |
10446 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { |
10447 | if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy)) |
10448 | return; |
10449 | |
10450 | S.Diag(Loc, DiagID: diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); |
10451 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
10452 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
10453 | S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_pointer_declared_here) |
10454 | << LHSArgDecl; |
10455 | } |
10456 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) { |
10457 | QualType ArrayElemTy = ArrayTy->getElementType(); |
10458 | if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) || |
10459 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || |
10460 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || |
10461 | S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy)) |
10462 | return; |
10463 | S.Diag(Loc, DiagID: diag::warn_division_sizeof_array) |
10464 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; |
10465 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
10466 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
10467 | S.Diag(Loc: LHSArgDecl->getLocation(), DiagID: diag::note_array_declared_here) |
10468 | << LHSArgDecl; |
10469 | } |
10470 | |
10471 | S.Diag(Loc, DiagID: diag::note_precedence_silence) << RHS; |
10472 | } |
10473 | } |
10474 | |
10475 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, |
10476 | ExprResult &RHS, |
10477 | SourceLocation Loc, bool IsDiv) { |
10478 | // Check for division/remainder by zero. |
10479 | Expr::EvalResult RHSValue; |
10480 | if (!RHS.get()->isValueDependent() && |
10481 | RHS.get()->EvaluateAsInt(Result&: RHSValue, Ctx: S.Context) && |
10482 | RHSValue.Val.getInt() == 0) |
10483 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
10484 | PD: S.PDiag(DiagID: diag::warn_remainder_division_by_zero) |
10485 | << IsDiv << RHS.get()->getSourceRange()); |
10486 | } |
10487 | |
10488 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, |
10489 | SourceLocation Loc, |
10490 | bool IsCompAssign, bool IsDiv) { |
10491 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10492 | |
10493 | QualType LHSTy = LHS.get()->getType(); |
10494 | QualType RHSTy = RHS.get()->getType(); |
10495 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) |
10496 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10497 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10498 | /*AllowBoolConversions*/ false, |
10499 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10500 | /*ReportInvalid*/ true); |
10501 | if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType()) |
10502 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10503 | OperationKind: ACK_Arithmetic); |
10504 | if (!IsDiv && |
10505 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) |
10506 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); |
10507 | // For division, only matrix-by-scalar is supported. Other combinations with |
10508 | // matrix types are invalid. |
10509 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) |
10510 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
10511 | |
10512 | QualType compType = UsualArithmeticConversions( |
10513 | LHS, RHS, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); |
10514 | if (LHS.isInvalid() || RHS.isInvalid()) |
10515 | return QualType(); |
10516 | |
10517 | |
10518 | if (compType.isNull() || !compType->isArithmeticType()) |
10519 | return InvalidOperands(Loc, LHS, RHS); |
10520 | if (IsDiv) { |
10521 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv); |
10522 | DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc); |
10523 | } |
10524 | return compType; |
10525 | } |
10526 | |
10527 | QualType Sema::CheckRemainderOperands( |
10528 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { |
10529 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10530 | |
10531 | if (LHS.get()->getType()->isVectorType() || |
10532 | RHS.get()->getType()->isVectorType()) { |
10533 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
10534 | RHS.get()->getType()->hasIntegerRepresentation()) |
10535 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10536 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10537 | /*AllowBoolConversions*/ false, |
10538 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10539 | /*ReportInvalid*/ true); |
10540 | return InvalidOperands(Loc, LHS, RHS); |
10541 | } |
10542 | |
10543 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
10544 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
10545 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
10546 | RHS.get()->getType()->hasIntegerRepresentation()) |
10547 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10548 | OperationKind: ACK_Arithmetic); |
10549 | |
10550 | return InvalidOperands(Loc, LHS, RHS); |
10551 | } |
10552 | |
10553 | QualType compType = UsualArithmeticConversions( |
10554 | LHS, RHS, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); |
10555 | if (LHS.isInvalid() || RHS.isInvalid()) |
10556 | return QualType(); |
10557 | |
10558 | if (compType.isNull() || !compType->isIntegerType()) |
10559 | return InvalidOperands(Loc, LHS, RHS); |
10560 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */); |
10561 | return compType; |
10562 | } |
10563 | |
10564 | /// Diagnose invalid arithmetic on two void pointers. |
10565 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, |
10566 | Expr *LHSExpr, Expr *RHSExpr) { |
10567 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
10568 | ? diag::err_typecheck_pointer_arith_void_type |
10569 | : diag::ext_gnu_void_ptr) |
10570 | << 1 /* two pointers */ << LHSExpr->getSourceRange() |
10571 | << RHSExpr->getSourceRange(); |
10572 | } |
10573 | |
10574 | /// Diagnose invalid arithmetic on a void pointer. |
10575 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, |
10576 | Expr *Pointer) { |
10577 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
10578 | ? diag::err_typecheck_pointer_arith_void_type |
10579 | : diag::ext_gnu_void_ptr) |
10580 | << 0 /* one pointer */ << Pointer->getSourceRange(); |
10581 | } |
10582 | |
10583 | /// Diagnose invalid arithmetic on a null pointer. |
10584 | /// |
10585 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' |
10586 | /// idiom, which we recognize as a GNU extension. |
10587 | /// |
10588 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, |
10589 | Expr *Pointer, bool IsGNUIdiom) { |
10590 | if (IsGNUIdiom) |
10591 | S.Diag(Loc, DiagID: diag::warn_gnu_null_ptr_arith) |
10592 | << Pointer->getSourceRange(); |
10593 | else |
10594 | S.Diag(Loc, DiagID: diag::warn_pointer_arith_null_ptr) |
10595 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); |
10596 | } |
10597 | |
10598 | /// Diagnose invalid subraction on a null pointer. |
10599 | /// |
10600 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, |
10601 | Expr *Pointer, bool BothNull) { |
10602 | // Null - null is valid in C++ [expr.add]p7 |
10603 | if (BothNull && S.getLangOpts().CPlusPlus) |
10604 | return; |
10605 | |
10606 | // Is this s a macro from a system header? |
10607 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc)) |
10608 | return; |
10609 | |
10610 | S.DiagRuntimeBehavior(Loc, Statement: Pointer, |
10611 | PD: S.PDiag(DiagID: diag::warn_pointer_sub_null_ptr) |
10612 | << S.getLangOpts().CPlusPlus |
10613 | << Pointer->getSourceRange()); |
10614 | } |
10615 | |
10616 | /// Diagnose invalid arithmetic on two function pointers. |
10617 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, |
10618 | Expr *LHS, Expr *RHS) { |
10619 | assert(LHS->getType()->isAnyPointerType()); |
10620 | assert(RHS->getType()->isAnyPointerType()); |
10621 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
10622 | ? diag::err_typecheck_pointer_arith_function_type |
10623 | : diag::ext_gnu_ptr_func_arith) |
10624 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() |
10625 | // We only show the second type if it differs from the first. |
10626 | << (unsigned)!S.Context.hasSameUnqualifiedType(T1: LHS->getType(), |
10627 | T2: RHS->getType()) |
10628 | << RHS->getType()->getPointeeType() |
10629 | << LHS->getSourceRange() << RHS->getSourceRange(); |
10630 | } |
10631 | |
10632 | /// Diagnose invalid arithmetic on a function pointer. |
10633 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, |
10634 | Expr *Pointer) { |
10635 | assert(Pointer->getType()->isAnyPointerType()); |
10636 | S.Diag(Loc, DiagID: S.getLangOpts().CPlusPlus |
10637 | ? diag::err_typecheck_pointer_arith_function_type |
10638 | : diag::ext_gnu_ptr_func_arith) |
10639 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() |
10640 | << 0 /* one pointer, so only one type */ |
10641 | << Pointer->getSourceRange(); |
10642 | } |
10643 | |
10644 | /// Emit error if Operand is incomplete pointer type |
10645 | /// |
10646 | /// \returns True if pointer has incomplete type |
10647 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, |
10648 | Expr *Operand) { |
10649 | QualType ResType = Operand->getType(); |
10650 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
10651 | ResType = ResAtomicType->getValueType(); |
10652 | |
10653 | assert(ResType->isAnyPointerType()); |
10654 | QualType PointeeTy = ResType->getPointeeType(); |
10655 | return S.RequireCompleteSizedType( |
10656 | Loc, T: PointeeTy, |
10657 | DiagID: diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, |
10658 | Args: Operand->getSourceRange()); |
10659 | } |
10660 | |
10661 | /// Check the validity of an arithmetic pointer operand. |
10662 | /// |
10663 | /// If the operand has pointer type, this code will check for pointer types |
10664 | /// which are invalid in arithmetic operations. These will be diagnosed |
10665 | /// appropriately, including whether or not the use is supported as an |
10666 | /// extension. |
10667 | /// |
10668 | /// \returns True when the operand is valid to use (even if as an extension). |
10669 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, |
10670 | Expr *Operand) { |
10671 | QualType ResType = Operand->getType(); |
10672 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
10673 | ResType = ResAtomicType->getValueType(); |
10674 | |
10675 | if (!ResType->isAnyPointerType()) return true; |
10676 | |
10677 | QualType PointeeTy = ResType->getPointeeType(); |
10678 | if (PointeeTy->isVoidType()) { |
10679 | diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand); |
10680 | return !S.getLangOpts().CPlusPlus; |
10681 | } |
10682 | if (PointeeTy->isFunctionType()) { |
10683 | diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand); |
10684 | return !S.getLangOpts().CPlusPlus; |
10685 | } |
10686 | |
10687 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; |
10688 | |
10689 | return true; |
10690 | } |
10691 | |
10692 | /// Check the validity of a binary arithmetic operation w.r.t. pointer |
10693 | /// operands. |
10694 | /// |
10695 | /// This routine will diagnose any invalid arithmetic on pointer operands much |
10696 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic |
10697 | /// for emitting a single diagnostic even for operations where both LHS and RHS |
10698 | /// are (potentially problematic) pointers. |
10699 | /// |
10700 | /// \returns True when the operand is valid to use (even if as an extension). |
10701 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, |
10702 | Expr *LHSExpr, Expr *RHSExpr) { |
10703 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); |
10704 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); |
10705 | if (!isLHSPointer && !isRHSPointer) return true; |
10706 | |
10707 | QualType LHSPointeeTy, RHSPointeeTy; |
10708 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); |
10709 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); |
10710 | |
10711 | // if both are pointers check if operation is valid wrt address spaces |
10712 | if (isLHSPointer && isRHSPointer) { |
10713 | if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy)) { |
10714 | S.Diag(Loc, |
10715 | DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
10716 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ |
10717 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); |
10718 | return false; |
10719 | } |
10720 | } |
10721 | |
10722 | // Check for arithmetic on pointers to incomplete types. |
10723 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); |
10724 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); |
10725 | if (isLHSVoidPtr || isRHSVoidPtr) { |
10726 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr); |
10727 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr); |
10728 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); |
10729 | |
10730 | return !S.getLangOpts().CPlusPlus; |
10731 | } |
10732 | |
10733 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); |
10734 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); |
10735 | if (isLHSFuncPtr || isRHSFuncPtr) { |
10736 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr); |
10737 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, |
10738 | Pointer: RHSExpr); |
10739 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr); |
10740 | |
10741 | return !S.getLangOpts().CPlusPlus; |
10742 | } |
10743 | |
10744 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr)) |
10745 | return false; |
10746 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr)) |
10747 | return false; |
10748 | |
10749 | return true; |
10750 | } |
10751 | |
10752 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string |
10753 | /// literal. |
10754 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, |
10755 | Expr *LHSExpr, Expr *RHSExpr) { |
10756 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
10757 | Expr* IndexExpr = RHSExpr; |
10758 | if (!StrExpr) { |
10759 | StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
10760 | IndexExpr = LHSExpr; |
10761 | } |
10762 | |
10763 | bool IsStringPlusInt = StrExpr && |
10764 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); |
10765 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) |
10766 | return; |
10767 | |
10768 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
10769 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_int) |
10770 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); |
10771 | |
10772 | // Only print a fixit for "str" + int, not for int + "str". |
10773 | if (IndexExpr == RHSExpr) { |
10774 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
10775 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence) |
10776 | << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&" ) |
10777 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[" ) |
10778 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]" ); |
10779 | } else |
10780 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence); |
10781 | } |
10782 | |
10783 | /// Emit a warning when adding a char literal to a string. |
10784 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, |
10785 | Expr *LHSExpr, Expr *RHSExpr) { |
10786 | const Expr *StringRefExpr = LHSExpr; |
10787 | const CharacterLiteral *CharExpr = |
10788 | dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
10789 | |
10790 | if (!CharExpr) { |
10791 | CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
10792 | StringRefExpr = RHSExpr; |
10793 | } |
10794 | |
10795 | if (!CharExpr || !StringRefExpr) |
10796 | return; |
10797 | |
10798 | const QualType StringType = StringRefExpr->getType(); |
10799 | |
10800 | // Return if not a PointerType. |
10801 | if (!StringType->isAnyPointerType()) |
10802 | return; |
10803 | |
10804 | // Return if not a CharacterType. |
10805 | if (!StringType->getPointeeType()->isAnyCharacterType()) |
10806 | return; |
10807 | |
10808 | ASTContext &Ctx = Self.getASTContext(); |
10809 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
10810 | |
10811 | const QualType CharType = CharExpr->getType(); |
10812 | if (!CharType->isAnyCharacterType() && |
10813 | CharType->isIntegerType() && |
10814 | llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) { |
10815 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char) |
10816 | << DiagRange << Ctx.CharTy; |
10817 | } else { |
10818 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_string_plus_char) |
10819 | << DiagRange << CharExpr->getType(); |
10820 | } |
10821 | |
10822 | // Only print a fixit for str + char, not for char + str. |
10823 | if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) { |
10824 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
10825 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence) |
10826 | << FixItHint::CreateInsertion(InsertionLoc: LHSExpr->getBeginLoc(), Code: "&" ) |
10827 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OpLoc), Code: "[" ) |
10828 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: "]" ); |
10829 | } else { |
10830 | Self.Diag(Loc: OpLoc, DiagID: diag::note_string_plus_scalar_silence); |
10831 | } |
10832 | } |
10833 | |
10834 | /// Emit error when two pointers are incompatible. |
10835 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, |
10836 | Expr *LHSExpr, Expr *RHSExpr) { |
10837 | assert(LHSExpr->getType()->isAnyPointerType()); |
10838 | assert(RHSExpr->getType()->isAnyPointerType()); |
10839 | S.Diag(Loc, DiagID: diag::err_typecheck_sub_ptr_compatible) |
10840 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() |
10841 | << RHSExpr->getSourceRange(); |
10842 | } |
10843 | |
10844 | // C99 6.5.6 |
10845 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, |
10846 | SourceLocation Loc, BinaryOperatorKind Opc, |
10847 | QualType* CompLHSTy) { |
10848 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10849 | |
10850 | if (LHS.get()->getType()->isVectorType() || |
10851 | RHS.get()->getType()->isVectorType()) { |
10852 | QualType compType = |
10853 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
10854 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10855 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
10856 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10857 | /*ReportInvalid*/ true); |
10858 | if (CompLHSTy) *CompLHSTy = compType; |
10859 | return compType; |
10860 | } |
10861 | |
10862 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
10863 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
10864 | QualType compType = |
10865 | CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, OperationKind: ACK_Arithmetic); |
10866 | if (CompLHSTy) |
10867 | *CompLHSTy = compType; |
10868 | return compType; |
10869 | } |
10870 | |
10871 | if (LHS.get()->getType()->isConstantMatrixType() || |
10872 | RHS.get()->getType()->isConstantMatrixType()) { |
10873 | QualType compType = |
10874 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
10875 | if (CompLHSTy) |
10876 | *CompLHSTy = compType; |
10877 | return compType; |
10878 | } |
10879 | |
10880 | QualType compType = UsualArithmeticConversions( |
10881 | LHS, RHS, Loc, ACK: CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); |
10882 | if (LHS.isInvalid() || RHS.isInvalid()) |
10883 | return QualType(); |
10884 | |
10885 | // Diagnose "string literal" '+' int and string '+' "char literal". |
10886 | if (Opc == BO_Add) { |
10887 | diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
10888 | diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
10889 | } |
10890 | |
10891 | // handle the common case first (both operands are arithmetic). |
10892 | if (!compType.isNull() && compType->isArithmeticType()) { |
10893 | if (CompLHSTy) *CompLHSTy = compType; |
10894 | return compType; |
10895 | } |
10896 | |
10897 | // Type-checking. Ultimately the pointer's going to be in PExp; |
10898 | // note that we bias towards the LHS being the pointer. |
10899 | Expr *PExp = LHS.get(), *IExp = RHS.get(); |
10900 | |
10901 | bool isObjCPointer; |
10902 | if (PExp->getType()->isPointerType()) { |
10903 | isObjCPointer = false; |
10904 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
10905 | isObjCPointer = true; |
10906 | } else { |
10907 | std::swap(a&: PExp, b&: IExp); |
10908 | if (PExp->getType()->isPointerType()) { |
10909 | isObjCPointer = false; |
10910 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
10911 | isObjCPointer = true; |
10912 | } else { |
10913 | return InvalidOperands(Loc, LHS, RHS); |
10914 | } |
10915 | } |
10916 | assert(PExp->getType()->isAnyPointerType()); |
10917 | |
10918 | if (!IExp->getType()->isIntegerType()) |
10919 | return InvalidOperands(Loc, LHS, RHS); |
10920 | |
10921 | // Adding to a null pointer results in undefined behavior. |
10922 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( |
10923 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
10924 | // In C++ adding zero to a null pointer is defined. |
10925 | Expr::EvalResult KnownVal; |
10926 | if (!getLangOpts().CPlusPlus || |
10927 | (!IExp->isValueDependent() && |
10928 | (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
10929 | KnownVal.Val.getInt() != 0))) { |
10930 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. |
10931 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( |
10932 | Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp); |
10933 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom); |
10934 | } |
10935 | } |
10936 | |
10937 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp)) |
10938 | return QualType(); |
10939 | |
10940 | if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp)) |
10941 | return QualType(); |
10942 | |
10943 | // Arithmetic on label addresses is normally allowed, except when we add |
10944 | // a ptrauth signature to the addresses. |
10945 | if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) { |
10946 | Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
10947 | << /*addition*/ 1; |
10948 | return QualType(); |
10949 | } |
10950 | |
10951 | // Check array bounds for pointer arithemtic |
10952 | CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp); |
10953 | |
10954 | if (CompLHSTy) { |
10955 | QualType LHSTy = Context.isPromotableBitField(E: LHS.get()); |
10956 | if (LHSTy.isNull()) { |
10957 | LHSTy = LHS.get()->getType(); |
10958 | if (Context.isPromotableIntegerType(T: LHSTy)) |
10959 | LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy); |
10960 | } |
10961 | *CompLHSTy = LHSTy; |
10962 | } |
10963 | |
10964 | return PExp->getType(); |
10965 | } |
10966 | |
10967 | // C99 6.5.6 |
10968 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, |
10969 | SourceLocation Loc, |
10970 | QualType* CompLHSTy) { |
10971 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10972 | |
10973 | if (LHS.get()->getType()->isVectorType() || |
10974 | RHS.get()->getType()->isVectorType()) { |
10975 | QualType compType = |
10976 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
10977 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10978 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
10979 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10980 | /*ReportInvalid*/ true); |
10981 | if (CompLHSTy) *CompLHSTy = compType; |
10982 | return compType; |
10983 | } |
10984 | |
10985 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
10986 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
10987 | QualType compType = |
10988 | CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, OperationKind: ACK_Arithmetic); |
10989 | if (CompLHSTy) |
10990 | *CompLHSTy = compType; |
10991 | return compType; |
10992 | } |
10993 | |
10994 | if (LHS.get()->getType()->isConstantMatrixType() || |
10995 | RHS.get()->getType()->isConstantMatrixType()) { |
10996 | QualType compType = |
10997 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
10998 | if (CompLHSTy) |
10999 | *CompLHSTy = compType; |
11000 | return compType; |
11001 | } |
11002 | |
11003 | QualType compType = UsualArithmeticConversions( |
11004 | LHS, RHS, Loc, ACK: CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); |
11005 | if (LHS.isInvalid() || RHS.isInvalid()) |
11006 | return QualType(); |
11007 | |
11008 | // Enforce type constraints: C99 6.5.6p3. |
11009 | |
11010 | // Handle the common case first (both operands are arithmetic). |
11011 | if (!compType.isNull() && compType->isArithmeticType()) { |
11012 | if (CompLHSTy) *CompLHSTy = compType; |
11013 | return compType; |
11014 | } |
11015 | |
11016 | // Either ptr - int or ptr - ptr. |
11017 | if (LHS.get()->getType()->isAnyPointerType()) { |
11018 | QualType lpointee = LHS.get()->getType()->getPointeeType(); |
11019 | |
11020 | // Diagnose bad cases where we step over interface counts. |
11021 | if (LHS.get()->getType()->isObjCObjectPointerType() && |
11022 | checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get())) |
11023 | return QualType(); |
11024 | |
11025 | // Arithmetic on label addresses is normally allowed, except when we add |
11026 | // a ptrauth signature to the addresses. |
11027 | if (isa<AddrLabelExpr>(Val: LHS.get()) && |
11028 | getLangOpts().PointerAuthIndirectGotos) { |
11029 | Diag(Loc, DiagID: diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
11030 | << /*subtraction*/ 0; |
11031 | return QualType(); |
11032 | } |
11033 | |
11034 | // The result type of a pointer-int computation is the pointer type. |
11035 | if (RHS.get()->getType()->isIntegerType()) { |
11036 | // Subtracting from a null pointer should produce a warning. |
11037 | // The last argument to the diagnose call says this doesn't match the |
11038 | // GNU int-to-pointer idiom. |
11039 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context, |
11040 | NPC: Expr::NPC_ValueDependentIsNotNull)) { |
11041 | // In C++ adding zero to a null pointer is defined. |
11042 | Expr::EvalResult KnownVal; |
11043 | if (!getLangOpts().CPlusPlus || |
11044 | (!RHS.get()->isValueDependent() && |
11045 | (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
11046 | KnownVal.Val.getInt() != 0))) { |
11047 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false); |
11048 | } |
11049 | } |
11050 | |
11051 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get())) |
11052 | return QualType(); |
11053 | |
11054 | // Check array bounds for pointer arithemtic |
11055 | CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr, |
11056 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); |
11057 | |
11058 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
11059 | return LHS.get()->getType(); |
11060 | } |
11061 | |
11062 | // Handle pointer-pointer subtractions. |
11063 | if (const PointerType *RHSPTy |
11064 | = RHS.get()->getType()->getAs<PointerType>()) { |
11065 | QualType rpointee = RHSPTy->getPointeeType(); |
11066 | |
11067 | if (getLangOpts().CPlusPlus) { |
11068 | // Pointee types must be the same: C++ [expr.add] |
11069 | if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) { |
11070 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11071 | } |
11072 | } else { |
11073 | // Pointee types must be compatible C99 6.5.6p3 |
11074 | if (!Context.typesAreCompatible( |
11075 | T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(), |
11076 | T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) { |
11077 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11078 | return QualType(); |
11079 | } |
11080 | } |
11081 | |
11082 | if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc, |
11083 | LHSExpr: LHS.get(), RHSExpr: RHS.get())) |
11084 | return QualType(); |
11085 | |
11086 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
11087 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
11088 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
11089 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
11090 | |
11091 | // Subtracting nullptr or from nullptr is suspect |
11092 | if (LHSIsNullPtr) |
11093 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr); |
11094 | if (RHSIsNullPtr) |
11095 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr); |
11096 | |
11097 | // The pointee type may have zero size. As an extension, a structure or |
11098 | // union may have zero size or an array may have zero length. In this |
11099 | // case subtraction does not make sense. |
11100 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { |
11101 | CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee); |
11102 | if (ElementSize.isZero()) { |
11103 | Diag(Loc,DiagID: diag::warn_sub_ptr_zero_size_types) |
11104 | << rpointee.getUnqualifiedType() |
11105 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11106 | } |
11107 | } |
11108 | |
11109 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
11110 | return Context.getPointerDiffType(); |
11111 | } |
11112 | } |
11113 | |
11114 | return InvalidOperands(Loc, LHS, RHS); |
11115 | } |
11116 | |
11117 | static bool isScopedEnumerationType(QualType T) { |
11118 | if (const EnumType *ET = T->getAs<EnumType>()) |
11119 | return ET->getDecl()->isScoped(); |
11120 | return false; |
11121 | } |
11122 | |
11123 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, |
11124 | SourceLocation Loc, BinaryOperatorKind Opc, |
11125 | QualType LHSType) { |
11126 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), |
11127 | // so skip remaining warnings as we don't want to modify values within Sema. |
11128 | if (S.getLangOpts().OpenCL) |
11129 | return; |
11130 | |
11131 | // Check right/shifter operand |
11132 | Expr::EvalResult RHSResult; |
11133 | if (RHS.get()->isValueDependent() || |
11134 | !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context)) |
11135 | return; |
11136 | llvm::APSInt Right = RHSResult.Val.getInt(); |
11137 | |
11138 | if (Right.isNegative()) { |
11139 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
11140 | PD: S.PDiag(DiagID: diag::warn_shift_negative) |
11141 | << RHS.get()->getSourceRange()); |
11142 | return; |
11143 | } |
11144 | |
11145 | QualType LHSExprType = LHS.get()->getType(); |
11146 | uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType); |
11147 | if (LHSExprType->isBitIntType()) |
11148 | LeftSize = S.Context.getIntWidth(T: LHSExprType); |
11149 | else if (LHSExprType->isFixedPointType()) { |
11150 | auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType); |
11151 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); |
11152 | } |
11153 | if (Right.uge(RHS: LeftSize)) { |
11154 | S.DiagRuntimeBehavior(Loc, Statement: RHS.get(), |
11155 | PD: S.PDiag(DiagID: diag::warn_shift_gt_typewidth) |
11156 | << RHS.get()->getSourceRange()); |
11157 | return; |
11158 | } |
11159 | |
11160 | // FIXME: We probably need to handle fixed point types specially here. |
11161 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) |
11162 | return; |
11163 | |
11164 | // When left shifting an ICE which is signed, we can check for overflow which |
11165 | // according to C++ standards prior to C++2a has undefined behavior |
11166 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one |
11167 | // more than the maximum value representable in the result type, so never |
11168 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant |
11169 | // expression is still probably a bug.) |
11170 | Expr::EvalResult LHSResult; |
11171 | if (LHS.get()->isValueDependent() || |
11172 | LHSType->hasUnsignedIntegerRepresentation() || |
11173 | !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context)) |
11174 | return; |
11175 | llvm::APSInt Left = LHSResult.Val.getInt(); |
11176 | |
11177 | // Don't warn if signed overflow is defined, then all the rest of the |
11178 | // diagnostics will not be triggered because the behavior is defined. |
11179 | // Also don't warn in C++20 mode (and newer), as signed left shifts |
11180 | // always wrap and never overflow. |
11181 | if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) |
11182 | return; |
11183 | |
11184 | // If LHS does not have a non-negative value then, the |
11185 | // behavior is undefined before C++2a. Warn about it. |
11186 | if (Left.isNegative()) { |
11187 | S.DiagRuntimeBehavior(Loc, Statement: LHS.get(), |
11188 | PD: S.PDiag(DiagID: diag::warn_shift_lhs_negative) |
11189 | << LHS.get()->getSourceRange()); |
11190 | return; |
11191 | } |
11192 | |
11193 | llvm::APInt ResultBits = |
11194 | static_cast<llvm::APInt &>(Right) + Left.getSignificantBits(); |
11195 | if (ResultBits.ule(RHS: LeftSize)) |
11196 | return; |
11197 | llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue()); |
11198 | Result = Result.shl(ShiftAmt: Right); |
11199 | |
11200 | // Print the bit representation of the signed integer as an unsigned |
11201 | // hexadecimal number. |
11202 | SmallString<40> HexResult; |
11203 | Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true); |
11204 | |
11205 | // If we are only missing a sign bit, this is less likely to result in actual |
11206 | // bugs -- if the result is cast back to an unsigned type, it will have the |
11207 | // expected value. Thus we place this behind a different warning that can be |
11208 | // turned off separately if needed. |
11209 | if (ResultBits - 1 == LeftSize) { |
11210 | S.Diag(Loc, DiagID: diag::warn_shift_result_sets_sign_bit) |
11211 | << HexResult << LHSType |
11212 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11213 | return; |
11214 | } |
11215 | |
11216 | S.Diag(Loc, DiagID: diag::warn_shift_result_gt_typewidth) |
11217 | << HexResult.str() << Result.getSignificantBits() << LHSType |
11218 | << Left.getBitWidth() << LHS.get()->getSourceRange() |
11219 | << RHS.get()->getSourceRange(); |
11220 | } |
11221 | |
11222 | /// Return the resulting type when a vector is shifted |
11223 | /// by a scalar or vector shift amount. |
11224 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, |
11225 | SourceLocation Loc, bool IsCompAssign) { |
11226 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. |
11227 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && |
11228 | !LHS.get()->getType()->isVectorType()) { |
11229 | S.Diag(Loc, DiagID: diag::err_shift_rhs_only_vector) |
11230 | << RHS.get()->getType() << LHS.get()->getType() |
11231 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11232 | return QualType(); |
11233 | } |
11234 | |
11235 | if (!IsCompAssign) { |
11236 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
11237 | if (LHS.isInvalid()) return QualType(); |
11238 | } |
11239 | |
11240 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
11241 | if (RHS.isInvalid()) return QualType(); |
11242 | |
11243 | QualType LHSType = LHS.get()->getType(); |
11244 | // Note that LHS might be a scalar because the routine calls not only in |
11245 | // OpenCL case. |
11246 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); |
11247 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; |
11248 | |
11249 | // Note that RHS might not be a vector. |
11250 | QualType RHSType = RHS.get()->getType(); |
11251 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); |
11252 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; |
11253 | |
11254 | // Do not allow shifts for boolean vectors. |
11255 | if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || |
11256 | (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { |
11257 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
11258 | << LHS.get()->getType() << RHS.get()->getType() |
11259 | << LHS.get()->getSourceRange(); |
11260 | return QualType(); |
11261 | } |
11262 | |
11263 | // The operands need to be integers. |
11264 | if (!LHSEleType->isIntegerType()) { |
11265 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
11266 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
11267 | return QualType(); |
11268 | } |
11269 | |
11270 | if (!RHSEleType->isIntegerType()) { |
11271 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
11272 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
11273 | return QualType(); |
11274 | } |
11275 | |
11276 | if (!LHSVecTy) { |
11277 | assert(RHSVecTy); |
11278 | if (IsCompAssign) |
11279 | return RHSType; |
11280 | if (LHSEleType != RHSEleType) { |
11281 | LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast); |
11282 | LHSEleType = RHSEleType; |
11283 | } |
11284 | QualType VecTy = |
11285 | S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements()); |
11286 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11287 | LHSType = VecTy; |
11288 | } else if (RHSVecTy) { |
11289 | // OpenCL v1.1 s6.3.j says that for vector types, the operators |
11290 | // are applied component-wise. So if RHS is a vector, then ensure |
11291 | // that the number of elements is the same as LHS... |
11292 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { |
11293 | S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
11294 | << LHS.get()->getType() << RHS.get()->getType() |
11295 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11296 | return QualType(); |
11297 | } |
11298 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { |
11299 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); |
11300 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); |
11301 | if (LHSBT != RHSBT && |
11302 | S.Context.getTypeSize(T: LHSBT) != S.Context.getTypeSize(T: RHSBT)) { |
11303 | S.Diag(Loc, DiagID: diag::warn_typecheck_vector_element_sizes_not_equal) |
11304 | << LHS.get()->getType() << RHS.get()->getType() |
11305 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11306 | } |
11307 | } |
11308 | } else { |
11309 | // ...else expand RHS to match the number of elements in LHS. |
11310 | QualType VecTy = |
11311 | S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements()); |
11312 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11313 | } |
11314 | |
11315 | return LHSType; |
11316 | } |
11317 | |
11318 | static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, |
11319 | ExprResult &RHS, SourceLocation Loc, |
11320 | bool IsCompAssign) { |
11321 | if (!IsCompAssign) { |
11322 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
11323 | if (LHS.isInvalid()) |
11324 | return QualType(); |
11325 | } |
11326 | |
11327 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
11328 | if (RHS.isInvalid()) |
11329 | return QualType(); |
11330 | |
11331 | QualType LHSType = LHS.get()->getType(); |
11332 | const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>(); |
11333 | QualType LHSEleType = LHSType->isSveVLSBuiltinType() |
11334 | ? LHSBuiltinTy->getSveEltType(Ctx: S.getASTContext()) |
11335 | : LHSType; |
11336 | |
11337 | // Note that RHS might not be a vector |
11338 | QualType RHSType = RHS.get()->getType(); |
11339 | const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>(); |
11340 | QualType RHSEleType = RHSType->isSveVLSBuiltinType() |
11341 | ? RHSBuiltinTy->getSveEltType(Ctx: S.getASTContext()) |
11342 | : RHSType; |
11343 | |
11344 | if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
11345 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { |
11346 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
11347 | << LHSType << RHSType << LHS.get()->getSourceRange(); |
11348 | return QualType(); |
11349 | } |
11350 | |
11351 | if (!LHSEleType->isIntegerType()) { |
11352 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
11353 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
11354 | return QualType(); |
11355 | } |
11356 | |
11357 | if (!RHSEleType->isIntegerType()) { |
11358 | S.Diag(Loc, DiagID: diag::err_typecheck_expect_int) |
11359 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
11360 | return QualType(); |
11361 | } |
11362 | |
11363 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
11364 | (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
11365 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) { |
11366 | S.Diag(Loc, DiagID: diag::err_typecheck_invalid_operands) |
11367 | << LHSType << RHSType << LHS.get()->getSourceRange() |
11368 | << RHS.get()->getSourceRange(); |
11369 | return QualType(); |
11370 | } |
11371 | |
11372 | if (!LHSType->isSveVLSBuiltinType()) { |
11373 | assert(RHSType->isSveVLSBuiltinType()); |
11374 | if (IsCompAssign) |
11375 | return RHSType; |
11376 | if (LHSEleType != RHSEleType) { |
11377 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast); |
11378 | LHSEleType = RHSEleType; |
11379 | } |
11380 | const llvm::ElementCount VecSize = |
11381 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC; |
11382 | QualType VecTy = |
11383 | S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue()); |
11384 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat); |
11385 | LHSType = VecTy; |
11386 | } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) { |
11387 | if (S.Context.getTypeSize(T: RHSBuiltinTy) != |
11388 | S.Context.getTypeSize(T: LHSBuiltinTy)) { |
11389 | S.Diag(Loc, DiagID: diag::err_typecheck_vector_lengths_not_equal) |
11390 | << LHSType << RHSType << LHS.get()->getSourceRange() |
11391 | << RHS.get()->getSourceRange(); |
11392 | return QualType(); |
11393 | } |
11394 | } else { |
11395 | const llvm::ElementCount VecSize = |
11396 | S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC; |
11397 | if (LHSEleType != RHSEleType) { |
11398 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast); |
11399 | RHSEleType = LHSEleType; |
11400 | } |
11401 | QualType VecTy = |
11402 | S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue()); |
11403 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11404 | } |
11405 | |
11406 | return LHSType; |
11407 | } |
11408 | |
11409 | // C99 6.5.7 |
11410 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, |
11411 | SourceLocation Loc, BinaryOperatorKind Opc, |
11412 | bool IsCompAssign) { |
11413 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
11414 | |
11415 | // Vector shifts promote their scalar inputs to vector type. |
11416 | if (LHS.get()->getType()->isVectorType() || |
11417 | RHS.get()->getType()->isVectorType()) { |
11418 | if (LangOpts.ZVector) { |
11419 | // The shift operators for the z vector extensions work basically |
11420 | // like general shifts, except that neither the LHS nor the RHS is |
11421 | // allowed to be a "vector bool". |
11422 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) |
11423 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
11424 | return InvalidOperands(Loc, LHS, RHS); |
11425 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) |
11426 | if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
11427 | return InvalidOperands(Loc, LHS, RHS); |
11428 | } |
11429 | return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
11430 | } |
11431 | |
11432 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
11433 | RHS.get()->getType()->isSveVLSBuiltinType()) |
11434 | return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
11435 | |
11436 | // Shifts don't perform usual arithmetic conversions, they just do integer |
11437 | // promotions on each operand. C99 6.5.7p3 |
11438 | |
11439 | // For the LHS, do usual unary conversions, but then reset them away |
11440 | // if this is a compound assignment. |
11441 | ExprResult OldLHS = LHS; |
11442 | LHS = UsualUnaryConversions(E: LHS.get()); |
11443 | if (LHS.isInvalid()) |
11444 | return QualType(); |
11445 | QualType LHSType = LHS.get()->getType(); |
11446 | if (IsCompAssign) LHS = OldLHS; |
11447 | |
11448 | // The RHS is simpler. |
11449 | RHS = UsualUnaryConversions(E: RHS.get()); |
11450 | if (RHS.isInvalid()) |
11451 | return QualType(); |
11452 | QualType RHSType = RHS.get()->getType(); |
11453 | |
11454 | // C99 6.5.7p2: Each of the operands shall have integer type. |
11455 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. |
11456 | if ((!LHSType->isFixedPointOrIntegerType() && |
11457 | !LHSType->hasIntegerRepresentation()) || |
11458 | !RHSType->hasIntegerRepresentation()) |
11459 | return InvalidOperands(Loc, LHS, RHS); |
11460 | |
11461 | // C++0x: Don't allow scoped enums. FIXME: Use something better than |
11462 | // hasIntegerRepresentation() above instead of this. |
11463 | if (isScopedEnumerationType(T: LHSType) || |
11464 | isScopedEnumerationType(T: RHSType)) { |
11465 | return InvalidOperands(Loc, LHS, RHS); |
11466 | } |
11467 | DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType); |
11468 | |
11469 | // "The type of the result is that of the promoted left operand." |
11470 | return LHSType; |
11471 | } |
11472 | |
11473 | /// Diagnose bad pointer comparisons. |
11474 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, |
11475 | ExprResult &LHS, ExprResult &RHS, |
11476 | bool IsError) { |
11477 | S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_distinct_pointers |
11478 | : diag::ext_typecheck_comparison_of_distinct_pointers) |
11479 | << LHS.get()->getType() << RHS.get()->getType() |
11480 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11481 | } |
11482 | |
11483 | /// Returns false if the pointers are converted to a composite type, |
11484 | /// true otherwise. |
11485 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, |
11486 | ExprResult &LHS, ExprResult &RHS) { |
11487 | // C++ [expr.rel]p2: |
11488 | // [...] Pointer conversions (4.10) and qualification |
11489 | // conversions (4.4) are performed on pointer operands (or on |
11490 | // a pointer operand and a null pointer constant) to bring |
11491 | // them to their composite pointer type. [...] |
11492 | // |
11493 | // C++ [expr.eq]p1 uses the same notion for (in)equality |
11494 | // comparisons of pointers. |
11495 | |
11496 | QualType LHSType = LHS.get()->getType(); |
11497 | QualType RHSType = RHS.get()->getType(); |
11498 | assert(LHSType->isPointerType() || RHSType->isPointerType() || |
11499 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); |
11500 | |
11501 | QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS); |
11502 | if (T.isNull()) { |
11503 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && |
11504 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) |
11505 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true); |
11506 | else |
11507 | S.InvalidOperands(Loc, LHS, RHS); |
11508 | return true; |
11509 | } |
11510 | |
11511 | return false; |
11512 | } |
11513 | |
11514 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, |
11515 | ExprResult &LHS, |
11516 | ExprResult &RHS, |
11517 | bool IsError) { |
11518 | S.Diag(Loc, DiagID: IsError ? diag::err_typecheck_comparison_of_fptr_to_void |
11519 | : diag::ext_typecheck_comparison_of_fptr_to_void) |
11520 | << LHS.get()->getType() << RHS.get()->getType() |
11521 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11522 | } |
11523 | |
11524 | static bool isObjCObjectLiteral(ExprResult &E) { |
11525 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { |
11526 | case Stmt::ObjCArrayLiteralClass: |
11527 | case Stmt::ObjCDictionaryLiteralClass: |
11528 | case Stmt::ObjCStringLiteralClass: |
11529 | case Stmt::ObjCBoxedExprClass: |
11530 | return true; |
11531 | default: |
11532 | // Note that ObjCBoolLiteral is NOT an object literal! |
11533 | return false; |
11534 | } |
11535 | } |
11536 | |
11537 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { |
11538 | const ObjCObjectPointerType *Type = |
11539 | LHS->getType()->getAs<ObjCObjectPointerType>(); |
11540 | |
11541 | // If this is not actually an Objective-C object, bail out. |
11542 | if (!Type) |
11543 | return false; |
11544 | |
11545 | // Get the LHS object's interface type. |
11546 | QualType InterfaceType = Type->getPointeeType(); |
11547 | |
11548 | // If the RHS isn't an Objective-C object, bail out. |
11549 | if (!RHS->getType()->isObjCObjectPointerType()) |
11550 | return false; |
11551 | |
11552 | // Try to find the -isEqual: method. |
11553 | Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector(); |
11554 | ObjCMethodDecl *Method = |
11555 | S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType, |
11556 | /*IsInstance=*/true); |
11557 | if (!Method) { |
11558 | if (Type->isObjCIdType()) { |
11559 | // For 'id', just check the global pool. |
11560 | Method = |
11561 | S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(), |
11562 | /*receiverId=*/receiverIdOrClass: true); |
11563 | } else { |
11564 | // Check protocols. |
11565 | Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type, |
11566 | /*IsInstance=*/true); |
11567 | } |
11568 | } |
11569 | |
11570 | if (!Method) |
11571 | return false; |
11572 | |
11573 | QualType T = Method->parameters()[0]->getType(); |
11574 | if (!T->isObjCObjectPointerType()) |
11575 | return false; |
11576 | |
11577 | QualType R = Method->getReturnType(); |
11578 | if (!R->isScalarType()) |
11579 | return false; |
11580 | |
11581 | return true; |
11582 | } |
11583 | |
11584 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, |
11585 | ExprResult &LHS, ExprResult &RHS, |
11586 | BinaryOperator::Opcode Opc){ |
11587 | Expr *Literal; |
11588 | Expr *Other; |
11589 | if (isObjCObjectLiteral(E&: LHS)) { |
11590 | Literal = LHS.get(); |
11591 | Other = RHS.get(); |
11592 | } else { |
11593 | Literal = RHS.get(); |
11594 | Other = LHS.get(); |
11595 | } |
11596 | |
11597 | // Don't warn on comparisons against nil. |
11598 | Other = Other->IgnoreParenCasts(); |
11599 | if (Other->isNullPointerConstant(Ctx&: S.getASTContext(), |
11600 | NPC: Expr::NPC_ValueDependentIsNotNull)) |
11601 | return; |
11602 | |
11603 | // This should be kept in sync with warn_objc_literal_comparison. |
11604 | // LK_String should always be after the other literals, since it has its own |
11605 | // warning flag. |
11606 | SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal); |
11607 | assert(LiteralKind != SemaObjC::LK_Block); |
11608 | if (LiteralKind == SemaObjC::LK_None) { |
11609 | llvm_unreachable("Unknown Objective-C object literal kind" ); |
11610 | } |
11611 | |
11612 | if (LiteralKind == SemaObjC::LK_String) |
11613 | S.Diag(Loc, DiagID: diag::warn_objc_string_literal_comparison) |
11614 | << Literal->getSourceRange(); |
11615 | else |
11616 | S.Diag(Loc, DiagID: diag::warn_objc_literal_comparison) |
11617 | << LiteralKind << Literal->getSourceRange(); |
11618 | |
11619 | if (BinaryOperator::isEqualityOp(Opc) && |
11620 | hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) { |
11621 | SourceLocation Start = LHS.get()->getBeginLoc(); |
11622 | SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
11623 | CharSourceRange OpRange = |
11624 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
11625 | |
11626 | S.Diag(Loc, DiagID: diag::note_objc_literal_comparison_isequal) |
11627 | << FixItHint::CreateInsertion(InsertionLoc: Start, Code: Opc == BO_EQ ? "[" : "![" ) |
11628 | << FixItHint::CreateReplacement(RemoveRange: OpRange, Code: " isEqual:" ) |
11629 | << FixItHint::CreateInsertion(InsertionLoc: End, Code: "]" ); |
11630 | } |
11631 | } |
11632 | |
11633 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. |
11634 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, |
11635 | ExprResult &RHS, SourceLocation Loc, |
11636 | BinaryOperatorKind Opc) { |
11637 | // Check that left hand side is !something. |
11638 | UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts()); |
11639 | if (!UO || UO->getOpcode() != UO_LNot) return; |
11640 | |
11641 | // Only check if the right hand side is non-bool arithmetic type. |
11642 | if (RHS.get()->isKnownToHaveBooleanValue()) return; |
11643 | |
11644 | // Make sure that the something in !something is not bool. |
11645 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); |
11646 | if (SubExpr->isKnownToHaveBooleanValue()) return; |
11647 | |
11648 | // Emit warning. |
11649 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; |
11650 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::warn_logical_not_on_lhs_of_check) |
11651 | << Loc << IsBitwiseOp; |
11652 | |
11653 | // First note suggest !(x < y) |
11654 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); |
11655 | SourceLocation FirstClose = RHS.get()->getEndLoc(); |
11656 | FirstClose = S.getLocForEndOfToken(Loc: FirstClose); |
11657 | if (FirstClose.isInvalid()) |
11658 | FirstOpen = SourceLocation(); |
11659 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_fix) |
11660 | << IsBitwiseOp |
11661 | << FixItHint::CreateInsertion(InsertionLoc: FirstOpen, Code: "(" ) |
11662 | << FixItHint::CreateInsertion(InsertionLoc: FirstClose, Code: ")" ); |
11663 | |
11664 | // Second note suggests (!x) < y |
11665 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); |
11666 | SourceLocation SecondClose = LHS.get()->getEndLoc(); |
11667 | SecondClose = S.getLocForEndOfToken(Loc: SecondClose); |
11668 | if (SecondClose.isInvalid()) |
11669 | SecondOpen = SourceLocation(); |
11670 | S.Diag(Loc: UO->getOperatorLoc(), DiagID: diag::note_logical_not_silence_with_parens) |
11671 | << FixItHint::CreateInsertion(InsertionLoc: SecondOpen, Code: "(" ) |
11672 | << FixItHint::CreateInsertion(InsertionLoc: SecondClose, Code: ")" ); |
11673 | } |
11674 | |
11675 | // Returns true if E refers to a non-weak array. |
11676 | static bool checkForArray(const Expr *E) { |
11677 | const ValueDecl *D = nullptr; |
11678 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) { |
11679 | D = DR->getDecl(); |
11680 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) { |
11681 | if (Mem->isImplicitAccess()) |
11682 | D = Mem->getMemberDecl(); |
11683 | } |
11684 | if (!D) |
11685 | return false; |
11686 | return D->getType()->isArrayType() && !D->isWeak(); |
11687 | } |
11688 | |
11689 | /// Diagnose some forms of syntactically-obvious tautological comparison. |
11690 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, |
11691 | Expr *LHS, Expr *RHS, |
11692 | BinaryOperatorKind Opc) { |
11693 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); |
11694 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); |
11695 | |
11696 | QualType LHSType = LHS->getType(); |
11697 | QualType RHSType = RHS->getType(); |
11698 | if (LHSType->hasFloatingRepresentation() || |
11699 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || |
11700 | S.inTemplateInstantiation()) |
11701 | return; |
11702 | |
11703 | // WebAssembly Tables cannot be compared, therefore shouldn't emit |
11704 | // Tautological diagnostics. |
11705 | if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType()) |
11706 | return; |
11707 | |
11708 | // Comparisons between two array types are ill-formed for operator<=>, so |
11709 | // we shouldn't emit any additional warnings about it. |
11710 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) |
11711 | return; |
11712 | |
11713 | // For non-floating point types, check for self-comparisons of the form |
11714 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
11715 | // often indicate logic errors in the program. |
11716 | // |
11717 | // NOTE: Don't warn about comparison expressions resulting from macro |
11718 | // expansion. Also don't warn about comparisons which are only self |
11719 | // comparisons within a template instantiation. The warnings should catch |
11720 | // obvious cases in the definition of the template anyways. The idea is to |
11721 | // warn when the typed comparison operator will always evaluate to the same |
11722 | // result. |
11723 | |
11724 | // Used for indexing into %select in warn_comparison_always |
11725 | enum { |
11726 | AlwaysConstant, |
11727 | AlwaysTrue, |
11728 | AlwaysFalse, |
11729 | AlwaysEqual, // std::strong_ordering::equal from operator<=> |
11730 | }; |
11731 | |
11732 | // C++2a [depr.array.comp]: |
11733 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two |
11734 | // operands of array type are deprecated. |
11735 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && |
11736 | RHSStripped->getType()->isArrayType()) { |
11737 | S.Diag(Loc, DiagID: diag::warn_depr_array_comparison) |
11738 | << LHS->getSourceRange() << RHS->getSourceRange() |
11739 | << LHSStripped->getType() << RHSStripped->getType(); |
11740 | // Carry on to produce the tautological comparison warning, if this |
11741 | // expression is potentially-evaluated, we can resolve the array to a |
11742 | // non-weak declaration, and so on. |
11743 | } |
11744 | |
11745 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { |
11746 | if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) { |
11747 | unsigned Result; |
11748 | switch (Opc) { |
11749 | case BO_EQ: |
11750 | case BO_LE: |
11751 | case BO_GE: |
11752 | Result = AlwaysTrue; |
11753 | break; |
11754 | case BO_NE: |
11755 | case BO_LT: |
11756 | case BO_GT: |
11757 | Result = AlwaysFalse; |
11758 | break; |
11759 | case BO_Cmp: |
11760 | Result = AlwaysEqual; |
11761 | break; |
11762 | default: |
11763 | Result = AlwaysConstant; |
11764 | break; |
11765 | } |
11766 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
11767 | PD: S.PDiag(DiagID: diag::warn_comparison_always) |
11768 | << 0 /*self-comparison*/ |
11769 | << Result); |
11770 | } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) { |
11771 | // What is it always going to evaluate to? |
11772 | unsigned Result; |
11773 | switch (Opc) { |
11774 | case BO_EQ: // e.g. array1 == array2 |
11775 | Result = AlwaysFalse; |
11776 | break; |
11777 | case BO_NE: // e.g. array1 != array2 |
11778 | Result = AlwaysTrue; |
11779 | break; |
11780 | default: // e.g. array1 <= array2 |
11781 | // The best we can say is 'a constant' |
11782 | Result = AlwaysConstant; |
11783 | break; |
11784 | } |
11785 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
11786 | PD: S.PDiag(DiagID: diag::warn_comparison_always) |
11787 | << 1 /*array comparison*/ |
11788 | << Result); |
11789 | } |
11790 | } |
11791 | |
11792 | if (isa<CastExpr>(Val: LHSStripped)) |
11793 | LHSStripped = LHSStripped->IgnoreParenCasts(); |
11794 | if (isa<CastExpr>(Val: RHSStripped)) |
11795 | RHSStripped = RHSStripped->IgnoreParenCasts(); |
11796 | |
11797 | // Warn about comparisons against a string constant (unless the other |
11798 | // operand is null); the user probably wants string comparison function. |
11799 | Expr *LiteralString = nullptr; |
11800 | Expr *LiteralStringStripped = nullptr; |
11801 | if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) && |
11802 | !RHSStripped->isNullPointerConstant(Ctx&: S.Context, |
11803 | NPC: Expr::NPC_ValueDependentIsNull)) { |
11804 | LiteralString = LHS; |
11805 | LiteralStringStripped = LHSStripped; |
11806 | } else if ((isa<StringLiteral>(Val: RHSStripped) || |
11807 | isa<ObjCEncodeExpr>(Val: RHSStripped)) && |
11808 | !LHSStripped->isNullPointerConstant(Ctx&: S.Context, |
11809 | NPC: Expr::NPC_ValueDependentIsNull)) { |
11810 | LiteralString = RHS; |
11811 | LiteralStringStripped = RHSStripped; |
11812 | } |
11813 | |
11814 | if (LiteralString) { |
11815 | S.DiagRuntimeBehavior(Loc, Statement: nullptr, |
11816 | PD: S.PDiag(DiagID: diag::warn_stringcompare) |
11817 | << isa<ObjCEncodeExpr>(Val: LiteralStringStripped) |
11818 | << LiteralString->getSourceRange()); |
11819 | } |
11820 | } |
11821 | |
11822 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { |
11823 | switch (CK) { |
11824 | default: { |
11825 | #ifndef NDEBUG |
11826 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) |
11827 | << "\n" ; |
11828 | #endif |
11829 | llvm_unreachable("unhandled cast kind" ); |
11830 | } |
11831 | case CK_UserDefinedConversion: |
11832 | return ICK_Identity; |
11833 | case CK_LValueToRValue: |
11834 | return ICK_Lvalue_To_Rvalue; |
11835 | case CK_ArrayToPointerDecay: |
11836 | return ICK_Array_To_Pointer; |
11837 | case CK_FunctionToPointerDecay: |
11838 | return ICK_Function_To_Pointer; |
11839 | case CK_IntegralCast: |
11840 | return ICK_Integral_Conversion; |
11841 | case CK_FloatingCast: |
11842 | return ICK_Floating_Conversion; |
11843 | case CK_IntegralToFloating: |
11844 | case CK_FloatingToIntegral: |
11845 | return ICK_Floating_Integral; |
11846 | case CK_IntegralComplexCast: |
11847 | case CK_FloatingComplexCast: |
11848 | case CK_FloatingComplexToIntegralComplex: |
11849 | case CK_IntegralComplexToFloatingComplex: |
11850 | return ICK_Complex_Conversion; |
11851 | case CK_FloatingComplexToReal: |
11852 | case CK_FloatingRealToComplex: |
11853 | case CK_IntegralComplexToReal: |
11854 | case CK_IntegralRealToComplex: |
11855 | return ICK_Complex_Real; |
11856 | case CK_HLSLArrayRValue: |
11857 | return ICK_HLSL_Array_RValue; |
11858 | } |
11859 | } |
11860 | |
11861 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, |
11862 | QualType FromType, |
11863 | SourceLocation Loc) { |
11864 | // Check for a narrowing implicit conversion. |
11865 | StandardConversionSequence SCS; |
11866 | SCS.setAsIdentityConversion(); |
11867 | SCS.setToType(Idx: 0, T: FromType); |
11868 | SCS.setToType(Idx: 1, T: ToType); |
11869 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
11870 | SCS.Second = castKindToImplicitConversionKind(CK: ICE->getCastKind()); |
11871 | |
11872 | APValue PreNarrowingValue; |
11873 | QualType PreNarrowingType; |
11874 | switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue, |
11875 | ConstantType&: PreNarrowingType, |
11876 | /*IgnoreFloatToIntegralConversion*/ true)) { |
11877 | case NK_Dependent_Narrowing: |
11878 | // Implicit conversion to a narrower type, but the expression is |
11879 | // value-dependent so we can't tell whether it's actually narrowing. |
11880 | case NK_Not_Narrowing: |
11881 | return false; |
11882 | |
11883 | case NK_Constant_Narrowing: |
11884 | // Implicit conversion to a narrower type, and the value is not a constant |
11885 | // expression. |
11886 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing) |
11887 | << /*Constant*/ 1 |
11888 | << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType; |
11889 | return true; |
11890 | |
11891 | case NK_Variable_Narrowing: |
11892 | // Implicit conversion to a narrower type, and the value is not a constant |
11893 | // expression. |
11894 | case NK_Type_Narrowing: |
11895 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_spaceship_argument_narrowing) |
11896 | << /*Constant*/ 0 << FromType << ToType; |
11897 | // TODO: It's not a constant expression, but what if the user intended it |
11898 | // to be? Can we produce notes to help them figure out why it isn't? |
11899 | return true; |
11900 | } |
11901 | llvm_unreachable("unhandled case in switch" ); |
11902 | } |
11903 | |
11904 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, |
11905 | ExprResult &LHS, |
11906 | ExprResult &RHS, |
11907 | SourceLocation Loc) { |
11908 | QualType LHSType = LHS.get()->getType(); |
11909 | QualType RHSType = RHS.get()->getType(); |
11910 | // Dig out the original argument type and expression before implicit casts |
11911 | // were applied. These are the types/expressions we need to check the |
11912 | // [expr.spaceship] requirements against. |
11913 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); |
11914 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); |
11915 | QualType LHSStrippedType = LHSStripped.get()->getType(); |
11916 | QualType RHSStrippedType = RHSStripped.get()->getType(); |
11917 | |
11918 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the |
11919 | // other is not, the program is ill-formed. |
11920 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { |
11921 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
11922 | return QualType(); |
11923 | } |
11924 | |
11925 | // FIXME: Consider combining this with checkEnumArithmeticConversions. |
11926 | int = (int)LHSStrippedType->isEnumeralType() + |
11927 | RHSStrippedType->isEnumeralType(); |
11928 | if (NumEnumArgs == 1) { |
11929 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); |
11930 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; |
11931 | if (OtherTy->hasFloatingRepresentation()) { |
11932 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
11933 | return QualType(); |
11934 | } |
11935 | } |
11936 | if (NumEnumArgs == 2) { |
11937 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration |
11938 | // type E, the operator yields the result of converting the operands |
11939 | // to the underlying type of E and applying <=> to the converted operands. |
11940 | if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) { |
11941 | S.InvalidOperands(Loc, LHS, RHS); |
11942 | return QualType(); |
11943 | } |
11944 | QualType IntType = |
11945 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); |
11946 | assert(IntType->isArithmeticType()); |
11947 | |
11948 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we |
11949 | // promote the boolean type, and all other promotable integer types, to |
11950 | // avoid this. |
11951 | if (S.Context.isPromotableIntegerType(T: IntType)) |
11952 | IntType = S.Context.getPromotedIntegerType(PromotableType: IntType); |
11953 | |
11954 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast); |
11955 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast); |
11956 | LHSType = RHSType = IntType; |
11957 | } |
11958 | |
11959 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the |
11960 | // usual arithmetic conversions are applied to the operands. |
11961 | QualType Type = |
11962 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison); |
11963 | if (LHS.isInvalid() || RHS.isInvalid()) |
11964 | return QualType(); |
11965 | if (Type.isNull()) |
11966 | return S.InvalidOperands(Loc, LHS, RHS); |
11967 | |
11968 | std::optional<ComparisonCategoryType> CCT = |
11969 | getComparisonCategoryForBuiltinCmp(T: Type); |
11970 | if (!CCT) |
11971 | return S.InvalidOperands(Loc, LHS, RHS); |
11972 | |
11973 | bool HasNarrowing = checkThreeWayNarrowingConversion( |
11974 | S, ToType: Type, E: LHS.get(), FromType: LHSType, Loc: LHS.get()->getBeginLoc()); |
11975 | HasNarrowing |= checkThreeWayNarrowingConversion(S, ToType: Type, E: RHS.get(), FromType: RHSType, |
11976 | Loc: RHS.get()->getBeginLoc()); |
11977 | if (HasNarrowing) |
11978 | return QualType(); |
11979 | |
11980 | assert(!Type.isNull() && "composite type for <=> has not been set" ); |
11981 | |
11982 | return S.CheckComparisonCategoryType( |
11983 | Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression); |
11984 | } |
11985 | |
11986 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, |
11987 | ExprResult &RHS, |
11988 | SourceLocation Loc, |
11989 | BinaryOperatorKind Opc) { |
11990 | if (Opc == BO_Cmp) |
11991 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); |
11992 | |
11993 | // C99 6.5.8p3 / C99 6.5.9p4 |
11994 | QualType Type = |
11995 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison); |
11996 | if (LHS.isInvalid() || RHS.isInvalid()) |
11997 | return QualType(); |
11998 | if (Type.isNull()) |
11999 | return S.InvalidOperands(Loc, LHS, RHS); |
12000 | assert(Type->isArithmeticType() || Type->isEnumeralType()); |
12001 | |
12002 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) |
12003 | return S.InvalidOperands(Loc, LHS, RHS); |
12004 | |
12005 | // Check for comparisons of floating point operands using != and ==. |
12006 | if (Type->hasFloatingRepresentation()) |
12007 | S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
12008 | |
12009 | // The result of comparisons is 'bool' in C++, 'int' in C. |
12010 | return S.Context.getLogicalOperationType(); |
12011 | } |
12012 | |
12013 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { |
12014 | if (!NullE.get()->getType()->isAnyPointerType()) |
12015 | return; |
12016 | int NullValue = PP.isMacroDefined(Id: "NULL" ) ? 0 : 1; |
12017 | if (!E.get()->getType()->isAnyPointerType() && |
12018 | E.get()->isNullPointerConstant(Ctx&: Context, |
12019 | NPC: Expr::NPC_ValueDependentIsNotNull) == |
12020 | Expr::NPCK_ZeroExpression) { |
12021 | if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) { |
12022 | if (CL->getValue() == 0) |
12023 | Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare) |
12024 | << NullValue |
12025 | << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(), |
12026 | Code: NullValue ? "NULL" : "(void *)0" ); |
12027 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) { |
12028 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); |
12029 | QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType(); |
12030 | if (T == Context.CharTy) |
12031 | Diag(Loc: E.get()->getExprLoc(), DiagID: diag::warn_pointer_compare) |
12032 | << NullValue |
12033 | << FixItHint::CreateReplacement(RemoveRange: E.get()->getExprLoc(), |
12034 | Code: NullValue ? "NULL" : "(void *)0" ); |
12035 | } |
12036 | } |
12037 | } |
12038 | |
12039 | // C99 6.5.8, C++ [expr.rel] |
12040 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, |
12041 | SourceLocation Loc, |
12042 | BinaryOperatorKind Opc) { |
12043 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); |
12044 | bool IsThreeWay = Opc == BO_Cmp; |
12045 | bool IsOrdered = IsRelational || IsThreeWay; |
12046 | auto IsAnyPointerType = [](ExprResult E) { |
12047 | QualType Ty = E.get()->getType(); |
12048 | return Ty->isPointerType() || Ty->isMemberPointerType(); |
12049 | }; |
12050 | |
12051 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer |
12052 | // type, array-to-pointer, ..., conversions are performed on both operands to |
12053 | // bring them to their composite type. |
12054 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before |
12055 | // any type-related checks. |
12056 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { |
12057 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
12058 | if (LHS.isInvalid()) |
12059 | return QualType(); |
12060 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
12061 | if (RHS.isInvalid()) |
12062 | return QualType(); |
12063 | } else { |
12064 | LHS = DefaultLvalueConversion(E: LHS.get()); |
12065 | if (LHS.isInvalid()) |
12066 | return QualType(); |
12067 | RHS = DefaultLvalueConversion(E: RHS.get()); |
12068 | if (RHS.isInvalid()) |
12069 | return QualType(); |
12070 | } |
12071 | |
12072 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true); |
12073 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { |
12074 | CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS); |
12075 | CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS); |
12076 | } |
12077 | |
12078 | // Handle vector comparisons separately. |
12079 | if (LHS.get()->getType()->isVectorType() || |
12080 | RHS.get()->getType()->isVectorType()) |
12081 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); |
12082 | |
12083 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
12084 | RHS.get()->getType()->isSveVLSBuiltinType()) |
12085 | return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); |
12086 | |
12087 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
12088 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
12089 | |
12090 | QualType LHSType = LHS.get()->getType(); |
12091 | QualType RHSType = RHS.get()->getType(); |
12092 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && |
12093 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) |
12094 | return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc); |
12095 | |
12096 | if ((LHSType->isPointerType() && |
12097 | LHSType->getPointeeType().isWebAssemblyReferenceType()) || |
12098 | (RHSType->isPointerType() && |
12099 | RHSType->getPointeeType().isWebAssemblyReferenceType())) |
12100 | return InvalidOperands(Loc, LHS, RHS); |
12101 | |
12102 | const Expr::NullPointerConstantKind LHSNullKind = |
12103 | LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
12104 | const Expr::NullPointerConstantKind RHSNullKind = |
12105 | RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
12106 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; |
12107 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
12108 | |
12109 | auto computeResultTy = [&]() { |
12110 | if (Opc != BO_Cmp) |
12111 | return Context.getLogicalOperationType(); |
12112 | assert(getLangOpts().CPlusPlus); |
12113 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); |
12114 | |
12115 | QualType CompositeTy = LHS.get()->getType(); |
12116 | assert(!CompositeTy->isReferenceType()); |
12117 | |
12118 | std::optional<ComparisonCategoryType> CCT = |
12119 | getComparisonCategoryForBuiltinCmp(T: CompositeTy); |
12120 | if (!CCT) |
12121 | return InvalidOperands(Loc, LHS, RHS); |
12122 | |
12123 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { |
12124 | // P0946R0: Comparisons between a null pointer constant and an object |
12125 | // pointer result in std::strong_equality, which is ill-formed under |
12126 | // P1959R0. |
12127 | Diag(Loc, DiagID: diag::err_typecheck_three_way_comparison_of_pointer_and_zero) |
12128 | << (LHSIsNull ? LHS.get()->getSourceRange() |
12129 | : RHS.get()->getSourceRange()); |
12130 | return QualType(); |
12131 | } |
12132 | |
12133 | return CheckComparisonCategoryType( |
12134 | Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression); |
12135 | }; |
12136 | |
12137 | if (!IsOrdered && LHSIsNull != RHSIsNull) { |
12138 | bool IsEquality = Opc == BO_EQ; |
12139 | if (RHSIsNull) |
12140 | DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality, |
12141 | Range: RHS.get()->getSourceRange()); |
12142 | else |
12143 | DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality, |
12144 | Range: LHS.get()->getSourceRange()); |
12145 | } |
12146 | |
12147 | if (IsOrdered && LHSType->isFunctionPointerType() && |
12148 | RHSType->isFunctionPointerType()) { |
12149 | // Valid unless a relational comparison of function pointers |
12150 | bool IsError = Opc == BO_Cmp; |
12151 | auto DiagID = |
12152 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers |
12153 | : getLangOpts().CPlusPlus |
12154 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers |
12155 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; |
12156 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
12157 | << RHS.get()->getSourceRange(); |
12158 | if (IsError) |
12159 | return QualType(); |
12160 | } |
12161 | |
12162 | if ((LHSType->isIntegerType() && !LHSIsNull) || |
12163 | (RHSType->isIntegerType() && !RHSIsNull)) { |
12164 | // Skip normal pointer conversion checks in this case; we have better |
12165 | // diagnostics for this below. |
12166 | } else if (getLangOpts().CPlusPlus) { |
12167 | // Equality comparison of a function pointer to a void pointer is invalid, |
12168 | // but we allow it as an extension. |
12169 | // FIXME: If we really want to allow this, should it be part of composite |
12170 | // pointer type computation so it works in conditionals too? |
12171 | if (!IsOrdered && |
12172 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || |
12173 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { |
12174 | // This is a gcc extension compatibility comparison. |
12175 | // In a SFINAE context, we treat this as a hard error to maintain |
12176 | // conformance with the C++ standard. |
12177 | diagnoseFunctionPointerToVoidComparison( |
12178 | S&: *this, Loc, LHS, RHS, /*isError*/ IsError: (bool)isSFINAEContext()); |
12179 | |
12180 | if (isSFINAEContext()) |
12181 | return QualType(); |
12182 | |
12183 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12184 | return computeResultTy(); |
12185 | } |
12186 | |
12187 | // C++ [expr.eq]p2: |
12188 | // If at least one operand is a pointer [...] bring them to their |
12189 | // composite pointer type. |
12190 | // C++ [expr.spaceship]p6 |
12191 | // If at least one of the operands is of pointer type, [...] bring them |
12192 | // to their composite pointer type. |
12193 | // C++ [expr.rel]p2: |
12194 | // If both operands are pointers, [...] bring them to their composite |
12195 | // pointer type. |
12196 | // For <=>, the only valid non-pointer types are arrays and functions, and |
12197 | // we already decayed those, so this is really the same as the relational |
12198 | // comparison rule. |
12199 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= |
12200 | (IsOrdered ? 2 : 1) && |
12201 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || |
12202 | RHSType->isObjCObjectPointerType()))) { |
12203 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
12204 | return QualType(); |
12205 | return computeResultTy(); |
12206 | } |
12207 | } else if (LHSType->isPointerType() && |
12208 | RHSType->isPointerType()) { // C99 6.5.8p2 |
12209 | // All of the following pointer-related warnings are GCC extensions, except |
12210 | // when handling null pointer constants. |
12211 | QualType LCanPointeeTy = |
12212 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
12213 | QualType RCanPointeeTy = |
12214 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
12215 | |
12216 | // C99 6.5.9p2 and C99 6.5.8p2 |
12217 | if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(), |
12218 | T2: RCanPointeeTy.getUnqualifiedType())) { |
12219 | if (IsRelational) { |
12220 | // Pointers both need to point to complete or incomplete types |
12221 | if ((LCanPointeeTy->isIncompleteType() != |
12222 | RCanPointeeTy->isIncompleteType()) && |
12223 | !getLangOpts().C11) { |
12224 | Diag(Loc, DiagID: diag::ext_typecheck_compare_complete_incomplete_pointers) |
12225 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() |
12226 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() |
12227 | << RCanPointeeTy->isIncompleteType(); |
12228 | } |
12229 | } |
12230 | } else if (!IsRelational && |
12231 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { |
12232 | // Valid unless comparison between non-null pointer and function pointer |
12233 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) |
12234 | && !LHSIsNull && !RHSIsNull) |
12235 | diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, |
12236 | /*isError*/IsError: false); |
12237 | } else { |
12238 | // Invalid |
12239 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false); |
12240 | } |
12241 | if (LCanPointeeTy != RCanPointeeTy) { |
12242 | // Treat NULL constant as a special case in OpenCL. |
12243 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { |
12244 | if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy)) { |
12245 | Diag(Loc, |
12246 | DiagID: diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
12247 | << LHSType << RHSType << 0 /* comparison */ |
12248 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
12249 | } |
12250 | } |
12251 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); |
12252 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); |
12253 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion |
12254 | : CK_BitCast; |
12255 | if (LHSIsNull && !RHSIsNull) |
12256 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind); |
12257 | else |
12258 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind); |
12259 | } |
12260 | return computeResultTy(); |
12261 | } |
12262 | |
12263 | |
12264 | // C++ [expr.eq]p4: |
12265 | // Two operands of type std::nullptr_t or one operand of type |
12266 | // std::nullptr_t and the other a null pointer constant compare |
12267 | // equal. |
12268 | // C23 6.5.9p5: |
12269 | // If both operands have type nullptr_t or one operand has type nullptr_t |
12270 | // and the other is a null pointer constant, they compare equal if the |
12271 | // former is a null pointer. |
12272 | if (!IsOrdered && LHSIsNull && RHSIsNull) { |
12273 | if (LHSType->isNullPtrType()) { |
12274 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12275 | return computeResultTy(); |
12276 | } |
12277 | if (RHSType->isNullPtrType()) { |
12278 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12279 | return computeResultTy(); |
12280 | } |
12281 | } |
12282 | |
12283 | if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { |
12284 | // C23 6.5.9p6: |
12285 | // Otherwise, at least one operand is a pointer. If one is a pointer and |
12286 | // the other is a null pointer constant or has type nullptr_t, they |
12287 | // compare equal |
12288 | if (LHSIsNull && RHSType->isPointerType()) { |
12289 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12290 | return computeResultTy(); |
12291 | } |
12292 | if (RHSIsNull && LHSType->isPointerType()) { |
12293 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12294 | return computeResultTy(); |
12295 | } |
12296 | } |
12297 | |
12298 | // Comparison of Objective-C pointers and block pointers against nullptr_t. |
12299 | // These aren't covered by the composite pointer type rules. |
12300 | if (!IsOrdered && RHSType->isNullPtrType() && |
12301 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { |
12302 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12303 | return computeResultTy(); |
12304 | } |
12305 | if (!IsOrdered && LHSType->isNullPtrType() && |
12306 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { |
12307 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12308 | return computeResultTy(); |
12309 | } |
12310 | |
12311 | if (getLangOpts().CPlusPlus) { |
12312 | if (IsRelational && |
12313 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || |
12314 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { |
12315 | // HACK: Relational comparison of nullptr_t against a pointer type is |
12316 | // invalid per DR583, but we allow it within std::less<> and friends, |
12317 | // since otherwise common uses of it break. |
12318 | // FIXME: Consider removing this hack once LWG fixes std::less<> and |
12319 | // friends to have std::nullptr_t overload candidates. |
12320 | DeclContext *DC = CurContext; |
12321 | if (isa<FunctionDecl>(Val: DC)) |
12322 | DC = DC->getParent(); |
12323 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) { |
12324 | if (CTSD->isInStdNamespace() && |
12325 | llvm::StringSwitch<bool>(CTSD->getName()) |
12326 | .Cases(S0: "less" , S1: "less_equal" , S2: "greater" , S3: "greater_equal" , Value: true) |
12327 | .Default(Value: false)) { |
12328 | if (RHSType->isNullPtrType()) |
12329 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12330 | else |
12331 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12332 | return computeResultTy(); |
12333 | } |
12334 | } |
12335 | } |
12336 | |
12337 | // C++ [expr.eq]p2: |
12338 | // If at least one operand is a pointer to member, [...] bring them to |
12339 | // their composite pointer type. |
12340 | if (!IsOrdered && |
12341 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { |
12342 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
12343 | return QualType(); |
12344 | else |
12345 | return computeResultTy(); |
12346 | } |
12347 | } |
12348 | |
12349 | // Handle block pointer types. |
12350 | if (!IsOrdered && LHSType->isBlockPointerType() && |
12351 | RHSType->isBlockPointerType()) { |
12352 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); |
12353 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); |
12354 | |
12355 | if (!LHSIsNull && !RHSIsNull && |
12356 | !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) { |
12357 | Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks) |
12358 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12359 | << RHS.get()->getSourceRange(); |
12360 | } |
12361 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12362 | return computeResultTy(); |
12363 | } |
12364 | |
12365 | // Allow block pointers to be compared with null pointer constants. |
12366 | if (!IsOrdered |
12367 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) |
12368 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { |
12369 | if (!LHSIsNull && !RHSIsNull) { |
12370 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() |
12371 | ->getPointeeType()->isVoidType()) |
12372 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() |
12373 | ->getPointeeType()->isVoidType()))) |
12374 | Diag(Loc, DiagID: diag::err_typecheck_comparison_of_distinct_blocks) |
12375 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12376 | << RHS.get()->getSourceRange(); |
12377 | } |
12378 | if (LHSIsNull && !RHSIsNull) |
12379 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12380 | CK: RHSType->isPointerType() ? CK_BitCast |
12381 | : CK_AnyPointerToBlockPointerCast); |
12382 | else |
12383 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12384 | CK: LHSType->isPointerType() ? CK_BitCast |
12385 | : CK_AnyPointerToBlockPointerCast); |
12386 | return computeResultTy(); |
12387 | } |
12388 | |
12389 | if (LHSType->isObjCObjectPointerType() || |
12390 | RHSType->isObjCObjectPointerType()) { |
12391 | const PointerType *LPT = LHSType->getAs<PointerType>(); |
12392 | const PointerType *RPT = RHSType->getAs<PointerType>(); |
12393 | if (LPT || RPT) { |
12394 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; |
12395 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; |
12396 | |
12397 | if (!LPtrToVoid && !RPtrToVoid && |
12398 | !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
12399 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
12400 | /*isError*/IsError: false); |
12401 | } |
12402 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than |
12403 | // the RHS, but we have test coverage for this behavior. |
12404 | // FIXME: Consider using convertPointersToCompositeType in C++. |
12405 | if (LHSIsNull && !RHSIsNull) { |
12406 | Expr *E = LHS.get(); |
12407 | if (getLangOpts().ObjCAutoRefCount) |
12408 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E, |
12409 | CCK: CheckedConversionKind::Implicit); |
12410 | LHS = ImpCastExprToType(E, Type: RHSType, |
12411 | CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
12412 | } |
12413 | else { |
12414 | Expr *E = RHS.get(); |
12415 | if (getLangOpts().ObjCAutoRefCount) |
12416 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E, |
12417 | CCK: CheckedConversionKind::Implicit, |
12418 | /*Diagnose=*/true, |
12419 | /*DiagnoseCFAudited=*/false, Opc); |
12420 | RHS = ImpCastExprToType(E, Type: LHSType, |
12421 | CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
12422 | } |
12423 | return computeResultTy(); |
12424 | } |
12425 | if (LHSType->isObjCObjectPointerType() && |
12426 | RHSType->isObjCObjectPointerType()) { |
12427 | if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType)) |
12428 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
12429 | /*isError*/IsError: false); |
12430 | if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS)) |
12431 | diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc); |
12432 | |
12433 | if (LHSIsNull && !RHSIsNull) |
12434 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
12435 | else |
12436 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12437 | return computeResultTy(); |
12438 | } |
12439 | |
12440 | if (!IsOrdered && LHSType->isBlockPointerType() && |
12441 | RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
12442 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12443 | CK: CK_BlockPointerToObjCPointerCast); |
12444 | return computeResultTy(); |
12445 | } else if (!IsOrdered && |
12446 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) && |
12447 | RHSType->isBlockPointerType()) { |
12448 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12449 | CK: CK_BlockPointerToObjCPointerCast); |
12450 | return computeResultTy(); |
12451 | } |
12452 | } |
12453 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || |
12454 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { |
12455 | unsigned DiagID = 0; |
12456 | bool isError = false; |
12457 | if (LangOpts.DebuggerSupport) { |
12458 | // Under a debugger, allow the comparison of pointers to integers, |
12459 | // since users tend to want to compare addresses. |
12460 | } else if ((LHSIsNull && LHSType->isIntegerType()) || |
12461 | (RHSIsNull && RHSType->isIntegerType())) { |
12462 | if (IsOrdered) { |
12463 | isError = getLangOpts().CPlusPlus; |
12464 | DiagID = |
12465 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero |
12466 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; |
12467 | } |
12468 | } else if (getLangOpts().CPlusPlus) { |
12469 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; |
12470 | isError = true; |
12471 | } else if (IsOrdered) |
12472 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; |
12473 | else |
12474 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; |
12475 | |
12476 | if (DiagID) { |
12477 | Diag(Loc, DiagID) |
12478 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12479 | << RHS.get()->getSourceRange(); |
12480 | if (isError) |
12481 | return QualType(); |
12482 | } |
12483 | |
12484 | if (LHSType->isIntegerType()) |
12485 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12486 | CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
12487 | else |
12488 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12489 | CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
12490 | return computeResultTy(); |
12491 | } |
12492 | |
12493 | // Handle block pointers. |
12494 | if (!IsOrdered && RHSIsNull |
12495 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { |
12496 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12497 | return computeResultTy(); |
12498 | } |
12499 | if (!IsOrdered && LHSIsNull |
12500 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { |
12501 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12502 | return computeResultTy(); |
12503 | } |
12504 | |
12505 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { |
12506 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { |
12507 | return computeResultTy(); |
12508 | } |
12509 | |
12510 | if (LHSType->isQueueT() && RHSType->isQueueT()) { |
12511 | return computeResultTy(); |
12512 | } |
12513 | |
12514 | if (LHSIsNull && RHSType->isQueueT()) { |
12515 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12516 | return computeResultTy(); |
12517 | } |
12518 | |
12519 | if (LHSType->isQueueT() && RHSIsNull) { |
12520 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12521 | return computeResultTy(); |
12522 | } |
12523 | } |
12524 | |
12525 | return InvalidOperands(Loc, LHS, RHS); |
12526 | } |
12527 | |
12528 | QualType Sema::GetSignedVectorType(QualType V) { |
12529 | const VectorType *VTy = V->castAs<VectorType>(); |
12530 | unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType()); |
12531 | |
12532 | if (isa<ExtVectorType>(Val: VTy)) { |
12533 | if (VTy->isExtVectorBoolType()) |
12534 | return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements()); |
12535 | if (TypeSize == Context.getTypeSize(T: Context.CharTy)) |
12536 | return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements()); |
12537 | if (TypeSize == Context.getTypeSize(T: Context.ShortTy)) |
12538 | return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements()); |
12539 | if (TypeSize == Context.getTypeSize(T: Context.IntTy)) |
12540 | return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements()); |
12541 | if (TypeSize == Context.getTypeSize(T: Context.Int128Ty)) |
12542 | return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements()); |
12543 | if (TypeSize == Context.getTypeSize(T: Context.LongTy)) |
12544 | return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements()); |
12545 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && |
12546 | "Unhandled vector element size in vector compare" ); |
12547 | return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements()); |
12548 | } |
12549 | |
12550 | if (TypeSize == Context.getTypeSize(T: Context.Int128Ty)) |
12551 | return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(), |
12552 | VecKind: VectorKind::Generic); |
12553 | if (TypeSize == Context.getTypeSize(T: Context.LongLongTy)) |
12554 | return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(), |
12555 | VecKind: VectorKind::Generic); |
12556 | if (TypeSize == Context.getTypeSize(T: Context.LongTy)) |
12557 | return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(), |
12558 | VecKind: VectorKind::Generic); |
12559 | if (TypeSize == Context.getTypeSize(T: Context.IntTy)) |
12560 | return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(), |
12561 | VecKind: VectorKind::Generic); |
12562 | if (TypeSize == Context.getTypeSize(T: Context.ShortTy)) |
12563 | return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(), |
12564 | VecKind: VectorKind::Generic); |
12565 | assert(TypeSize == Context.getTypeSize(Context.CharTy) && |
12566 | "Unhandled vector element size in vector compare" ); |
12567 | return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(), |
12568 | VecKind: VectorKind::Generic); |
12569 | } |
12570 | |
12571 | QualType Sema::GetSignedSizelessVectorType(QualType V) { |
12572 | const BuiltinType *VTy = V->castAs<BuiltinType>(); |
12573 | assert(VTy->isSizelessBuiltinType() && "expected sizeless type" ); |
12574 | |
12575 | const QualType ETy = V->getSveEltType(Ctx: Context); |
12576 | const auto TypeSize = Context.getTypeSize(T: ETy); |
12577 | |
12578 | const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true); |
12579 | const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC; |
12580 | return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue()); |
12581 | } |
12582 | |
12583 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
12584 | SourceLocation Loc, |
12585 | BinaryOperatorKind Opc) { |
12586 | if (Opc == BO_Cmp) { |
12587 | Diag(Loc, DiagID: diag::err_three_way_vector_comparison); |
12588 | return QualType(); |
12589 | } |
12590 | |
12591 | // Check to make sure we're operating on vectors of the same type and width, |
12592 | // Allowing one side to be a scalar of element type. |
12593 | QualType vType = |
12594 | CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, |
12595 | /*AllowBothBool*/ true, |
12596 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
12597 | /*AllowBooleanOperation*/ AllowBoolOperation: true, |
12598 | /*ReportInvalid*/ true); |
12599 | if (vType.isNull()) |
12600 | return vType; |
12601 | |
12602 | QualType LHSType = LHS.get()->getType(); |
12603 | |
12604 | // Determine the return type of a vector compare. By default clang will return |
12605 | // a scalar for all vector compares except vector bool and vector pixel. |
12606 | // With the gcc compiler we will always return a vector type and with the xl |
12607 | // compiler we will always return a scalar type. This switch allows choosing |
12608 | // which behavior is prefered. |
12609 | if (getLangOpts().AltiVec) { |
12610 | switch (getLangOpts().getAltivecSrcCompat()) { |
12611 | case LangOptions::AltivecSrcCompatKind::Mixed: |
12612 | // If AltiVec, the comparison results in a numeric type, i.e. |
12613 | // bool for C++, int for C |
12614 | if (vType->castAs<VectorType>()->getVectorKind() == |
12615 | VectorKind::AltiVecVector) |
12616 | return Context.getLogicalOperationType(); |
12617 | else |
12618 | Diag(Loc, DiagID: diag::warn_deprecated_altivec_src_compat); |
12619 | break; |
12620 | case LangOptions::AltivecSrcCompatKind::GCC: |
12621 | // For GCC we always return the vector type. |
12622 | break; |
12623 | case LangOptions::AltivecSrcCompatKind::XL: |
12624 | return Context.getLogicalOperationType(); |
12625 | break; |
12626 | } |
12627 | } |
12628 | |
12629 | // For non-floating point types, check for self-comparisons of the form |
12630 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
12631 | // often indicate logic errors in the program. |
12632 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
12633 | |
12634 | // Check for comparisons of floating point operands using != and ==. |
12635 | if (LHSType->hasFloatingRepresentation()) { |
12636 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
12637 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
12638 | } |
12639 | |
12640 | // Return a signed type for the vector. |
12641 | return GetSignedVectorType(V: vType); |
12642 | } |
12643 | |
12644 | QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, |
12645 | ExprResult &RHS, |
12646 | SourceLocation Loc, |
12647 | BinaryOperatorKind Opc) { |
12648 | if (Opc == BO_Cmp) { |
12649 | Diag(Loc, DiagID: diag::err_three_way_vector_comparison); |
12650 | return QualType(); |
12651 | } |
12652 | |
12653 | // Check to make sure we're operating on vectors of the same type and width, |
12654 | // Allowing one side to be a scalar of element type. |
12655 | QualType vType = CheckSizelessVectorOperands( |
12656 | LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ACK_Comparison); |
12657 | |
12658 | if (vType.isNull()) |
12659 | return vType; |
12660 | |
12661 | QualType LHSType = LHS.get()->getType(); |
12662 | |
12663 | // For non-floating point types, check for self-comparisons of the form |
12664 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
12665 | // often indicate logic errors in the program. |
12666 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
12667 | |
12668 | // Check for comparisons of floating point operands using != and ==. |
12669 | if (LHSType->hasFloatingRepresentation()) { |
12670 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
12671 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
12672 | } |
12673 | |
12674 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
12675 | const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); |
12676 | |
12677 | if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && |
12678 | RHSBuiltinTy->isSVEBool()) |
12679 | return LHSType; |
12680 | |
12681 | // Return a signed type for the vector. |
12682 | return GetSignedSizelessVectorType(V: vType); |
12683 | } |
12684 | |
12685 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, |
12686 | const ExprResult &XorRHS, |
12687 | const SourceLocation Loc) { |
12688 | // Do not diagnose macros. |
12689 | if (Loc.isMacroID()) |
12690 | return; |
12691 | |
12692 | // Do not diagnose if both LHS and RHS are macros. |
12693 | if (XorLHS.get()->getExprLoc().isMacroID() && |
12694 | XorRHS.get()->getExprLoc().isMacroID()) |
12695 | return; |
12696 | |
12697 | bool Negative = false; |
12698 | bool ExplicitPlus = false; |
12699 | const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get()); |
12700 | const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get()); |
12701 | |
12702 | if (!LHSInt) |
12703 | return; |
12704 | if (!RHSInt) { |
12705 | // Check negative literals. |
12706 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) { |
12707 | UnaryOperatorKind Opc = UO->getOpcode(); |
12708 | if (Opc != UO_Minus && Opc != UO_Plus) |
12709 | return; |
12710 | RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr()); |
12711 | if (!RHSInt) |
12712 | return; |
12713 | Negative = (Opc == UO_Minus); |
12714 | ExplicitPlus = !Negative; |
12715 | } else { |
12716 | return; |
12717 | } |
12718 | } |
12719 | |
12720 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); |
12721 | llvm::APInt RightSideValue = RHSInt->getValue(); |
12722 | if (LeftSideValue != 2 && LeftSideValue != 10) |
12723 | return; |
12724 | |
12725 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) |
12726 | return; |
12727 | |
12728 | CharSourceRange ExprRange = CharSourceRange::getCharRange( |
12729 | B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation())); |
12730 | llvm::StringRef ExprStr = |
12731 | Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
12732 | |
12733 | CharSourceRange XorRange = |
12734 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
12735 | llvm::StringRef XorStr = |
12736 | Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
12737 | // Do not diagnose if xor keyword/macro is used. |
12738 | if (XorStr == "xor" ) |
12739 | return; |
12740 | |
12741 | std::string LHSStr = std::string(Lexer::getSourceText( |
12742 | Range: CharSourceRange::getTokenRange(R: LHSInt->getSourceRange()), |
12743 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
12744 | std::string RHSStr = std::string(Lexer::getSourceText( |
12745 | Range: CharSourceRange::getTokenRange(R: RHSInt->getSourceRange()), |
12746 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
12747 | |
12748 | if (Negative) { |
12749 | RightSideValue = -RightSideValue; |
12750 | RHSStr = "-" + RHSStr; |
12751 | } else if (ExplicitPlus) { |
12752 | RHSStr = "+" + RHSStr; |
12753 | } |
12754 | |
12755 | StringRef LHSStrRef = LHSStr; |
12756 | StringRef RHSStrRef = RHSStr; |
12757 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal |
12758 | // literals. |
12759 | if (LHSStrRef.starts_with(Prefix: "0b" ) || LHSStrRef.starts_with(Prefix: "0B" ) || |
12760 | RHSStrRef.starts_with(Prefix: "0b" ) || RHSStrRef.starts_with(Prefix: "0B" ) || |
12761 | LHSStrRef.starts_with(Prefix: "0x" ) || LHSStrRef.starts_with(Prefix: "0X" ) || |
12762 | RHSStrRef.starts_with(Prefix: "0x" ) || RHSStrRef.starts_with(Prefix: "0X" ) || |
12763 | (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0" )) || |
12764 | (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0" )) || |
12765 | LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\'')) |
12766 | return; |
12767 | |
12768 | bool SuggestXor = |
12769 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor" ); |
12770 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; |
12771 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); |
12772 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { |
12773 | std::string SuggestedExpr = "1 << " + RHSStr; |
12774 | bool Overflow = false; |
12775 | llvm::APInt One = (LeftSideValue - 1); |
12776 | llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow); |
12777 | if (Overflow) { |
12778 | if (RightSideIntValue < 64) |
12779 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base) |
12780 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << ("1LL << " + RHSStr) |
12781 | << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: "1LL << " + RHSStr); |
12782 | else if (RightSideIntValue == 64) |
12783 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow) |
12784 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true); |
12785 | else |
12786 | return; |
12787 | } else { |
12788 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base_extra) |
12789 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedExpr |
12790 | << toString(I: PowValue, Radix: 10, Signed: true) |
12791 | << FixItHint::CreateReplacement( |
12792 | RemoveRange: ExprRange, Code: (RightSideIntValue == 0) ? "1" : SuggestedExpr); |
12793 | } |
12794 | |
12795 | S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence) |
12796 | << ("0x2 ^ " + RHSStr) << SuggestXor; |
12797 | } else if (LeftSideValue == 10) { |
12798 | std::string SuggestedValue = "1e" + std::to_string(val: RightSideIntValue); |
12799 | S.Diag(Loc, DiagID: diag::warn_xor_used_as_pow_base) |
12800 | << ExprStr << toString(I: XorValue, Radix: 10, Signed: true) << SuggestedValue |
12801 | << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: SuggestedValue); |
12802 | S.Diag(Loc, DiagID: diag::note_xor_used_as_pow_silence) |
12803 | << ("0xA ^ " + RHSStr) << SuggestXor; |
12804 | } |
12805 | } |
12806 | |
12807 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
12808 | SourceLocation Loc) { |
12809 | // Ensure that either both operands are of the same vector type, or |
12810 | // one operand is of a vector type and the other is of its element type. |
12811 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false, |
12812 | /*AllowBothBool*/ true, |
12813 | /*AllowBoolConversions*/ false, |
12814 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
12815 | /*ReportInvalid*/ false); |
12816 | if (vType.isNull()) |
12817 | return InvalidOperands(Loc, LHS, RHS); |
12818 | if (getLangOpts().OpenCL && |
12819 | getLangOpts().getOpenCLCompatibleVersion() < 120 && |
12820 | vType->hasFloatingRepresentation()) |
12821 | return InvalidOperands(Loc, LHS, RHS); |
12822 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the |
12823 | // usage of the logical operators && and || with vectors in C. This |
12824 | // check could be notionally dropped. |
12825 | if (!getLangOpts().CPlusPlus && |
12826 | !(isa<ExtVectorType>(Val: vType->getAs<VectorType>()))) |
12827 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); |
12828 | |
12829 | return GetSignedVectorType(V: LHS.get()->getType()); |
12830 | } |
12831 | |
12832 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, |
12833 | SourceLocation Loc, |
12834 | bool IsCompAssign) { |
12835 | if (!IsCompAssign) { |
12836 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
12837 | if (LHS.isInvalid()) |
12838 | return QualType(); |
12839 | } |
12840 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
12841 | if (RHS.isInvalid()) |
12842 | return QualType(); |
12843 | |
12844 | // For conversion purposes, we ignore any qualifiers. |
12845 | // For example, "const float" and "float" are equivalent. |
12846 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
12847 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
12848 | |
12849 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); |
12850 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); |
12851 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ); |
12852 | |
12853 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
12854 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
12855 | |
12856 | // Type conversion may change LHS/RHS. Keep copies to the original results, in |
12857 | // case we have to return InvalidOperands. |
12858 | ExprResult OriginalLHS = LHS; |
12859 | ExprResult OriginalRHS = RHS; |
12860 | if (LHSMatType && !RHSMatType) { |
12861 | RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType()); |
12862 | if (!RHS.isInvalid()) |
12863 | return LHSType; |
12864 | |
12865 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
12866 | } |
12867 | |
12868 | if (!LHSMatType && RHSMatType) { |
12869 | LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType()); |
12870 | if (!LHS.isInvalid()) |
12871 | return RHSType; |
12872 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
12873 | } |
12874 | |
12875 | return InvalidOperands(Loc, LHS, RHS); |
12876 | } |
12877 | |
12878 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, |
12879 | SourceLocation Loc, |
12880 | bool IsCompAssign) { |
12881 | if (!IsCompAssign) { |
12882 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
12883 | if (LHS.isInvalid()) |
12884 | return QualType(); |
12885 | } |
12886 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
12887 | if (RHS.isInvalid()) |
12888 | return QualType(); |
12889 | |
12890 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); |
12891 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); |
12892 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ); |
12893 | |
12894 | if (LHSMatType && RHSMatType) { |
12895 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) |
12896 | return InvalidOperands(Loc, LHS, RHS); |
12897 | |
12898 | if (Context.hasSameType(T1: LHSMatType, T2: RHSMatType)) |
12899 | return Context.getCommonSugaredType( |
12900 | X: LHS.get()->getType().getUnqualifiedType(), |
12901 | Y: RHS.get()->getType().getUnqualifiedType()); |
12902 | |
12903 | QualType LHSELTy = LHSMatType->getElementType(), |
12904 | RHSELTy = RHSMatType->getElementType(); |
12905 | if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy)) |
12906 | return InvalidOperands(Loc, LHS, RHS); |
12907 | |
12908 | return Context.getConstantMatrixType( |
12909 | ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy), |
12910 | NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns()); |
12911 | } |
12912 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
12913 | } |
12914 | |
12915 | static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { |
12916 | switch (Opc) { |
12917 | default: |
12918 | return false; |
12919 | case BO_And: |
12920 | case BO_AndAssign: |
12921 | case BO_Or: |
12922 | case BO_OrAssign: |
12923 | case BO_Xor: |
12924 | case BO_XorAssign: |
12925 | return true; |
12926 | } |
12927 | } |
12928 | |
12929 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, |
12930 | SourceLocation Loc, |
12931 | BinaryOperatorKind Opc) { |
12932 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
12933 | |
12934 | bool IsCompAssign = |
12935 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; |
12936 | |
12937 | bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); |
12938 | |
12939 | if (LHS.get()->getType()->isVectorType() || |
12940 | RHS.get()->getType()->isVectorType()) { |
12941 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
12942 | RHS.get()->getType()->hasIntegerRepresentation()) |
12943 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
12944 | /*AllowBothBool*/ true, |
12945 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
12946 | /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator, |
12947 | /*ReportInvalid*/ true); |
12948 | return InvalidOperands(Loc, LHS, RHS); |
12949 | } |
12950 | |
12951 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
12952 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
12953 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
12954 | RHS.get()->getType()->hasIntegerRepresentation()) |
12955 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
12956 | OperationKind: ACK_BitwiseOp); |
12957 | return InvalidOperands(Loc, LHS, RHS); |
12958 | } |
12959 | |
12960 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
12961 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
12962 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
12963 | RHS.get()->getType()->hasIntegerRepresentation()) |
12964 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
12965 | OperationKind: ACK_BitwiseOp); |
12966 | return InvalidOperands(Loc, LHS, RHS); |
12967 | } |
12968 | |
12969 | if (Opc == BO_And) |
12970 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
12971 | |
12972 | if (LHS.get()->getType()->hasFloatingRepresentation() || |
12973 | RHS.get()->getType()->hasFloatingRepresentation()) |
12974 | return InvalidOperands(Loc, LHS, RHS); |
12975 | |
12976 | ExprResult LHSResult = LHS, RHSResult = RHS; |
12977 | QualType compType = UsualArithmeticConversions( |
12978 | LHS&: LHSResult, RHS&: RHSResult, Loc, ACK: IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); |
12979 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) |
12980 | return QualType(); |
12981 | LHS = LHSResult.get(); |
12982 | RHS = RHSResult.get(); |
12983 | |
12984 | if (Opc == BO_Xor) |
12985 | diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc); |
12986 | |
12987 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) |
12988 | return compType; |
12989 | return InvalidOperands(Loc, LHS, RHS); |
12990 | } |
12991 | |
12992 | // C99 6.5.[13,14] |
12993 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
12994 | SourceLocation Loc, |
12995 | BinaryOperatorKind Opc) { |
12996 | // Check vector operands differently. |
12997 | if (LHS.get()->getType()->isVectorType() || |
12998 | RHS.get()->getType()->isVectorType()) |
12999 | return CheckVectorLogicalOperands(LHS, RHS, Loc); |
13000 | |
13001 | bool EnumConstantInBoolContext = false; |
13002 | for (const ExprResult &HS : {LHS, RHS}) { |
13003 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) { |
13004 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl()); |
13005 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) |
13006 | EnumConstantInBoolContext = true; |
13007 | } |
13008 | } |
13009 | |
13010 | if (EnumConstantInBoolContext) |
13011 | Diag(Loc, DiagID: diag::warn_enum_constant_in_bool_context); |
13012 | |
13013 | // WebAssembly tables can't be used with logical operators. |
13014 | QualType LHSTy = LHS.get()->getType(); |
13015 | QualType RHSTy = RHS.get()->getType(); |
13016 | const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy); |
13017 | const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy); |
13018 | if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) || |
13019 | (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) { |
13020 | return InvalidOperands(Loc, LHS, RHS); |
13021 | } |
13022 | |
13023 | // Diagnose cases where the user write a logical and/or but probably meant a |
13024 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS |
13025 | // is a constant. |
13026 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && |
13027 | !LHS.get()->getType()->isBooleanType() && |
13028 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && |
13029 | // Don't warn in macros or template instantiations. |
13030 | !Loc.isMacroID() && !inTemplateInstantiation()) { |
13031 | // If the RHS can be constant folded, and if it constant folds to something |
13032 | // that isn't 0 or 1 (which indicate a potential logical operation that |
13033 | // happened to fold to true/false) then warn. |
13034 | // Parens on the RHS are ignored. |
13035 | Expr::EvalResult EVResult; |
13036 | if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) { |
13037 | llvm::APSInt Result = EVResult.Val.getInt(); |
13038 | if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() && |
13039 | !RHS.get()->getExprLoc().isMacroID()) || |
13040 | (Result != 0 && Result != 1)) { |
13041 | Diag(Loc, DiagID: diag::warn_logical_instead_of_bitwise) |
13042 | << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||" ); |
13043 | // Suggest replacing the logical operator with the bitwise version |
13044 | Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_change_operator) |
13045 | << (Opc == BO_LAnd ? "&" : "|" ) |
13046 | << FixItHint::CreateReplacement( |
13047 | RemoveRange: SourceRange(Loc, getLocForEndOfToken(Loc)), |
13048 | Code: Opc == BO_LAnd ? "&" : "|" ); |
13049 | if (Opc == BO_LAnd) |
13050 | // Suggest replacing "Foo() && kNonZero" with "Foo()" |
13051 | Diag(Loc, DiagID: diag::note_logical_instead_of_bitwise_remove_constant) |
13052 | << FixItHint::CreateRemoval( |
13053 | RemoveRange: SourceRange(getLocForEndOfToken(Loc: LHS.get()->getEndLoc()), |
13054 | RHS.get()->getEndLoc())); |
13055 | } |
13056 | } |
13057 | } |
13058 | |
13059 | if (!Context.getLangOpts().CPlusPlus) { |
13060 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do |
13061 | // not operate on the built-in scalar and vector float types. |
13062 | if (Context.getLangOpts().OpenCL && |
13063 | Context.getLangOpts().OpenCLVersion < 120) { |
13064 | if (LHS.get()->getType()->isFloatingType() || |
13065 | RHS.get()->getType()->isFloatingType()) |
13066 | return InvalidOperands(Loc, LHS, RHS); |
13067 | } |
13068 | |
13069 | LHS = UsualUnaryConversions(E: LHS.get()); |
13070 | if (LHS.isInvalid()) |
13071 | return QualType(); |
13072 | |
13073 | RHS = UsualUnaryConversions(E: RHS.get()); |
13074 | if (RHS.isInvalid()) |
13075 | return QualType(); |
13076 | |
13077 | if (!LHS.get()->getType()->isScalarType() || |
13078 | !RHS.get()->getType()->isScalarType()) |
13079 | return InvalidOperands(Loc, LHS, RHS); |
13080 | |
13081 | return Context.IntTy; |
13082 | } |
13083 | |
13084 | // The following is safe because we only use this method for |
13085 | // non-overloadable operands. |
13086 | |
13087 | // C++ [expr.log.and]p1 |
13088 | // C++ [expr.log.or]p1 |
13089 | // The operands are both contextually converted to type bool. |
13090 | ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get()); |
13091 | if (LHSRes.isInvalid()) |
13092 | return InvalidOperands(Loc, LHS, RHS); |
13093 | LHS = LHSRes; |
13094 | |
13095 | ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get()); |
13096 | if (RHSRes.isInvalid()) |
13097 | return InvalidOperands(Loc, LHS, RHS); |
13098 | RHS = RHSRes; |
13099 | |
13100 | // C++ [expr.log.and]p2 |
13101 | // C++ [expr.log.or]p2 |
13102 | // The result is a bool. |
13103 | return Context.BoolTy; |
13104 | } |
13105 | |
13106 | static bool IsReadonlyMessage(Expr *E, Sema &S) { |
13107 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
13108 | if (!ME) return false; |
13109 | if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false; |
13110 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( |
13111 | Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); |
13112 | if (!Base) return false; |
13113 | return Base->getMethodDecl() != nullptr; |
13114 | } |
13115 | |
13116 | /// Is the given expression (which must be 'const') a reference to a |
13117 | /// variable which was originally non-const, but which has become |
13118 | /// 'const' due to being captured within a block? |
13119 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; |
13120 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { |
13121 | assert(E->isLValue() && E->getType().isConstQualified()); |
13122 | E = E->IgnoreParens(); |
13123 | |
13124 | // Must be a reference to a declaration from an enclosing scope. |
13125 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
13126 | if (!DRE) return NCCK_None; |
13127 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; |
13128 | |
13129 | // The declaration must be a variable which is not declared 'const'. |
13130 | VarDecl *var = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
13131 | if (!var) return NCCK_None; |
13132 | if (var->getType().isConstQualified()) return NCCK_None; |
13133 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?" ); |
13134 | |
13135 | // Decide whether the first capture was for a block or a lambda. |
13136 | DeclContext *DC = S.CurContext, *Prev = nullptr; |
13137 | // Decide whether the first capture was for a block or a lambda. |
13138 | while (DC) { |
13139 | // For init-capture, it is possible that the variable belongs to the |
13140 | // template pattern of the current context. |
13141 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DC)) |
13142 | if (var->isInitCapture() && |
13143 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) |
13144 | break; |
13145 | if (DC == var->getDeclContext()) |
13146 | break; |
13147 | Prev = DC; |
13148 | DC = DC->getParent(); |
13149 | } |
13150 | // Unless we have an init-capture, we've gone one step too far. |
13151 | if (!var->isInitCapture()) |
13152 | DC = Prev; |
13153 | return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda); |
13154 | } |
13155 | |
13156 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { |
13157 | Ty = Ty.getNonReferenceType(); |
13158 | if (IsDereference && Ty->isPointerType()) |
13159 | Ty = Ty->getPointeeType(); |
13160 | return !Ty.isConstQualified(); |
13161 | } |
13162 | |
13163 | // Update err_typecheck_assign_const and note_typecheck_assign_const |
13164 | // when this enum is changed. |
13165 | enum { |
13166 | ConstFunction, |
13167 | ConstVariable, |
13168 | ConstMember, |
13169 | ConstMethod, |
13170 | NestedConstMember, |
13171 | ConstUnknown, // Keep as last element |
13172 | }; |
13173 | |
13174 | /// Emit the "read-only variable not assignable" error and print notes to give |
13175 | /// more information about why the variable is not assignable, such as pointing |
13176 | /// to the declaration of a const variable, showing that a method is const, or |
13177 | /// that the function is returning a const reference. |
13178 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, |
13179 | SourceLocation Loc) { |
13180 | SourceRange ExprRange = E->getSourceRange(); |
13181 | |
13182 | // Only emit one error on the first const found. All other consts will emit |
13183 | // a note to the error. |
13184 | bool DiagnosticEmitted = false; |
13185 | |
13186 | // Track if the current expression is the result of a dereference, and if the |
13187 | // next checked expression is the result of a dereference. |
13188 | bool IsDereference = false; |
13189 | bool NextIsDereference = false; |
13190 | |
13191 | // Loop to process MemberExpr chains. |
13192 | while (true) { |
13193 | IsDereference = NextIsDereference; |
13194 | |
13195 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); |
13196 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) { |
13197 | NextIsDereference = ME->isArrow(); |
13198 | const ValueDecl *VD = ME->getMemberDecl(); |
13199 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) { |
13200 | // Mutable fields can be modified even if the class is const. |
13201 | if (Field->isMutable()) { |
13202 | assert(DiagnosticEmitted && "Expected diagnostic not emitted." ); |
13203 | break; |
13204 | } |
13205 | |
13206 | if (!IsTypeModifiable(Ty: Field->getType(), IsDereference)) { |
13207 | if (!DiagnosticEmitted) { |
13208 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
13209 | << ExprRange << ConstMember << false /*static*/ << Field |
13210 | << Field->getType(); |
13211 | DiagnosticEmitted = true; |
13212 | } |
13213 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
13214 | << ConstMember << false /*static*/ << Field << Field->getType() |
13215 | << Field->getSourceRange(); |
13216 | } |
13217 | E = ME->getBase(); |
13218 | continue; |
13219 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) { |
13220 | if (VDecl->getType().isConstQualified()) { |
13221 | if (!DiagnosticEmitted) { |
13222 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
13223 | << ExprRange << ConstMember << true /*static*/ << VDecl |
13224 | << VDecl->getType(); |
13225 | DiagnosticEmitted = true; |
13226 | } |
13227 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
13228 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() |
13229 | << VDecl->getSourceRange(); |
13230 | } |
13231 | // Static fields do not inherit constness from parents. |
13232 | break; |
13233 | } |
13234 | break; // End MemberExpr |
13235 | } else if (const ArraySubscriptExpr *ASE = |
13236 | dyn_cast<ArraySubscriptExpr>(Val: E)) { |
13237 | E = ASE->getBase()->IgnoreParenImpCasts(); |
13238 | continue; |
13239 | } else if (const ExtVectorElementExpr *EVE = |
13240 | dyn_cast<ExtVectorElementExpr>(Val: E)) { |
13241 | E = EVE->getBase()->IgnoreParenImpCasts(); |
13242 | continue; |
13243 | } |
13244 | break; |
13245 | } |
13246 | |
13247 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
13248 | // Function calls |
13249 | const FunctionDecl *FD = CE->getDirectCallee(); |
13250 | if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) { |
13251 | if (!DiagnosticEmitted) { |
13252 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange |
13253 | << ConstFunction << FD; |
13254 | DiagnosticEmitted = true; |
13255 | } |
13256 | S.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(), |
13257 | DiagID: diag::note_typecheck_assign_const) |
13258 | << ConstFunction << FD << FD->getReturnType() |
13259 | << FD->getReturnTypeSourceRange(); |
13260 | } |
13261 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
13262 | // Point to variable declaration. |
13263 | if (const ValueDecl *VD = DRE->getDecl()) { |
13264 | if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) { |
13265 | if (!DiagnosticEmitted) { |
13266 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
13267 | << ExprRange << ConstVariable << VD << VD->getType(); |
13268 | DiagnosticEmitted = true; |
13269 | } |
13270 | S.Diag(Loc: VD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
13271 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); |
13272 | } |
13273 | } |
13274 | } else if (isa<CXXThisExpr>(Val: E)) { |
13275 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { |
13276 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) { |
13277 | if (MD->isConst()) { |
13278 | if (!DiagnosticEmitted) { |
13279 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange |
13280 | << ConstMethod << MD; |
13281 | DiagnosticEmitted = true; |
13282 | } |
13283 | S.Diag(Loc: MD->getLocation(), DiagID: diag::note_typecheck_assign_const) |
13284 | << ConstMethod << MD << MD->getSourceRange(); |
13285 | } |
13286 | } |
13287 | } |
13288 | } |
13289 | |
13290 | if (DiagnosticEmitted) |
13291 | return; |
13292 | |
13293 | // Can't determine a more specific message, so display the generic error. |
13294 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; |
13295 | } |
13296 | |
13297 | enum OriginalExprKind { |
13298 | OEK_Variable, |
13299 | OEK_Member, |
13300 | OEK_LValue |
13301 | }; |
13302 | |
13303 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, |
13304 | const RecordType *Ty, |
13305 | SourceLocation Loc, SourceRange Range, |
13306 | OriginalExprKind OEK, |
13307 | bool &DiagnosticEmitted) { |
13308 | std::vector<const RecordType *> RecordTypeList; |
13309 | RecordTypeList.push_back(x: Ty); |
13310 | unsigned NextToCheckIndex = 0; |
13311 | // We walk the record hierarchy breadth-first to ensure that we print |
13312 | // diagnostics in field nesting order. |
13313 | while (RecordTypeList.size() > NextToCheckIndex) { |
13314 | bool IsNested = NextToCheckIndex > 0; |
13315 | for (const FieldDecl *Field : |
13316 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { |
13317 | // First, check every field for constness. |
13318 | QualType FieldTy = Field->getType(); |
13319 | if (FieldTy.isConstQualified()) { |
13320 | if (!DiagnosticEmitted) { |
13321 | S.Diag(Loc, DiagID: diag::err_typecheck_assign_const) |
13322 | << Range << NestedConstMember << OEK << VD |
13323 | << IsNested << Field; |
13324 | DiagnosticEmitted = true; |
13325 | } |
13326 | S.Diag(Loc: Field->getLocation(), DiagID: diag::note_typecheck_assign_const) |
13327 | << NestedConstMember << IsNested << Field |
13328 | << FieldTy << Field->getSourceRange(); |
13329 | } |
13330 | |
13331 | // Then we append it to the list to check next in order. |
13332 | FieldTy = FieldTy.getCanonicalType(); |
13333 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { |
13334 | if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy)) |
13335 | RecordTypeList.push_back(x: FieldRecTy); |
13336 | } |
13337 | } |
13338 | ++NextToCheckIndex; |
13339 | } |
13340 | } |
13341 | |
13342 | /// Emit an error for the case where a record we are trying to assign to has a |
13343 | /// const-qualified field somewhere in its hierarchy. |
13344 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, |
13345 | SourceLocation Loc) { |
13346 | QualType Ty = E->getType(); |
13347 | assert(Ty->isRecordType() && "lvalue was not record?" ); |
13348 | SourceRange Range = E->getSourceRange(); |
13349 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); |
13350 | bool DiagEmitted = false; |
13351 | |
13352 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) |
13353 | DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc, |
13354 | Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted); |
13355 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
13356 | DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc, |
13357 | Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted); |
13358 | else |
13359 | DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc, |
13360 | Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted); |
13361 | if (!DiagEmitted) |
13362 | DiagnoseConstAssignment(S, E, Loc); |
13363 | } |
13364 | |
13365 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, |
13366 | /// emit an error and return true. If so, return false. |
13367 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { |
13368 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); |
13369 | |
13370 | S.CheckShadowingDeclModification(E, Loc); |
13371 | |
13372 | SourceLocation OrigLoc = Loc; |
13373 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context, |
13374 | Loc: &Loc); |
13375 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) |
13376 | IsLV = Expr::MLV_InvalidMessageExpression; |
13377 | if (IsLV == Expr::MLV_Valid) |
13378 | return false; |
13379 | |
13380 | unsigned DiagID = 0; |
13381 | bool NeedType = false; |
13382 | switch (IsLV) { // C99 6.5.16p2 |
13383 | case Expr::MLV_ConstQualified: |
13384 | // Use a specialized diagnostic when we're assigning to an object |
13385 | // from an enclosing function or block. |
13386 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { |
13387 | if (NCCK == NCCK_Block) |
13388 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; |
13389 | else |
13390 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; |
13391 | break; |
13392 | } |
13393 | |
13394 | // In ARC, use some specialized diagnostics for occasions where we |
13395 | // infer 'const'. These are always pseudo-strong variables. |
13396 | if (S.getLangOpts().ObjCAutoRefCount) { |
13397 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()); |
13398 | if (declRef && isa<VarDecl>(Val: declRef->getDecl())) { |
13399 | VarDecl *var = cast<VarDecl>(Val: declRef->getDecl()); |
13400 | |
13401 | // Use the normal diagnostic if it's pseudo-__strong but the |
13402 | // user actually wrote 'const'. |
13403 | if (var->isARCPseudoStrong() && |
13404 | (!var->getTypeSourceInfo() || |
13405 | !var->getTypeSourceInfo()->getType().isConstQualified())) { |
13406 | // There are three pseudo-strong cases: |
13407 | // - self |
13408 | ObjCMethodDecl *method = S.getCurMethodDecl(); |
13409 | if (method && var == method->getSelfDecl()) { |
13410 | DiagID = method->isClassMethod() |
13411 | ? diag::err_typecheck_arc_assign_self_class_method |
13412 | : diag::err_typecheck_arc_assign_self; |
13413 | |
13414 | // - Objective-C externally_retained attribute. |
13415 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || |
13416 | isa<ParmVarDecl>(Val: var)) { |
13417 | DiagID = diag::err_typecheck_arc_assign_externally_retained; |
13418 | |
13419 | // - fast enumeration variables |
13420 | } else { |
13421 | DiagID = diag::err_typecheck_arr_assign_enumeration; |
13422 | } |
13423 | |
13424 | SourceRange Assign; |
13425 | if (Loc != OrigLoc) |
13426 | Assign = SourceRange(OrigLoc, OrigLoc); |
13427 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
13428 | // We need to preserve the AST regardless, so migration tool |
13429 | // can do its job. |
13430 | return false; |
13431 | } |
13432 | } |
13433 | } |
13434 | |
13435 | // If none of the special cases above are triggered, then this is a |
13436 | // simple const assignment. |
13437 | if (DiagID == 0) { |
13438 | DiagnoseConstAssignment(S, E, Loc); |
13439 | return true; |
13440 | } |
13441 | |
13442 | break; |
13443 | case Expr::MLV_ConstAddrSpace: |
13444 | DiagnoseConstAssignment(S, E, Loc); |
13445 | return true; |
13446 | case Expr::MLV_ConstQualifiedField: |
13447 | DiagnoseRecursiveConstFields(S, E, Loc); |
13448 | return true; |
13449 | case Expr::MLV_ArrayType: |
13450 | case Expr::MLV_ArrayTemporary: |
13451 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; |
13452 | NeedType = true; |
13453 | break; |
13454 | case Expr::MLV_NotObjectType: |
13455 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; |
13456 | NeedType = true; |
13457 | break; |
13458 | case Expr::MLV_LValueCast: |
13459 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; |
13460 | break; |
13461 | case Expr::MLV_Valid: |
13462 | llvm_unreachable("did not take early return for MLV_Valid" ); |
13463 | case Expr::MLV_InvalidExpression: |
13464 | case Expr::MLV_MemberFunction: |
13465 | case Expr::MLV_ClassTemporary: |
13466 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; |
13467 | break; |
13468 | case Expr::MLV_IncompleteType: |
13469 | case Expr::MLV_IncompleteVoidType: |
13470 | return S.RequireCompleteType(Loc, T: E->getType(), |
13471 | DiagID: diag::err_typecheck_incomplete_type_not_modifiable_lvalue, Args: E); |
13472 | case Expr::MLV_DuplicateVectorComponents: |
13473 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; |
13474 | break; |
13475 | case Expr::MLV_NoSetterProperty: |
13476 | llvm_unreachable("readonly properties should be processed differently" ); |
13477 | case Expr::MLV_InvalidMessageExpression: |
13478 | DiagID = diag::err_readonly_message_assignment; |
13479 | break; |
13480 | case Expr::MLV_SubObjCPropertySetting: |
13481 | DiagID = diag::err_no_subobject_property_setting; |
13482 | break; |
13483 | } |
13484 | |
13485 | SourceRange Assign; |
13486 | if (Loc != OrigLoc) |
13487 | Assign = SourceRange(OrigLoc, OrigLoc); |
13488 | if (NeedType) |
13489 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; |
13490 | else |
13491 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
13492 | return true; |
13493 | } |
13494 | |
13495 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, |
13496 | SourceLocation Loc, |
13497 | Sema &Sema) { |
13498 | if (Sema.inTemplateInstantiation()) |
13499 | return; |
13500 | if (Sema.isUnevaluatedContext()) |
13501 | return; |
13502 | if (Loc.isInvalid() || Loc.isMacroID()) |
13503 | return; |
13504 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) |
13505 | return; |
13506 | |
13507 | // C / C++ fields |
13508 | MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr); |
13509 | MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr); |
13510 | if (ML && MR) { |
13511 | if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase()))) |
13512 | return; |
13513 | const ValueDecl *LHSDecl = |
13514 | cast<ValueDecl>(Val: ML->getMemberDecl()->getCanonicalDecl()); |
13515 | const ValueDecl *RHSDecl = |
13516 | cast<ValueDecl>(Val: MR->getMemberDecl()->getCanonicalDecl()); |
13517 | if (LHSDecl != RHSDecl) |
13518 | return; |
13519 | if (LHSDecl->getType().isVolatileQualified()) |
13520 | return; |
13521 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
13522 | if (RefTy->getPointeeType().isVolatileQualified()) |
13523 | return; |
13524 | |
13525 | Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 0; |
13526 | } |
13527 | |
13528 | // Objective-C instance variables |
13529 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr); |
13530 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr); |
13531 | if (OL && OR && OL->getDecl() == OR->getDecl()) { |
13532 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts()); |
13533 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts()); |
13534 | if (RL && RR && RL->getDecl() == RR->getDecl()) |
13535 | Sema.Diag(Loc, DiagID: diag::warn_identity_field_assign) << 1; |
13536 | } |
13537 | } |
13538 | |
13539 | // C99 6.5.16.1 |
13540 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, |
13541 | SourceLocation Loc, |
13542 | QualType CompoundType, |
13543 | BinaryOperatorKind Opc) { |
13544 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); |
13545 | |
13546 | // Verify that LHS is a modifiable lvalue, and emit error if not. |
13547 | if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this)) |
13548 | return QualType(); |
13549 | |
13550 | QualType LHSType = LHSExpr->getType(); |
13551 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : |
13552 | CompoundType; |
13553 | // OpenCL v1.2 s6.1.1.1 p2: |
13554 | // The half data type can only be used to declare a pointer to a buffer that |
13555 | // contains half values |
13556 | if (getLangOpts().OpenCL && |
13557 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , LO: getLangOpts()) && |
13558 | LHSType->isHalfType()) { |
13559 | Diag(Loc, DiagID: diag::err_opencl_half_load_store) << 1 |
13560 | << LHSType.getUnqualifiedType(); |
13561 | return QualType(); |
13562 | } |
13563 | |
13564 | // WebAssembly tables can't be used on RHS of an assignment expression. |
13565 | if (RHSType->isWebAssemblyTableType()) { |
13566 | Diag(Loc, DiagID: diag::err_wasm_table_art) << 0; |
13567 | return QualType(); |
13568 | } |
13569 | |
13570 | AssignConvertType ConvTy; |
13571 | if (CompoundType.isNull()) { |
13572 | Expr *RHSCheck = RHS.get(); |
13573 | |
13574 | CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this); |
13575 | |
13576 | QualType LHSTy(LHSType); |
13577 | ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS); |
13578 | if (RHS.isInvalid()) |
13579 | return QualType(); |
13580 | // Special case of NSObject attributes on c-style pointer types. |
13581 | if (ConvTy == IncompatiblePointer && |
13582 | ((Context.isObjCNSObjectType(Ty: LHSType) && |
13583 | RHSType->isObjCObjectPointerType()) || |
13584 | (Context.isObjCNSObjectType(Ty: RHSType) && |
13585 | LHSType->isObjCObjectPointerType()))) |
13586 | ConvTy = Compatible; |
13587 | |
13588 | if (ConvTy == Compatible && |
13589 | LHSType->isObjCObjectType()) |
13590 | Diag(Loc, DiagID: diag::err_objc_object_assignment) |
13591 | << LHSType; |
13592 | |
13593 | // If the RHS is a unary plus or minus, check to see if they = and + are |
13594 | // right next to each other. If so, the user may have typo'd "x =+ 4" |
13595 | // instead of "x += 4". |
13596 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck)) |
13597 | RHSCheck = ICE->getSubExpr(); |
13598 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) { |
13599 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && |
13600 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && |
13601 | // Only if the two operators are exactly adjacent. |
13602 | Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() && |
13603 | // And there is a space or other character before the subexpr of the |
13604 | // unary +/-. We don't want to warn on "x=-1". |
13605 | Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() && |
13606 | UO->getSubExpr()->getBeginLoc().isFileID()) { |
13607 | Diag(Loc, DiagID: diag::warn_not_compound_assign) |
13608 | << (UO->getOpcode() == UO_Plus ? "+" : "-" ) |
13609 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); |
13610 | } |
13611 | } |
13612 | |
13613 | if (ConvTy == Compatible) { |
13614 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { |
13615 | // Warn about retain cycles where a block captures the LHS, but |
13616 | // not if the LHS is a simple variable into which the block is |
13617 | // being stored...unless that variable can be captured by reference! |
13618 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); |
13619 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS); |
13620 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) |
13621 | ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get()); |
13622 | } |
13623 | |
13624 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || |
13625 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { |
13626 | // It is safe to assign a weak reference into a strong variable. |
13627 | // Although this code can still have problems: |
13628 | // id x = self.weakProp; |
13629 | // id y = self.weakProp; |
13630 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
13631 | // paths through the function. This should be revisited if |
13632 | // -Wrepeated-use-of-weak is made flow-sensitive. |
13633 | // For ObjCWeak only, we do not warn if the assign is to a non-weak |
13634 | // variable, which will be valid for the current autorelease scope. |
13635 | if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, |
13636 | Loc: RHS.get()->getBeginLoc())) |
13637 | getCurFunction()->markSafeWeakUse(E: RHS.get()); |
13638 | |
13639 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { |
13640 | checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get()); |
13641 | } |
13642 | } |
13643 | } else { |
13644 | // Compound assignment "x += y" |
13645 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); |
13646 | } |
13647 | |
13648 | if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, |
13649 | SrcExpr: RHS.get(), Action: AA_Assigning)) |
13650 | return QualType(); |
13651 | |
13652 | CheckForNullPointerDereference(S&: *this, E: LHSExpr); |
13653 | |
13654 | AssignedEntity AE{.LHS: LHSExpr}; |
13655 | checkExprLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get()); |
13656 | |
13657 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { |
13658 | if (CompoundType.isNull()) { |
13659 | // C++2a [expr.ass]p5: |
13660 | // A simple-assignment whose left operand is of a volatile-qualified |
13661 | // type is deprecated unless the assignment is either a discarded-value |
13662 | // expression or an unevaluated operand |
13663 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr); |
13664 | } |
13665 | } |
13666 | |
13667 | // C11 6.5.16p3: The type of an assignment expression is the type of the |
13668 | // left operand would have after lvalue conversion. |
13669 | // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has |
13670 | // qualified type, the value has the unqualified version of the type of the |
13671 | // lvalue; additionally, if the lvalue has atomic type, the value has the |
13672 | // non-atomic version of the type of the lvalue. |
13673 | // C++ 5.17p1: the type of the assignment expression is that of its left |
13674 | // operand. |
13675 | return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); |
13676 | } |
13677 | |
13678 | // Scenarios to ignore if expression E is: |
13679 | // 1. an explicit cast expression into void |
13680 | // 2. a function call expression that returns void |
13681 | static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { |
13682 | E = E->IgnoreParens(); |
13683 | |
13684 | if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) { |
13685 | if (CE->getCastKind() == CK_ToVoid) { |
13686 | return true; |
13687 | } |
13688 | |
13689 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. |
13690 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && |
13691 | CE->getSubExpr()->getType()->isDependentType()) { |
13692 | return true; |
13693 | } |
13694 | } |
13695 | |
13696 | if (const auto *CE = dyn_cast<CallExpr>(Val: E)) |
13697 | return CE->getCallReturnType(Ctx: Context)->isVoidType(); |
13698 | return false; |
13699 | } |
13700 | |
13701 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { |
13702 | // No warnings in macros |
13703 | if (Loc.isMacroID()) |
13704 | return; |
13705 | |
13706 | // Don't warn in template instantiations. |
13707 | if (inTemplateInstantiation()) |
13708 | return; |
13709 | |
13710 | // Scope isn't fine-grained enough to explicitly list the specific cases, so |
13711 | // instead, skip more than needed, then call back into here with the |
13712 | // CommaVisitor in SemaStmt.cpp. |
13713 | // The listed locations are the initialization and increment portions |
13714 | // of a for loop. The additional checks are on the condition of |
13715 | // if statements, do/while loops, and for loops. |
13716 | // Differences in scope flags for C89 mode requires the extra logic. |
13717 | const unsigned ForIncrementFlags = |
13718 | getLangOpts().C99 || getLangOpts().CPlusPlus |
13719 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope |
13720 | : Scope::ContinueScope | Scope::BreakScope; |
13721 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; |
13722 | const unsigned ScopeFlags = getCurScope()->getFlags(); |
13723 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || |
13724 | (ScopeFlags & ForInitFlags) == ForInitFlags) |
13725 | return; |
13726 | |
13727 | // If there are multiple comma operators used together, get the RHS of the |
13728 | // of the comma operator as the LHS. |
13729 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) { |
13730 | if (BO->getOpcode() != BO_Comma) |
13731 | break; |
13732 | LHS = BO->getRHS(); |
13733 | } |
13734 | |
13735 | // Only allow some expressions on LHS to not warn. |
13736 | if (IgnoreCommaOperand(E: LHS, Context)) |
13737 | return; |
13738 | |
13739 | Diag(Loc, DiagID: diag::warn_comma_operator); |
13740 | Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_cast_to_void) |
13741 | << LHS->getSourceRange() |
13742 | << FixItHint::CreateInsertion(InsertionLoc: LHS->getBeginLoc(), |
13743 | Code: LangOpts.CPlusPlus ? "static_cast<void>(" |
13744 | : "(void)(" ) |
13745 | << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: LHS->getEndLoc()), |
13746 | Code: ")" ); |
13747 | } |
13748 | |
13749 | // C99 6.5.17 |
13750 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, |
13751 | SourceLocation Loc) { |
13752 | LHS = S.CheckPlaceholderExpr(E: LHS.get()); |
13753 | RHS = S.CheckPlaceholderExpr(E: RHS.get()); |
13754 | if (LHS.isInvalid() || RHS.isInvalid()) |
13755 | return QualType(); |
13756 | |
13757 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its |
13758 | // operands, but not unary promotions. |
13759 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). |
13760 | |
13761 | // So we treat the LHS as a ignored value, and in C++ we allow the |
13762 | // containing site to determine what should be done with the RHS. |
13763 | LHS = S.IgnoredValueConversions(E: LHS.get()); |
13764 | if (LHS.isInvalid()) |
13765 | return QualType(); |
13766 | |
13767 | S.DiagnoseUnusedExprResult(S: LHS.get(), DiagID: diag::warn_unused_comma_left_operand); |
13768 | |
13769 | if (!S.getLangOpts().CPlusPlus) { |
13770 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
13771 | if (RHS.isInvalid()) |
13772 | return QualType(); |
13773 | if (!RHS.get()->getType()->isVoidType()) |
13774 | S.RequireCompleteType(Loc, T: RHS.get()->getType(), |
13775 | DiagID: diag::err_incomplete_type); |
13776 | } |
13777 | |
13778 | if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_comma_operator, Loc)) |
13779 | S.DiagnoseCommaOperator(LHS: LHS.get(), Loc); |
13780 | |
13781 | return RHS.get()->getType(); |
13782 | } |
13783 | |
13784 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine |
13785 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. |
13786 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, |
13787 | ExprValueKind &VK, |
13788 | ExprObjectKind &OK, |
13789 | SourceLocation OpLoc, bool IsInc, |
13790 | bool IsPrefix) { |
13791 | QualType ResType = Op->getType(); |
13792 | // Atomic types can be used for increment / decrement where the non-atomic |
13793 | // versions can, so ignore the _Atomic() specifier for the purpose of |
13794 | // checking. |
13795 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
13796 | ResType = ResAtomicType->getValueType(); |
13797 | |
13798 | assert(!ResType.isNull() && "no type for increment/decrement expression" ); |
13799 | |
13800 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { |
13801 | // Decrement of bool is not allowed. |
13802 | if (!IsInc) { |
13803 | S.Diag(Loc: OpLoc, DiagID: diag::err_decrement_bool) << Op->getSourceRange(); |
13804 | return QualType(); |
13805 | } |
13806 | // Increment of bool sets it to true, but is deprecated. |
13807 | S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool |
13808 | : diag::warn_increment_bool) |
13809 | << Op->getSourceRange(); |
13810 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { |
13811 | // Error on enum increments and decrements in C++ mode |
13812 | S.Diag(Loc: OpLoc, DiagID: diag::err_increment_decrement_enum) << IsInc << ResType; |
13813 | return QualType(); |
13814 | } else if (ResType->isRealType()) { |
13815 | // OK! |
13816 | } else if (ResType->isPointerType()) { |
13817 | // C99 6.5.2.4p2, 6.5.6p2 |
13818 | if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op)) |
13819 | return QualType(); |
13820 | } else if (ResType->isObjCObjectPointerType()) { |
13821 | // On modern runtimes, ObjC pointer arithmetic is forbidden. |
13822 | // Otherwise, we just need a complete type. |
13823 | if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) || |
13824 | checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op)) |
13825 | return QualType(); |
13826 | } else if (ResType->isAnyComplexType()) { |
13827 | // C99 does not support ++/-- on complex types, we allow as an extension. |
13828 | S.Diag(Loc: OpLoc, DiagID: S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex |
13829 | : diag::ext_c2y_increment_complex) |
13830 | << IsInc << Op->getSourceRange(); |
13831 | } else if (ResType->isPlaceholderType()) { |
13832 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
13833 | if (PR.isInvalid()) return QualType(); |
13834 | return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc, |
13835 | IsInc, IsPrefix); |
13836 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { |
13837 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) |
13838 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && |
13839 | (ResType->castAs<VectorType>()->getVectorKind() != |
13840 | VectorKind::AltiVecBool)) { |
13841 | // The z vector extensions allow ++ and -- for non-bool vectors. |
13842 | } else if (S.getLangOpts().OpenCL && ResType->isVectorType() && |
13843 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { |
13844 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. |
13845 | } else { |
13846 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_illegal_increment_decrement) |
13847 | << ResType << int(IsInc) << Op->getSourceRange(); |
13848 | return QualType(); |
13849 | } |
13850 | // At this point, we know we have a real, complex or pointer type. |
13851 | // Now make sure the operand is a modifiable lvalue. |
13852 | if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S)) |
13853 | return QualType(); |
13854 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { |
13855 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: |
13856 | // An operand with volatile-qualified type is deprecated |
13857 | S.Diag(Loc: OpLoc, DiagID: diag::warn_deprecated_increment_decrement_volatile) |
13858 | << IsInc << ResType; |
13859 | } |
13860 | // In C++, a prefix increment is the same type as the operand. Otherwise |
13861 | // (in C or with postfix), the increment is the unqualified type of the |
13862 | // operand. |
13863 | if (IsPrefix && S.getLangOpts().CPlusPlus) { |
13864 | VK = VK_LValue; |
13865 | OK = Op->getObjectKind(); |
13866 | return ResType; |
13867 | } else { |
13868 | VK = VK_PRValue; |
13869 | return ResType.getUnqualifiedType(); |
13870 | } |
13871 | } |
13872 | |
13873 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). |
13874 | /// This routine allows us to typecheck complex/recursive expressions |
13875 | /// where the declaration is needed for type checking. We only need to |
13876 | /// handle cases when the expression references a function designator |
13877 | /// or is an lvalue. Here are some examples: |
13878 | /// - &(x) => x |
13879 | /// - &*****f => f for f a function designator. |
13880 | /// - &s.xx => s |
13881 | /// - &s.zz[1].yy -> s, if zz is an array |
13882 | /// - *(x + 1) -> x, if x is an array |
13883 | /// - &"123"[2] -> 0 |
13884 | /// - & __real__ x -> x |
13885 | /// |
13886 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to |
13887 | /// members. |
13888 | static ValueDecl *getPrimaryDecl(Expr *E) { |
13889 | switch (E->getStmtClass()) { |
13890 | case Stmt::DeclRefExprClass: |
13891 | return cast<DeclRefExpr>(Val: E)->getDecl(); |
13892 | case Stmt::MemberExprClass: |
13893 | // If this is an arrow operator, the address is an offset from |
13894 | // the base's value, so the object the base refers to is |
13895 | // irrelevant. |
13896 | if (cast<MemberExpr>(Val: E)->isArrow()) |
13897 | return nullptr; |
13898 | // Otherwise, the expression refers to a part of the base |
13899 | return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase()); |
13900 | case Stmt::ArraySubscriptExprClass: { |
13901 | // FIXME: This code shouldn't be necessary! We should catch the implicit |
13902 | // promotion of register arrays earlier. |
13903 | Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase(); |
13904 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) { |
13905 | if (ICE->getSubExpr()->getType()->isArrayType()) |
13906 | return getPrimaryDecl(E: ICE->getSubExpr()); |
13907 | } |
13908 | return nullptr; |
13909 | } |
13910 | case Stmt::UnaryOperatorClass: { |
13911 | UnaryOperator *UO = cast<UnaryOperator>(Val: E); |
13912 | |
13913 | switch(UO->getOpcode()) { |
13914 | case UO_Real: |
13915 | case UO_Imag: |
13916 | case UO_Extension: |
13917 | return getPrimaryDecl(E: UO->getSubExpr()); |
13918 | default: |
13919 | return nullptr; |
13920 | } |
13921 | } |
13922 | case Stmt::ParenExprClass: |
13923 | return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr()); |
13924 | case Stmt::ImplicitCastExprClass: |
13925 | // If the result of an implicit cast is an l-value, we care about |
13926 | // the sub-expression; otherwise, the result here doesn't matter. |
13927 | return getPrimaryDecl(E: cast<ImplicitCastExpr>(Val: E)->getSubExpr()); |
13928 | case Stmt::CXXUuidofExprClass: |
13929 | return cast<CXXUuidofExpr>(Val: E)->getGuidDecl(); |
13930 | default: |
13931 | return nullptr; |
13932 | } |
13933 | } |
13934 | |
13935 | namespace { |
13936 | enum { |
13937 | AO_Bit_Field = 0, |
13938 | AO_Vector_Element = 1, |
13939 | AO_Property_Expansion = 2, |
13940 | AO_Register_Variable = 3, |
13941 | AO_Matrix_Element = 4, |
13942 | AO_No_Error = 5 |
13943 | }; |
13944 | } |
13945 | /// Diagnose invalid operand for address of operations. |
13946 | /// |
13947 | /// \param Type The type of operand which cannot have its address taken. |
13948 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, |
13949 | Expr *E, unsigned Type) { |
13950 | S.Diag(Loc, DiagID: diag::err_typecheck_address_of) << Type << E->getSourceRange(); |
13951 | } |
13952 | |
13953 | bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, |
13954 | const Expr *Op, |
13955 | const CXXMethodDecl *MD) { |
13956 | const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens()); |
13957 | |
13958 | if (Op != DRE) |
13959 | return Diag(Loc: OpLoc, DiagID: diag::err_parens_pointer_member_function) |
13960 | << Op->getSourceRange(); |
13961 | |
13962 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. |
13963 | if (isa<CXXDestructorDecl>(Val: MD)) |
13964 | return Diag(Loc: OpLoc, DiagID: diag::err_typecheck_addrof_dtor) |
13965 | << DRE->getSourceRange(); |
13966 | |
13967 | if (DRE->getQualifier()) |
13968 | return false; |
13969 | |
13970 | if (MD->getParent()->getName().empty()) |
13971 | return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function) |
13972 | << DRE->getSourceRange(); |
13973 | |
13974 | SmallString<32> Str; |
13975 | StringRef Qual = (MD->getParent()->getName() + "::" ).toStringRef(Out&: Str); |
13976 | return Diag(Loc: OpLoc, DiagID: diag::err_unqualified_pointer_member_function) |
13977 | << DRE->getSourceRange() |
13978 | << FixItHint::CreateInsertion(InsertionLoc: DRE->getSourceRange().getBegin(), Code: Qual); |
13979 | } |
13980 | |
13981 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { |
13982 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ |
13983 | if (PTy->getKind() == BuiltinType::Overload) { |
13984 | Expr *E = OrigOp.get()->IgnoreParens(); |
13985 | if (!isa<OverloadExpr>(Val: E)) { |
13986 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); |
13987 | Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof_addrof_function) |
13988 | << OrigOp.get()->getSourceRange(); |
13989 | return QualType(); |
13990 | } |
13991 | |
13992 | OverloadExpr *Ovl = cast<OverloadExpr>(Val: E); |
13993 | if (isa<UnresolvedMemberExpr>(Val: Ovl)) |
13994 | if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) { |
13995 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
13996 | << OrigOp.get()->getSourceRange(); |
13997 | return QualType(); |
13998 | } |
13999 | |
14000 | return Context.OverloadTy; |
14001 | } |
14002 | |
14003 | if (PTy->getKind() == BuiltinType::UnknownAny) |
14004 | return Context.UnknownAnyTy; |
14005 | |
14006 | if (PTy->getKind() == BuiltinType::BoundMember) { |
14007 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
14008 | << OrigOp.get()->getSourceRange(); |
14009 | return QualType(); |
14010 | } |
14011 | |
14012 | OrigOp = CheckPlaceholderExpr(E: OrigOp.get()); |
14013 | if (OrigOp.isInvalid()) return QualType(); |
14014 | } |
14015 | |
14016 | if (OrigOp.get()->isTypeDependent()) |
14017 | return Context.DependentTy; |
14018 | |
14019 | assert(!OrigOp.get()->hasPlaceholderType()); |
14020 | |
14021 | // Make sure to ignore parentheses in subsequent checks |
14022 | Expr *op = OrigOp.get()->IgnoreParens(); |
14023 | |
14024 | // In OpenCL captures for blocks called as lambda functions |
14025 | // are located in the private address space. Blocks used in |
14026 | // enqueue_kernel can be located in a different address space |
14027 | // depending on a vendor implementation. Thus preventing |
14028 | // taking an address of the capture to avoid invalid AS casts. |
14029 | if (LangOpts.OpenCL) { |
14030 | auto* VarRef = dyn_cast<DeclRefExpr>(Val: op); |
14031 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { |
14032 | Diag(Loc: op->getExprLoc(), DiagID: diag::err_opencl_taking_address_capture); |
14033 | return QualType(); |
14034 | } |
14035 | } |
14036 | |
14037 | if (getLangOpts().C99) { |
14038 | // Implement C99-only parts of addressof rules. |
14039 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) { |
14040 | if (uOp->getOpcode() == UO_Deref) |
14041 | // Per C99 6.5.3.2, the address of a deref always returns a valid result |
14042 | // (assuming the deref expression is valid). |
14043 | return uOp->getSubExpr()->getType(); |
14044 | } |
14045 | // Technically, there should be a check for array subscript |
14046 | // expressions here, but the result of one is always an lvalue anyway. |
14047 | } |
14048 | ValueDecl *dcl = getPrimaryDecl(E: op); |
14049 | |
14050 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl)) |
14051 | if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
14052 | Loc: op->getBeginLoc())) |
14053 | return QualType(); |
14054 | |
14055 | Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context); |
14056 | unsigned AddressOfError = AO_No_Error; |
14057 | |
14058 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { |
14059 | bool sfinae = (bool)isSFINAEContext(); |
14060 | Diag(Loc: OpLoc, DiagID: isSFINAEContext() ? diag::err_typecheck_addrof_temporary |
14061 | : diag::ext_typecheck_addrof_temporary) |
14062 | << op->getType() << op->getSourceRange(); |
14063 | if (sfinae) |
14064 | return QualType(); |
14065 | // Materialize the temporary as an lvalue so that we can take its address. |
14066 | OrigOp = op = |
14067 | CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true); |
14068 | } else if (isa<ObjCSelectorExpr>(Val: op)) { |
14069 | return Context.getPointerType(T: op->getType()); |
14070 | } else if (lval == Expr::LV_MemberFunction) { |
14071 | // If it's an instance method, make a member pointer. |
14072 | // The expression must have exactly the form &A::foo. |
14073 | |
14074 | // If the underlying expression isn't a decl ref, give up. |
14075 | if (!isa<DeclRefExpr>(Val: op)) { |
14076 | Diag(Loc: OpLoc, DiagID: diag::err_invalid_form_pointer_member_function) |
14077 | << OrigOp.get()->getSourceRange(); |
14078 | return QualType(); |
14079 | } |
14080 | DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op); |
14081 | CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl()); |
14082 | |
14083 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
14084 | |
14085 | QualType MPTy = Context.getMemberPointerType( |
14086 | T: op->getType(), Cls: Context.getTypeDeclType(Decl: MD->getParent()).getTypePtr()); |
14087 | |
14088 | if (getLangOpts().PointerAuthCalls && MD->isVirtual() && |
14089 | !isUnevaluatedContext() && !MPTy->isDependentType()) { |
14090 | // When pointer authentication is enabled, argument and return types of |
14091 | // vitual member functions must be complete. This is because vitrual |
14092 | // member function pointers are implemented using virtual dispatch |
14093 | // thunks and the thunks cannot be emitted if the argument or return |
14094 | // types are incomplete. |
14095 | auto ReturnOrParamTypeIsIncomplete = [&](QualType T, |
14096 | SourceLocation DeclRefLoc, |
14097 | SourceLocation RetArgTypeLoc) { |
14098 | if (RequireCompleteType(Loc: DeclRefLoc, T, DiagID: diag::err_incomplete_type)) { |
14099 | Diag(Loc: DeclRefLoc, |
14100 | DiagID: diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret); |
14101 | Diag(Loc: RetArgTypeLoc, |
14102 | DiagID: diag::note_ptrauth_virtual_function_incomplete_arg_ret_type) |
14103 | << T; |
14104 | return true; |
14105 | } |
14106 | return false; |
14107 | }; |
14108 | QualType RetTy = MD->getReturnType(); |
14109 | bool IsIncomplete = |
14110 | !RetTy->isVoidType() && |
14111 | ReturnOrParamTypeIsIncomplete( |
14112 | RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin()); |
14113 | for (auto *PVD : MD->parameters()) |
14114 | IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc, |
14115 | PVD->getBeginLoc()); |
14116 | if (IsIncomplete) |
14117 | return QualType(); |
14118 | } |
14119 | |
14120 | // Under the MS ABI, lock down the inheritance model now. |
14121 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
14122 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
14123 | return MPTy; |
14124 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { |
14125 | // C99 6.5.3.2p1 |
14126 | // The operand must be either an l-value or a function designator |
14127 | if (!op->getType()->isFunctionType()) { |
14128 | // Use a special diagnostic for loads from property references. |
14129 | if (isa<PseudoObjectExpr>(Val: op)) { |
14130 | AddressOfError = AO_Property_Expansion; |
14131 | } else { |
14132 | Diag(Loc: OpLoc, DiagID: diag::err_typecheck_invalid_lvalue_addrof) |
14133 | << op->getType() << op->getSourceRange(); |
14134 | return QualType(); |
14135 | } |
14136 | } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) { |
14137 | if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl())) |
14138 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
14139 | } |
14140 | |
14141 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 |
14142 | // The operand cannot be a bit-field |
14143 | AddressOfError = AO_Bit_Field; |
14144 | } else if (op->getObjectKind() == OK_VectorComponent) { |
14145 | // The operand cannot be an element of a vector |
14146 | AddressOfError = AO_Vector_Element; |
14147 | } else if (op->getObjectKind() == OK_MatrixComponent) { |
14148 | // The operand cannot be an element of a matrix. |
14149 | AddressOfError = AO_Matrix_Element; |
14150 | } else if (dcl) { // C99 6.5.3.2p1 |
14151 | // We have an lvalue with a decl. Make sure the decl is not declared |
14152 | // with the register storage-class specifier. |
14153 | if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) { |
14154 | // in C++ it is not error to take address of a register |
14155 | // variable (c++03 7.1.1P3) |
14156 | if (vd->getStorageClass() == SC_Register && |
14157 | !getLangOpts().CPlusPlus) { |
14158 | AddressOfError = AO_Register_Variable; |
14159 | } |
14160 | } else if (isa<MSPropertyDecl>(Val: dcl)) { |
14161 | AddressOfError = AO_Property_Expansion; |
14162 | } else if (isa<FunctionTemplateDecl>(Val: dcl)) { |
14163 | return Context.OverloadTy; |
14164 | } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) { |
14165 | // Okay: we can take the address of a field. |
14166 | // Could be a pointer to member, though, if there is an explicit |
14167 | // scope qualifier for the class. |
14168 | |
14169 | // [C++26] [expr.prim.id.general] |
14170 | // If an id-expression E denotes a non-static non-type member |
14171 | // of some class C [...] and if E is a qualified-id, E is |
14172 | // not the un-parenthesized operand of the unary & operator [...] |
14173 | // the id-expression is transformed into a class member access expression. |
14174 | if (isa<DeclRefExpr>(Val: op) && cast<DeclRefExpr>(Val: op)->getQualifier() && |
14175 | !isa<ParenExpr>(Val: OrigOp.get())) { |
14176 | DeclContext *Ctx = dcl->getDeclContext(); |
14177 | if (Ctx && Ctx->isRecord()) { |
14178 | if (dcl->getType()->isReferenceType()) { |
14179 | Diag(Loc: OpLoc, |
14180 | DiagID: diag::err_cannot_form_pointer_to_member_of_reference_type) |
14181 | << dcl->getDeclName() << dcl->getType(); |
14182 | return QualType(); |
14183 | } |
14184 | |
14185 | while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion()) |
14186 | Ctx = Ctx->getParent(); |
14187 | |
14188 | QualType MPTy = Context.getMemberPointerType( |
14189 | T: op->getType(), |
14190 | Cls: Context.getTypeDeclType(Decl: cast<RecordDecl>(Val: Ctx)).getTypePtr()); |
14191 | // Under the MS ABI, lock down the inheritance model now. |
14192 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
14193 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
14194 | return MPTy; |
14195 | } |
14196 | } |
14197 | } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, |
14198 | MSGuidDecl, UnnamedGlobalConstantDecl>(Val: dcl)) |
14199 | llvm_unreachable("Unknown/unexpected decl type" ); |
14200 | } |
14201 | |
14202 | if (AddressOfError != AO_No_Error) { |
14203 | diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError); |
14204 | return QualType(); |
14205 | } |
14206 | |
14207 | if (lval == Expr::LV_IncompleteVoidType) { |
14208 | // Taking the address of a void variable is technically illegal, but we |
14209 | // allow it in cases which are otherwise valid. |
14210 | // Example: "extern void x; void* y = &x;". |
14211 | Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_addrof_void) << op->getSourceRange(); |
14212 | } |
14213 | |
14214 | // If the operand has type "type", the result has type "pointer to type". |
14215 | if (op->getType()->isObjCObjectType()) |
14216 | return Context.getObjCObjectPointerType(OIT: op->getType()); |
14217 | |
14218 | // Cannot take the address of WebAssembly references or tables. |
14219 | if (Context.getTargetInfo().getTriple().isWasm()) { |
14220 | QualType OpTy = op->getType(); |
14221 | if (OpTy.isWebAssemblyReferenceType()) { |
14222 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_ca_reference) |
14223 | << 1 << OrigOp.get()->getSourceRange(); |
14224 | return QualType(); |
14225 | } |
14226 | if (OpTy->isWebAssemblyTableType()) { |
14227 | Diag(Loc: OpLoc, DiagID: diag::err_wasm_table_pr) |
14228 | << 1 << OrigOp.get()->getSourceRange(); |
14229 | return QualType(); |
14230 | } |
14231 | } |
14232 | |
14233 | CheckAddressOfPackedMember(rhs: op); |
14234 | |
14235 | return Context.getPointerType(T: op->getType()); |
14236 | } |
14237 | |
14238 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { |
14239 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp); |
14240 | if (!DRE) |
14241 | return; |
14242 | const Decl *D = DRE->getDecl(); |
14243 | if (!D) |
14244 | return; |
14245 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D); |
14246 | if (!Param) |
14247 | return; |
14248 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Val: Param->getDeclContext())) |
14249 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) |
14250 | return; |
14251 | if (FunctionScopeInfo *FD = S.getCurFunction()) |
14252 | FD->ModifiedNonNullParams.insert(Ptr: Param); |
14253 | } |
14254 | |
14255 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). |
14256 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, |
14257 | SourceLocation OpLoc, |
14258 | bool IsAfterAmp = false) { |
14259 | ExprResult ConvResult = S.UsualUnaryConversions(E: Op); |
14260 | if (ConvResult.isInvalid()) |
14261 | return QualType(); |
14262 | Op = ConvResult.get(); |
14263 | QualType OpTy = Op->getType(); |
14264 | QualType Result; |
14265 | |
14266 | if (isa<CXXReinterpretCastExpr>(Val: Op)) { |
14267 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); |
14268 | S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true, |
14269 | Range: Op->getSourceRange()); |
14270 | } |
14271 | |
14272 | if (const PointerType *PT = OpTy->getAs<PointerType>()) |
14273 | { |
14274 | Result = PT->getPointeeType(); |
14275 | } |
14276 | else if (const ObjCObjectPointerType *OPT = |
14277 | OpTy->getAs<ObjCObjectPointerType>()) |
14278 | Result = OPT->getPointeeType(); |
14279 | else { |
14280 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
14281 | if (PR.isInvalid()) return QualType(); |
14282 | if (PR.get() != Op) |
14283 | return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc); |
14284 | } |
14285 | |
14286 | if (Result.isNull()) { |
14287 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_requires_pointer) |
14288 | << OpTy << Op->getSourceRange(); |
14289 | return QualType(); |
14290 | } |
14291 | |
14292 | if (Result->isVoidType()) { |
14293 | // C++ [expr.unary.op]p1: |
14294 | // [...] the expression to which [the unary * operator] is applied shall |
14295 | // be a pointer to an object type, or a pointer to a function type |
14296 | LangOptions LO = S.getLangOpts(); |
14297 | if (LO.CPlusPlus) |
14298 | S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_indirection_through_void_pointer_cpp) |
14299 | << OpTy << Op->getSourceRange(); |
14300 | else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) |
14301 | S.Diag(Loc: OpLoc, DiagID: diag::ext_typecheck_indirection_through_void_pointer) |
14302 | << OpTy << Op->getSourceRange(); |
14303 | } |
14304 | |
14305 | // Dereferences are usually l-values... |
14306 | VK = VK_LValue; |
14307 | |
14308 | // ...except that certain expressions are never l-values in C. |
14309 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) |
14310 | VK = VK_PRValue; |
14311 | |
14312 | return Result; |
14313 | } |
14314 | |
14315 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { |
14316 | BinaryOperatorKind Opc; |
14317 | switch (Kind) { |
14318 | default: llvm_unreachable("Unknown binop!" ); |
14319 | case tok::periodstar: Opc = BO_PtrMemD; break; |
14320 | case tok::arrowstar: Opc = BO_PtrMemI; break; |
14321 | case tok::star: Opc = BO_Mul; break; |
14322 | case tok::slash: Opc = BO_Div; break; |
14323 | case tok::percent: Opc = BO_Rem; break; |
14324 | case tok::plus: Opc = BO_Add; break; |
14325 | case tok::minus: Opc = BO_Sub; break; |
14326 | case tok::lessless: Opc = BO_Shl; break; |
14327 | case tok::greatergreater: Opc = BO_Shr; break; |
14328 | case tok::lessequal: Opc = BO_LE; break; |
14329 | case tok::less: Opc = BO_LT; break; |
14330 | case tok::greaterequal: Opc = BO_GE; break; |
14331 | case tok::greater: Opc = BO_GT; break; |
14332 | case tok::exclaimequal: Opc = BO_NE; break; |
14333 | case tok::equalequal: Opc = BO_EQ; break; |
14334 | case tok::spaceship: Opc = BO_Cmp; break; |
14335 | case tok::amp: Opc = BO_And; break; |
14336 | case tok::caret: Opc = BO_Xor; break; |
14337 | case tok::pipe: Opc = BO_Or; break; |
14338 | case tok::ampamp: Opc = BO_LAnd; break; |
14339 | case tok::pipepipe: Opc = BO_LOr; break; |
14340 | case tok::equal: Opc = BO_Assign; break; |
14341 | case tok::starequal: Opc = BO_MulAssign; break; |
14342 | case tok::slashequal: Opc = BO_DivAssign; break; |
14343 | case tok::percentequal: Opc = BO_RemAssign; break; |
14344 | case tok::plusequal: Opc = BO_AddAssign; break; |
14345 | case tok::minusequal: Opc = BO_SubAssign; break; |
14346 | case tok::lesslessequal: Opc = BO_ShlAssign; break; |
14347 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; |
14348 | case tok::ampequal: Opc = BO_AndAssign; break; |
14349 | case tok::caretequal: Opc = BO_XorAssign; break; |
14350 | case tok::pipeequal: Opc = BO_OrAssign; break; |
14351 | case tok::comma: Opc = BO_Comma; break; |
14352 | } |
14353 | return Opc; |
14354 | } |
14355 | |
14356 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( |
14357 | tok::TokenKind Kind) { |
14358 | UnaryOperatorKind Opc; |
14359 | switch (Kind) { |
14360 | default: llvm_unreachable("Unknown unary op!" ); |
14361 | case tok::plusplus: Opc = UO_PreInc; break; |
14362 | case tok::minusminus: Opc = UO_PreDec; break; |
14363 | case tok::amp: Opc = UO_AddrOf; break; |
14364 | case tok::star: Opc = UO_Deref; break; |
14365 | case tok::plus: Opc = UO_Plus; break; |
14366 | case tok::minus: Opc = UO_Minus; break; |
14367 | case tok::tilde: Opc = UO_Not; break; |
14368 | case tok::exclaim: Opc = UO_LNot; break; |
14369 | case tok::kw___real: Opc = UO_Real; break; |
14370 | case tok::kw___imag: Opc = UO_Imag; break; |
14371 | case tok::kw___extension__: Opc = UO_Extension; break; |
14372 | } |
14373 | return Opc; |
14374 | } |
14375 | |
14376 | const FieldDecl * |
14377 | Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { |
14378 | // Explore the case for adding 'this->' to the LHS of a self assignment, very |
14379 | // common for setters. |
14380 | // struct A { |
14381 | // int X; |
14382 | // -void setX(int X) { X = X; } |
14383 | // +void setX(int X) { this->X = X; } |
14384 | // }; |
14385 | |
14386 | // Only consider parameters for self assignment fixes. |
14387 | if (!isa<ParmVarDecl>(Val: SelfAssigned)) |
14388 | return nullptr; |
14389 | const auto *Method = |
14390 | dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true)); |
14391 | if (!Method) |
14392 | return nullptr; |
14393 | |
14394 | const CXXRecordDecl *Parent = Method->getParent(); |
14395 | // In theory this is fixable if the lambda explicitly captures this, but |
14396 | // that's added complexity that's rarely going to be used. |
14397 | if (Parent->isLambda()) |
14398 | return nullptr; |
14399 | |
14400 | // FIXME: Use an actual Lookup operation instead of just traversing fields |
14401 | // in order to get base class fields. |
14402 | auto Field = |
14403 | llvm::find_if(Range: Parent->fields(), |
14404 | P: [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { |
14405 | return F->getDeclName() == Name; |
14406 | }); |
14407 | return (Field != Parent->field_end()) ? *Field : nullptr; |
14408 | } |
14409 | |
14410 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. |
14411 | /// This warning suppressed in the event of macro expansions. |
14412 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, |
14413 | SourceLocation OpLoc, bool IsBuiltin) { |
14414 | if (S.inTemplateInstantiation()) |
14415 | return; |
14416 | if (S.isUnevaluatedContext()) |
14417 | return; |
14418 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) |
14419 | return; |
14420 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); |
14421 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); |
14422 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr); |
14423 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr); |
14424 | if (!LHSDeclRef || !RHSDeclRef || |
14425 | LHSDeclRef->getLocation().isMacroID() || |
14426 | RHSDeclRef->getLocation().isMacroID()) |
14427 | return; |
14428 | const ValueDecl *LHSDecl = |
14429 | cast<ValueDecl>(Val: LHSDeclRef->getDecl()->getCanonicalDecl()); |
14430 | const ValueDecl *RHSDecl = |
14431 | cast<ValueDecl>(Val: RHSDeclRef->getDecl()->getCanonicalDecl()); |
14432 | if (LHSDecl != RHSDecl) |
14433 | return; |
14434 | if (LHSDecl->getType().isVolatileQualified()) |
14435 | return; |
14436 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
14437 | if (RefTy->getPointeeType().isVolatileQualified()) |
14438 | return; |
14439 | |
14440 | auto Diag = S.Diag(Loc: OpLoc, DiagID: IsBuiltin ? diag::warn_self_assignment_builtin |
14441 | : diag::warn_self_assignment_overloaded) |
14442 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() |
14443 | << RHSExpr->getSourceRange(); |
14444 | if (const FieldDecl *SelfAssignField = |
14445 | S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl)) |
14446 | Diag << 1 << SelfAssignField |
14447 | << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->" ); |
14448 | else |
14449 | Diag << 0; |
14450 | } |
14451 | |
14452 | /// Check if a bitwise-& is performed on an Objective-C pointer. This |
14453 | /// is usually indicative of introspection within the Objective-C pointer. |
14454 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, |
14455 | SourceLocation OpLoc) { |
14456 | if (!S.getLangOpts().ObjC) |
14457 | return; |
14458 | |
14459 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; |
14460 | const Expr *LHS = L.get(); |
14461 | const Expr *RHS = R.get(); |
14462 | |
14463 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
14464 | ObjCPointerExpr = LHS; |
14465 | OtherExpr = RHS; |
14466 | } |
14467 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
14468 | ObjCPointerExpr = RHS; |
14469 | OtherExpr = LHS; |
14470 | } |
14471 | |
14472 | // This warning is deliberately made very specific to reduce false |
14473 | // positives with logic that uses '&' for hashing. This logic mainly |
14474 | // looks for code trying to introspect into tagged pointers, which |
14475 | // code should generally never do. |
14476 | if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) { |
14477 | unsigned Diag = diag::warn_objc_pointer_masking; |
14478 | // Determine if we are introspecting the result of performSelectorXXX. |
14479 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); |
14480 | // Special case messages to -performSelector and friends, which |
14481 | // can return non-pointer values boxed in a pointer value. |
14482 | // Some clients may wish to silence warnings in this subcase. |
14483 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) { |
14484 | Selector S = ME->getSelector(); |
14485 | StringRef SelArg0 = S.getNameForSlot(argIndex: 0); |
14486 | if (SelArg0.starts_with(Prefix: "performSelector" )) |
14487 | Diag = diag::warn_objc_pointer_masking_performSelector; |
14488 | } |
14489 | |
14490 | S.Diag(Loc: OpLoc, DiagID: Diag) |
14491 | << ObjCPointerExpr->getSourceRange(); |
14492 | } |
14493 | } |
14494 | |
14495 | static NamedDecl *getDeclFromExpr(Expr *E) { |
14496 | if (!E) |
14497 | return nullptr; |
14498 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
14499 | return DRE->getDecl(); |
14500 | if (auto *ME = dyn_cast<MemberExpr>(Val: E)) |
14501 | return ME->getMemberDecl(); |
14502 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: E)) |
14503 | return IRE->getDecl(); |
14504 | return nullptr; |
14505 | } |
14506 | |
14507 | // This helper function promotes a binary operator's operands (which are of a |
14508 | // half vector type) to a vector of floats and then truncates the result to |
14509 | // a vector of either half or short. |
14510 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, |
14511 | BinaryOperatorKind Opc, QualType ResultTy, |
14512 | ExprValueKind VK, ExprObjectKind OK, |
14513 | bool IsCompAssign, SourceLocation OpLoc, |
14514 | FPOptionsOverride FPFeatures) { |
14515 | auto &Context = S.getASTContext(); |
14516 | assert((isVector(ResultTy, Context.HalfTy) || |
14517 | isVector(ResultTy, Context.ShortTy)) && |
14518 | "Result must be a vector of half or short" ); |
14519 | assert(isVector(LHS.get()->getType(), Context.HalfTy) && |
14520 | isVector(RHS.get()->getType(), Context.HalfTy) && |
14521 | "both operands expected to be a half vector" ); |
14522 | |
14523 | RHS = convertVector(E: RHS.get(), ElementType: Context.FloatTy, S); |
14524 | QualType BinOpResTy = RHS.get()->getType(); |
14525 | |
14526 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, |
14527 | // change BinOpResTy to a vector of ints. |
14528 | if (isVector(QT: ResultTy, ElementType: Context.ShortTy)) |
14529 | BinOpResTy = S.GetSignedVectorType(V: BinOpResTy); |
14530 | |
14531 | if (IsCompAssign) |
14532 | return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
14533 | ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures, |
14534 | CompLHSType: BinOpResTy, CompResultType: BinOpResTy); |
14535 | |
14536 | LHS = convertVector(E: LHS.get(), ElementType: Context.FloatTy, S); |
14537 | auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
14538 | ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures); |
14539 | return convertVector(E: BO, ElementType: ResultTy->castAs<VectorType>()->getElementType(), S); |
14540 | } |
14541 | |
14542 | static std::pair<ExprResult, ExprResult> |
14543 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, |
14544 | Expr *RHSExpr) { |
14545 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
14546 | if (!S.Context.isDependenceAllowed()) { |
14547 | // C cannot handle TypoExpr nodes on either side of a binop because it |
14548 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
14549 | // been dealt with before checking the operands. |
14550 | LHS = S.CorrectDelayedTyposInExpr(ER: LHS); |
14551 | RHS = S.CorrectDelayedTyposInExpr( |
14552 | ER: RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, |
14553 | Filter: [Opc, LHS](Expr *E) { |
14554 | if (Opc != BO_Assign) |
14555 | return ExprResult(E); |
14556 | // Avoid correcting the RHS to the same Expr as the LHS. |
14557 | Decl *D = getDeclFromExpr(E); |
14558 | return (D && D == getDeclFromExpr(E: LHS.get())) ? ExprError() : E; |
14559 | }); |
14560 | } |
14561 | return std::make_pair(x&: LHS, y&: RHS); |
14562 | } |
14563 | |
14564 | /// Returns true if conversion between vectors of halfs and vectors of floats |
14565 | /// is needed. |
14566 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, |
14567 | Expr *E0, Expr *E1 = nullptr) { |
14568 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || |
14569 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) |
14570 | return false; |
14571 | |
14572 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { |
14573 | QualType Ty = E->IgnoreImplicit()->getType(); |
14574 | |
14575 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h |
14576 | // to vectors of floats. Although the element type of the vectors is __fp16, |
14577 | // the vectors shouldn't be treated as storage-only types. See the |
14578 | // discussion here: https://reviews.llvm.org/rG825235c140e7 |
14579 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
14580 | if (VT->getVectorKind() == VectorKind::Neon) |
14581 | return false; |
14582 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; |
14583 | } |
14584 | return false; |
14585 | }; |
14586 | |
14587 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); |
14588 | } |
14589 | |
14590 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, |
14591 | BinaryOperatorKind Opc, |
14592 | Expr *LHSExpr, Expr *RHSExpr) { |
14593 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) { |
14594 | // The syntax only allows initializer lists on the RHS of assignment, |
14595 | // so we don't need to worry about accepting invalid code for |
14596 | // non-assignment operators. |
14597 | // C++11 5.17p9: |
14598 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning |
14599 | // of x = {} is x = T(). |
14600 | InitializationKind Kind = InitializationKind::CreateDirectList( |
14601 | InitLoc: RHSExpr->getBeginLoc(), LBraceLoc: RHSExpr->getBeginLoc(), RBraceLoc: RHSExpr->getEndLoc()); |
14602 | InitializedEntity Entity = |
14603 | InitializedEntity::InitializeTemporary(Type: LHSExpr->getType()); |
14604 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); |
14605 | ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr); |
14606 | if (Init.isInvalid()) |
14607 | return Init; |
14608 | RHSExpr = Init.get(); |
14609 | } |
14610 | |
14611 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
14612 | QualType ResultTy; // Result type of the binary operator. |
14613 | // The following two variables are used for compound assignment operators |
14614 | QualType CompLHSTy; // Type of LHS after promotions for computation |
14615 | QualType CompResultTy; // Type of computation result |
14616 | ExprValueKind VK = VK_PRValue; |
14617 | ExprObjectKind OK = OK_Ordinary; |
14618 | bool ConvertHalfVec = false; |
14619 | |
14620 | std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr); |
14621 | if (!LHS.isUsable() || !RHS.isUsable()) |
14622 | return ExprError(); |
14623 | |
14624 | if (getLangOpts().OpenCL) { |
14625 | QualType LHSTy = LHSExpr->getType(); |
14626 | QualType RHSTy = RHSExpr->getType(); |
14627 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by |
14628 | // the ATOMIC_VAR_INIT macro. |
14629 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { |
14630 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
14631 | if (BO_Assign == Opc) |
14632 | Diag(Loc: OpLoc, DiagID: diag::err_opencl_atomic_init) << 0 << SR; |
14633 | else |
14634 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
14635 | return ExprError(); |
14636 | } |
14637 | |
14638 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
14639 | // only with a builtin functions and therefore should be disallowed here. |
14640 | if (LHSTy->isImageType() || RHSTy->isImageType() || |
14641 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || |
14642 | LHSTy->isPipeType() || RHSTy->isPipeType() || |
14643 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { |
14644 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
14645 | return ExprError(); |
14646 | } |
14647 | } |
14648 | |
14649 | checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
14650 | checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
14651 | |
14652 | switch (Opc) { |
14653 | case BO_Assign: |
14654 | ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc); |
14655 | if (getLangOpts().CPlusPlus && |
14656 | LHS.get()->getObjectKind() != OK_ObjCProperty) { |
14657 | VK = LHS.get()->getValueKind(); |
14658 | OK = LHS.get()->getObjectKind(); |
14659 | } |
14660 | if (!ResultTy.isNull()) { |
14661 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
14662 | DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc); |
14663 | |
14664 | // Avoid copying a block to the heap if the block is assigned to a local |
14665 | // auto variable that is declared in the same scope as the block. This |
14666 | // optimization is unsafe if the local variable is declared in an outer |
14667 | // scope. For example: |
14668 | // |
14669 | // BlockTy b; |
14670 | // { |
14671 | // b = ^{...}; |
14672 | // } |
14673 | // // It is unsafe to invoke the block here if it wasn't copied to the |
14674 | // // heap. |
14675 | // b(); |
14676 | |
14677 | if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens())) |
14678 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens())) |
14679 | if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) |
14680 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(D: VD)) |
14681 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); |
14682 | |
14683 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
14684 | checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(), |
14685 | UseContext: NTCUC_Assignment, NonTrivialKind: NTCUK_Copy); |
14686 | } |
14687 | RecordModifiableNonNullParam(S&: *this, Exp: LHS.get()); |
14688 | break; |
14689 | case BO_PtrMemD: |
14690 | case BO_PtrMemI: |
14691 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, |
14692 | isIndirect: Opc == BO_PtrMemI); |
14693 | break; |
14694 | case BO_Mul: |
14695 | case BO_Div: |
14696 | ConvertHalfVec = true; |
14697 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: false, |
14698 | IsDiv: Opc == BO_Div); |
14699 | break; |
14700 | case BO_Rem: |
14701 | ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc); |
14702 | break; |
14703 | case BO_Add: |
14704 | ConvertHalfVec = true; |
14705 | ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc); |
14706 | break; |
14707 | case BO_Sub: |
14708 | ConvertHalfVec = true; |
14709 | ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc); |
14710 | break; |
14711 | case BO_Shl: |
14712 | case BO_Shr: |
14713 | ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc); |
14714 | break; |
14715 | case BO_LE: |
14716 | case BO_LT: |
14717 | case BO_GE: |
14718 | case BO_GT: |
14719 | ConvertHalfVec = true; |
14720 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
14721 | |
14722 | if (const auto *BI = dyn_cast<BinaryOperator>(Val: LHSExpr); |
14723 | BI && BI->isComparisonOp()) |
14724 | Diag(Loc: OpLoc, DiagID: diag::warn_consecutive_comparison); |
14725 | |
14726 | break; |
14727 | case BO_EQ: |
14728 | case BO_NE: |
14729 | ConvertHalfVec = true; |
14730 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
14731 | break; |
14732 | case BO_Cmp: |
14733 | ConvertHalfVec = true; |
14734 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
14735 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); |
14736 | break; |
14737 | case BO_And: |
14738 | checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc); |
14739 | [[fallthrough]]; |
14740 | case BO_Xor: |
14741 | case BO_Or: |
14742 | ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
14743 | break; |
14744 | case BO_LAnd: |
14745 | case BO_LOr: |
14746 | ConvertHalfVec = true; |
14747 | ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc); |
14748 | break; |
14749 | case BO_MulAssign: |
14750 | case BO_DivAssign: |
14751 | ConvertHalfVec = true; |
14752 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true, |
14753 | IsDiv: Opc == BO_DivAssign); |
14754 | CompLHSTy = CompResultTy; |
14755 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14756 | ResultTy = |
14757 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14758 | break; |
14759 | case BO_RemAssign: |
14760 | CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true); |
14761 | CompLHSTy = CompResultTy; |
14762 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14763 | ResultTy = |
14764 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14765 | break; |
14766 | case BO_AddAssign: |
14767 | ConvertHalfVec = true; |
14768 | CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy); |
14769 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14770 | ResultTy = |
14771 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14772 | break; |
14773 | case BO_SubAssign: |
14774 | ConvertHalfVec = true; |
14775 | CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, CompLHSTy: &CompLHSTy); |
14776 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14777 | ResultTy = |
14778 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14779 | break; |
14780 | case BO_ShlAssign: |
14781 | case BO_ShrAssign: |
14782 | CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true); |
14783 | CompLHSTy = CompResultTy; |
14784 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14785 | ResultTy = |
14786 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14787 | break; |
14788 | case BO_AndAssign: |
14789 | case BO_OrAssign: // fallthrough |
14790 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
14791 | [[fallthrough]]; |
14792 | case BO_XorAssign: |
14793 | CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
14794 | CompLHSTy = CompResultTy; |
14795 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
14796 | ResultTy = |
14797 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
14798 | break; |
14799 | case BO_Comma: |
14800 | ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc); |
14801 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { |
14802 | VK = RHS.get()->getValueKind(); |
14803 | OK = RHS.get()->getObjectKind(); |
14804 | } |
14805 | break; |
14806 | } |
14807 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) |
14808 | return ExprError(); |
14809 | |
14810 | // Some of the binary operations require promoting operands of half vector to |
14811 | // float vectors and truncating the result back to half vector. For now, we do |
14812 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or |
14813 | // arm64). |
14814 | assert( |
14815 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == |
14816 | isVector(LHS.get()->getType(), Context.HalfTy)) && |
14817 | "both sides are half vectors or neither sides are" ); |
14818 | ConvertHalfVec = |
14819 | needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get()); |
14820 | |
14821 | // Check for array bounds violations for both sides of the BinaryOperator |
14822 | CheckArrayAccess(E: LHS.get()); |
14823 | CheckArrayAccess(E: RHS.get()); |
14824 | |
14825 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) { |
14826 | NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope, |
14827 | Name: &Context.Idents.get(Name: "object_setClass" ), |
14828 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
14829 | if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) { |
14830 | SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
14831 | Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign) |
14832 | << FixItHint::CreateInsertion(InsertionLoc: LHS.get()->getBeginLoc(), |
14833 | Code: "object_setClass(" ) |
14834 | << FixItHint::CreateReplacement(RemoveRange: SourceRange(OISA->getOpLoc(), OpLoc), |
14835 | Code: "," ) |
14836 | << FixItHint::CreateInsertion(InsertionLoc: RHSLocEnd, Code: ")" ); |
14837 | } |
14838 | else |
14839 | Diag(Loc: LHS.get()->getExprLoc(), DiagID: diag::warn_objc_isa_assign); |
14840 | } |
14841 | else if (const ObjCIvarRefExpr *OIRE = |
14842 | dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts())) |
14843 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get()); |
14844 | |
14845 | // Opc is not a compound assignment if CompResultTy is null. |
14846 | if (CompResultTy.isNull()) { |
14847 | if (ConvertHalfVec) |
14848 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false, |
14849 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
14850 | return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, |
14851 | VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
14852 | } |
14853 | |
14854 | // Handle compound assignments. |
14855 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != |
14856 | OK_ObjCProperty) { |
14857 | VK = VK_LValue; |
14858 | OK = LHS.get()->getObjectKind(); |
14859 | } |
14860 | |
14861 | // The LHS is not converted to the result type for fixed-point compound |
14862 | // assignment as the common type is computed on demand. Reset the CompLHSTy |
14863 | // to the LHS type we would have gotten after unary conversions. |
14864 | if (CompResultTy->isFixedPointType()) |
14865 | CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType(); |
14866 | |
14867 | if (ConvertHalfVec) |
14868 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true, |
14869 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
14870 | |
14871 | return CompoundAssignOperator::Create( |
14872 | C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc, |
14873 | FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy); |
14874 | } |
14875 | |
14876 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison |
14877 | /// operators are mixed in a way that suggests that the programmer forgot that |
14878 | /// comparison operators have higher precedence. The most typical example of |
14879 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". |
14880 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, |
14881 | SourceLocation OpLoc, Expr *LHSExpr, |
14882 | Expr *RHSExpr) { |
14883 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr); |
14884 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr); |
14885 | |
14886 | // Check that one of the sides is a comparison operator and the other isn't. |
14887 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); |
14888 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); |
14889 | if (isLeftComp == isRightComp) |
14890 | return; |
14891 | |
14892 | // Bitwise operations are sometimes used as eager logical ops. |
14893 | // Don't diagnose this. |
14894 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); |
14895 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); |
14896 | if (isLeftBitwise || isRightBitwise) |
14897 | return; |
14898 | |
14899 | SourceRange DiagRange = isLeftComp |
14900 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) |
14901 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); |
14902 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); |
14903 | SourceRange ParensRange = |
14904 | isLeftComp |
14905 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) |
14906 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); |
14907 | |
14908 | Self.Diag(Loc: OpLoc, DiagID: diag::warn_precedence_bitwise_rel) |
14909 | << DiagRange << BinaryOperator::getOpcodeStr(Op: Opc) << OpStr; |
14910 | SuggestParentheses(Self, Loc: OpLoc, |
14911 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) << OpStr, |
14912 | ParenRange: (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); |
14913 | SuggestParentheses(Self, Loc: OpLoc, |
14914 | Note: Self.PDiag(DiagID: diag::note_precedence_bitwise_first) |
14915 | << BinaryOperator::getOpcodeStr(Op: Opc), |
14916 | ParenRange: ParensRange); |
14917 | } |
14918 | |
14919 | /// It accepts a '&&' expr that is inside a '||' one. |
14920 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression |
14921 | /// in parentheses. |
14922 | static void |
14923 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, |
14924 | BinaryOperator *Bop) { |
14925 | assert(Bop->getOpcode() == BO_LAnd); |
14926 | Self.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_logical_and_in_logical_or) |
14927 | << Bop->getSourceRange() << OpLoc; |
14928 | SuggestParentheses(Self, Loc: Bop->getOperatorLoc(), |
14929 | Note: Self.PDiag(DiagID: diag::note_precedence_silence) |
14930 | << Bop->getOpcodeStr(), |
14931 | ParenRange: Bop->getSourceRange()); |
14932 | } |
14933 | |
14934 | /// Look for '&&' in the left hand of a '||' expr. |
14935 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, |
14936 | Expr *LHSExpr, Expr *RHSExpr) { |
14937 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) { |
14938 | if (Bop->getOpcode() == BO_LAnd) { |
14939 | // If it's "string_literal && a || b" don't warn since the precedence |
14940 | // doesn't matter. |
14941 | if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts())) |
14942 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
14943 | } else if (Bop->getOpcode() == BO_LOr) { |
14944 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) { |
14945 | // If it's "a || b && string_literal || c" we didn't warn earlier for |
14946 | // "a || b && string_literal", but warn now. |
14947 | if (RBop->getOpcode() == BO_LAnd && |
14948 | isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts())) |
14949 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop); |
14950 | } |
14951 | } |
14952 | } |
14953 | } |
14954 | |
14955 | /// Look for '&&' in the right hand of a '||' expr. |
14956 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, |
14957 | Expr *LHSExpr, Expr *RHSExpr) { |
14958 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) { |
14959 | if (Bop->getOpcode() == BO_LAnd) { |
14960 | // If it's "a || b && string_literal" don't warn since the precedence |
14961 | // doesn't matter. |
14962 | if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts())) |
14963 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
14964 | } |
14965 | } |
14966 | } |
14967 | |
14968 | /// Look for bitwise op in the left or right hand of a bitwise op with |
14969 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps |
14970 | /// the '&' expression in parentheses. |
14971 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, |
14972 | SourceLocation OpLoc, Expr *SubExpr) { |
14973 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
14974 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { |
14975 | S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_bitwise_op_in_bitwise_op) |
14976 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Op: Opc) |
14977 | << Bop->getSourceRange() << OpLoc; |
14978 | SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(), |
14979 | Note: S.PDiag(DiagID: diag::note_precedence_silence) |
14980 | << Bop->getOpcodeStr(), |
14981 | ParenRange: Bop->getSourceRange()); |
14982 | } |
14983 | } |
14984 | } |
14985 | |
14986 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, |
14987 | Expr *SubExpr, StringRef Shift) { |
14988 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
14989 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { |
14990 | StringRef Op = Bop->getOpcodeStr(); |
14991 | S.Diag(Loc: Bop->getOperatorLoc(), DiagID: diag::warn_addition_in_bitshift) |
14992 | << Bop->getSourceRange() << OpLoc << Shift << Op; |
14993 | SuggestParentheses(Self&: S, Loc: Bop->getOperatorLoc(), |
14994 | Note: S.PDiag(DiagID: diag::note_precedence_silence) << Op, |
14995 | ParenRange: Bop->getSourceRange()); |
14996 | } |
14997 | } |
14998 | } |
14999 | |
15000 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, |
15001 | Expr *LHSExpr, Expr *RHSExpr) { |
15002 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr); |
15003 | if (!OCE) |
15004 | return; |
15005 | |
15006 | FunctionDecl *FD = OCE->getDirectCallee(); |
15007 | if (!FD || !FD->isOverloadedOperator()) |
15008 | return; |
15009 | |
15010 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); |
15011 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) |
15012 | return; |
15013 | |
15014 | S.Diag(Loc: OpLoc, DiagID: diag::warn_overloaded_shift_in_comparison) |
15015 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() |
15016 | << (Kind == OO_LessLess); |
15017 | SuggestParentheses(Self&: S, Loc: OCE->getOperatorLoc(), |
15018 | Note: S.PDiag(DiagID: diag::note_precedence_silence) |
15019 | << (Kind == OO_LessLess ? "<<" : ">>" ), |
15020 | ParenRange: OCE->getSourceRange()); |
15021 | SuggestParentheses( |
15022 | Self&: S, Loc: OpLoc, Note: S.PDiag(DiagID: diag::note_evaluate_comparison_first), |
15023 | ParenRange: SourceRange(OCE->getArg(Arg: 1)->getBeginLoc(), RHSExpr->getEndLoc())); |
15024 | } |
15025 | |
15026 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky |
15027 | /// precedence. |
15028 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, |
15029 | SourceLocation OpLoc, Expr *LHSExpr, |
15030 | Expr *RHSExpr){ |
15031 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". |
15032 | if (BinaryOperator::isBitwiseOp(Opc)) |
15033 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); |
15034 | |
15035 | // Diagnose "arg1 & arg2 | arg3" |
15036 | if ((Opc == BO_Or || Opc == BO_Xor) && |
15037 | !OpLoc.isMacroID()/* Don't warn in macros. */) { |
15038 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr); |
15039 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr); |
15040 | } |
15041 | |
15042 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. |
15043 | // We don't warn for 'assert(a || b && "bad")' since this is safe. |
15044 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { |
15045 | DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15046 | DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15047 | } |
15048 | |
15049 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext())) |
15050 | || Opc == BO_Shr) { |
15051 | StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc); |
15052 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift); |
15053 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift); |
15054 | } |
15055 | |
15056 | // Warn on overloaded shift operators and comparisons, such as: |
15057 | // cout << 5 == 4; |
15058 | if (BinaryOperator::isComparisonOp(Opc)) |
15059 | DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15060 | } |
15061 | |
15062 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, |
15063 | tok::TokenKind Kind, |
15064 | Expr *LHSExpr, Expr *RHSExpr) { |
15065 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); |
15066 | assert(LHSExpr && "ActOnBinOp(): missing left expression" ); |
15067 | assert(RHSExpr && "ActOnBinOp(): missing right expression" ); |
15068 | |
15069 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" |
15070 | DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr); |
15071 | |
15072 | return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr); |
15073 | } |
15074 | |
15075 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, |
15076 | UnresolvedSetImpl &Functions) { |
15077 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); |
15078 | if (OverOp != OO_None && OverOp != OO_Equal) |
15079 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
15080 | |
15081 | // In C++20 onwards, we may have a second operator to look up. |
15082 | if (getLangOpts().CPlusPlus20) { |
15083 | if (OverloadedOperatorKind = getRewrittenOverloadedOperator(Kind: OverOp)) |
15084 | LookupOverloadedOperatorName(Op: ExtraOp, S, Functions); |
15085 | } |
15086 | } |
15087 | |
15088 | /// Build an overloaded binary operator expression in the given scope. |
15089 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, |
15090 | BinaryOperatorKind Opc, |
15091 | Expr *LHS, Expr *RHS) { |
15092 | switch (Opc) { |
15093 | case BO_Assign: |
15094 | // In the non-overloaded case, we warn about self-assignment (x = x) for |
15095 | // both simple assignment and certain compound assignments where algebra |
15096 | // tells us the operation yields a constant result. When the operator is |
15097 | // overloaded, we can't do the latter because we don't want to assume that |
15098 | // those algebraic identities still apply; for example, a path-building |
15099 | // library might use operator/= to append paths. But it's still reasonable |
15100 | // to assume that simple assignment is just moving/copying values around |
15101 | // and so self-assignment is likely a bug. |
15102 | DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false); |
15103 | [[fallthrough]]; |
15104 | case BO_DivAssign: |
15105 | case BO_RemAssign: |
15106 | case BO_SubAssign: |
15107 | case BO_AndAssign: |
15108 | case BO_OrAssign: |
15109 | case BO_XorAssign: |
15110 | CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S); |
15111 | break; |
15112 | default: |
15113 | break; |
15114 | } |
15115 | |
15116 | // Find all of the overloaded operators visible from this point. |
15117 | UnresolvedSet<16> Functions; |
15118 | S.LookupBinOp(S: Sc, OpLoc, Opc, Functions); |
15119 | |
15120 | // Build the (potentially-overloaded, potentially-dependent) |
15121 | // binary operation. |
15122 | return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS); |
15123 | } |
15124 | |
15125 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, |
15126 | BinaryOperatorKind Opc, |
15127 | Expr *LHSExpr, Expr *RHSExpr) { |
15128 | ExprResult LHS, RHS; |
15129 | std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr); |
15130 | if (!LHS.isUsable() || !RHS.isUsable()) |
15131 | return ExprError(); |
15132 | LHSExpr = LHS.get(); |
15133 | RHSExpr = RHS.get(); |
15134 | |
15135 | // We want to end up calling one of SemaPseudoObject::checkAssignment |
15136 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if |
15137 | // both expressions are overloadable or either is type-dependent), |
15138 | // or CreateBuiltinBinOp (in any other case). We also want to get |
15139 | // any placeholder types out of the way. |
15140 | |
15141 | // Handle pseudo-objects in the LHS. |
15142 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { |
15143 | // Assignments with a pseudo-object l-value need special analysis. |
15144 | if (pty->getKind() == BuiltinType::PseudoObject && |
15145 | BinaryOperator::isAssignmentOp(Opc)) |
15146 | return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr); |
15147 | |
15148 | // Don't resolve overloads if the other type is overloadable. |
15149 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { |
15150 | // We can't actually test that if we still have a placeholder, |
15151 | // though. Fortunately, none of the exceptions we see in that |
15152 | // code below are valid when the LHS is an overload set. Note |
15153 | // that an overload set can be dependently-typed, but it never |
15154 | // instantiates to having an overloadable type. |
15155 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
15156 | if (resolvedRHS.isInvalid()) return ExprError(); |
15157 | RHSExpr = resolvedRHS.get(); |
15158 | |
15159 | if (RHSExpr->isTypeDependent() || |
15160 | RHSExpr->getType()->isOverloadableType()) |
15161 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15162 | } |
15163 | |
15164 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function |
15165 | // template, diagnose the missing 'template' keyword instead of diagnosing |
15166 | // an invalid use of a bound member function. |
15167 | // |
15168 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due |
15169 | // to C++1z [over.over]/1.4, but we already checked for that case above. |
15170 | if (Opc == BO_LT && inTemplateInstantiation() && |
15171 | (pty->getKind() == BuiltinType::BoundMember || |
15172 | pty->getKind() == BuiltinType::Overload)) { |
15173 | auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr); |
15174 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && |
15175 | llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) { |
15176 | return isa<FunctionTemplateDecl>(Val: ND); |
15177 | })) { |
15178 | Diag(Loc: OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() |
15179 | : OE->getNameLoc(), |
15180 | DiagID: diag::err_template_kw_missing) |
15181 | << OE->getName().getAsString() << "" ; |
15182 | return ExprError(); |
15183 | } |
15184 | } |
15185 | |
15186 | ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr); |
15187 | if (LHS.isInvalid()) return ExprError(); |
15188 | LHSExpr = LHS.get(); |
15189 | } |
15190 | |
15191 | // Handle pseudo-objects in the RHS. |
15192 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { |
15193 | // An overload in the RHS can potentially be resolved by the type |
15194 | // being assigned to. |
15195 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { |
15196 | if (getLangOpts().CPlusPlus && |
15197 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
15198 | LHSExpr->getType()->isOverloadableType())) |
15199 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15200 | |
15201 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); |
15202 | } |
15203 | |
15204 | // Don't resolve overloads if the other type is overloadable. |
15205 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && |
15206 | LHSExpr->getType()->isOverloadableType()) |
15207 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15208 | |
15209 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
15210 | if (!resolvedRHS.isUsable()) return ExprError(); |
15211 | RHSExpr = resolvedRHS.get(); |
15212 | } |
15213 | |
15214 | if (getLangOpts().CPlusPlus) { |
15215 | // Otherwise, build an overloaded op if either expression is type-dependent |
15216 | // or has an overloadable type. |
15217 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
15218 | LHSExpr->getType()->isOverloadableType() || |
15219 | RHSExpr->getType()->isOverloadableType()) |
15220 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15221 | } |
15222 | |
15223 | if (getLangOpts().RecoveryAST && |
15224 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { |
15225 | assert(!getLangOpts().CPlusPlus); |
15226 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && |
15227 | "Should only occur in error-recovery path." ); |
15228 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
15229 | // C [6.15.16] p3: |
15230 | // An assignment expression has the value of the left operand after the |
15231 | // assignment, but is not an lvalue. |
15232 | return CompoundAssignOperator::Create( |
15233 | C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, |
15234 | ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary, |
15235 | opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15236 | QualType ResultType; |
15237 | switch (Opc) { |
15238 | case BO_Assign: |
15239 | ResultType = LHSExpr->getType().getUnqualifiedType(); |
15240 | break; |
15241 | case BO_LT: |
15242 | case BO_GT: |
15243 | case BO_LE: |
15244 | case BO_GE: |
15245 | case BO_EQ: |
15246 | case BO_NE: |
15247 | case BO_LAnd: |
15248 | case BO_LOr: |
15249 | // These operators have a fixed result type regardless of operands. |
15250 | ResultType = Context.IntTy; |
15251 | break; |
15252 | case BO_Comma: |
15253 | ResultType = RHSExpr->getType(); |
15254 | break; |
15255 | default: |
15256 | ResultType = Context.DependentTy; |
15257 | break; |
15258 | } |
15259 | return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType, |
15260 | VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc, |
15261 | FPFeatures: CurFPFeatureOverrides()); |
15262 | } |
15263 | |
15264 | // Build a built-in binary operation. |
15265 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); |
15266 | } |
15267 | |
15268 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { |
15269 | if (T.isNull() || T->isDependentType()) |
15270 | return false; |
15271 | |
15272 | if (!Ctx.isPromotableIntegerType(T)) |
15273 | return true; |
15274 | |
15275 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy); |
15276 | } |
15277 | |
15278 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, |
15279 | UnaryOperatorKind Opc, Expr *InputExpr, |
15280 | bool IsAfterAmp) { |
15281 | ExprResult Input = InputExpr; |
15282 | ExprValueKind VK = VK_PRValue; |
15283 | ExprObjectKind OK = OK_Ordinary; |
15284 | QualType resultType; |
15285 | bool CanOverflow = false; |
15286 | |
15287 | bool ConvertHalfVec = false; |
15288 | if (getLangOpts().OpenCL) { |
15289 | QualType Ty = InputExpr->getType(); |
15290 | // The only legal unary operation for atomics is '&'. |
15291 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || |
15292 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
15293 | // only with a builtin functions and therefore should be disallowed here. |
15294 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() |
15295 | || Ty->isBlockPointerType())) { |
15296 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15297 | << InputExpr->getType() |
15298 | << Input.get()->getSourceRange()); |
15299 | } |
15300 | } |
15301 | |
15302 | if (getLangOpts().HLSL && OpLoc.isValid()) { |
15303 | if (Opc == UO_AddrOf) |
15304 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 0); |
15305 | if (Opc == UO_Deref) |
15306 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 1); |
15307 | } |
15308 | |
15309 | if (InputExpr->isTypeDependent() && |
15310 | InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) { |
15311 | resultType = Context.DependentTy; |
15312 | } else { |
15313 | switch (Opc) { |
15314 | case UO_PreInc: |
15315 | case UO_PreDec: |
15316 | case UO_PostInc: |
15317 | case UO_PostDec: |
15318 | resultType = |
15319 | CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc, |
15320 | IsInc: Opc == UO_PreInc || Opc == UO_PostInc, |
15321 | IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec); |
15322 | CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType); |
15323 | break; |
15324 | case UO_AddrOf: |
15325 | resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc); |
15326 | CheckAddressOfNoDeref(E: InputExpr); |
15327 | RecordModifiableNonNullParam(S&: *this, Exp: InputExpr); |
15328 | break; |
15329 | case UO_Deref: { |
15330 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
15331 | if (Input.isInvalid()) |
15332 | return ExprError(); |
15333 | resultType = |
15334 | CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp); |
15335 | break; |
15336 | } |
15337 | case UO_Plus: |
15338 | case UO_Minus: |
15339 | CanOverflow = Opc == UO_Minus && |
15340 | isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType()); |
15341 | Input = UsualUnaryConversions(E: Input.get()); |
15342 | if (Input.isInvalid()) |
15343 | return ExprError(); |
15344 | // Unary plus and minus require promoting an operand of half vector to a |
15345 | // float vector and truncating the result back to a half vector. For now, |
15346 | // we do this only when HalfArgsAndReturns is set (that is, when the |
15347 | // target is arm or arm64). |
15348 | ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get()); |
15349 | |
15350 | // If the operand is a half vector, promote it to a float vector. |
15351 | if (ConvertHalfVec) |
15352 | Input = convertVector(E: Input.get(), ElementType: Context.FloatTy, S&: *this); |
15353 | resultType = Input.get()->getType(); |
15354 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 |
15355 | break; |
15356 | else if (resultType->isVectorType() && |
15357 | // The z vector extensions don't allow + or - with bool vectors. |
15358 | (!Context.getLangOpts().ZVector || |
15359 | resultType->castAs<VectorType>()->getVectorKind() != |
15360 | VectorKind::AltiVecBool)) |
15361 | break; |
15362 | else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and - |
15363 | break; |
15364 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 |
15365 | Opc == UO_Plus && resultType->isPointerType()) |
15366 | break; |
15367 | |
15368 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15369 | << resultType << Input.get()->getSourceRange()); |
15370 | |
15371 | case UO_Not: // bitwise complement |
15372 | Input = UsualUnaryConversions(E: Input.get()); |
15373 | if (Input.isInvalid()) |
15374 | return ExprError(); |
15375 | resultType = Input.get()->getType(); |
15376 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. |
15377 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) |
15378 | // C99 does not support '~' for complex conjugation. |
15379 | Diag(Loc: OpLoc, DiagID: diag::ext_integer_complement_complex) |
15380 | << resultType << Input.get()->getSourceRange(); |
15381 | else if (resultType->hasIntegerRepresentation()) |
15382 | break; |
15383 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { |
15384 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate |
15385 | // on vector float types. |
15386 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
15387 | if (!T->isIntegerType()) |
15388 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15389 | << resultType << Input.get()->getSourceRange()); |
15390 | } else { |
15391 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15392 | << resultType << Input.get()->getSourceRange()); |
15393 | } |
15394 | break; |
15395 | |
15396 | case UO_LNot: // logical negation |
15397 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). |
15398 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
15399 | if (Input.isInvalid()) |
15400 | return ExprError(); |
15401 | resultType = Input.get()->getType(); |
15402 | |
15403 | // Though we still have to promote half FP to float... |
15404 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { |
15405 | Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast) |
15406 | .get(); |
15407 | resultType = Context.FloatTy; |
15408 | } |
15409 | |
15410 | // WebAsembly tables can't be used in unary expressions. |
15411 | if (resultType->isPointerType() && |
15412 | resultType->getPointeeType().isWebAssemblyReferenceType()) { |
15413 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15414 | << resultType << Input.get()->getSourceRange()); |
15415 | } |
15416 | |
15417 | if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) { |
15418 | // C99 6.5.3.3p1: ok, fallthrough; |
15419 | if (Context.getLangOpts().CPlusPlus) { |
15420 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: |
15421 | // operand contextually converted to bool. |
15422 | Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy, |
15423 | CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType)); |
15424 | } else if (Context.getLangOpts().OpenCL && |
15425 | Context.getLangOpts().OpenCLVersion < 120) { |
15426 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
15427 | // operate on scalar float types. |
15428 | if (!resultType->isIntegerType() && !resultType->isPointerType()) |
15429 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15430 | << resultType << Input.get()->getSourceRange()); |
15431 | } |
15432 | } else if (resultType->isExtVectorType()) { |
15433 | if (Context.getLangOpts().OpenCL && |
15434 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { |
15435 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
15436 | // operate on vector float types. |
15437 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
15438 | if (!T->isIntegerType()) |
15439 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15440 | << resultType << Input.get()->getSourceRange()); |
15441 | } |
15442 | // Vector logical not returns the signed variant of the operand type. |
15443 | resultType = GetSignedVectorType(V: resultType); |
15444 | break; |
15445 | } else if (Context.getLangOpts().CPlusPlus && |
15446 | resultType->isVectorType()) { |
15447 | const VectorType *VTy = resultType->castAs<VectorType>(); |
15448 | if (VTy->getVectorKind() != VectorKind::Generic) |
15449 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15450 | << resultType << Input.get()->getSourceRange()); |
15451 | |
15452 | // Vector logical not returns the signed variant of the operand type. |
15453 | resultType = GetSignedVectorType(V: resultType); |
15454 | break; |
15455 | } else { |
15456 | return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_typecheck_unary_expr) |
15457 | << resultType << Input.get()->getSourceRange()); |
15458 | } |
15459 | |
15460 | // LNot always has type int. C99 6.5.3.3p5. |
15461 | // In C++, it's bool. C++ 5.3.1p8 |
15462 | resultType = Context.getLogicalOperationType(); |
15463 | break; |
15464 | case UO_Real: |
15465 | case UO_Imag: |
15466 | resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real); |
15467 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps |
15468 | // ordinary complex l-values to ordinary l-values and all other values to |
15469 | // r-values. |
15470 | if (Input.isInvalid()) |
15471 | return ExprError(); |
15472 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { |
15473 | if (Input.get()->isGLValue() && |
15474 | Input.get()->getObjectKind() == OK_Ordinary) |
15475 | VK = Input.get()->getValueKind(); |
15476 | } else if (!getLangOpts().CPlusPlus) { |
15477 | // In C, a volatile scalar is read by __imag. In C++, it is not. |
15478 | Input = DefaultLvalueConversion(E: Input.get()); |
15479 | } |
15480 | break; |
15481 | case UO_Extension: |
15482 | resultType = Input.get()->getType(); |
15483 | VK = Input.get()->getValueKind(); |
15484 | OK = Input.get()->getObjectKind(); |
15485 | break; |
15486 | case UO_Coawait: |
15487 | // It's unnecessary to represent the pass-through operator co_await in the |
15488 | // AST; just return the input expression instead. |
15489 | assert(!Input.get()->getType()->isDependentType() && |
15490 | "the co_await expression must be non-dependant before " |
15491 | "building operator co_await" ); |
15492 | return Input; |
15493 | } |
15494 | } |
15495 | if (resultType.isNull() || Input.isInvalid()) |
15496 | return ExprError(); |
15497 | |
15498 | // Check for array bounds violations in the operand of the UnaryOperator, |
15499 | // except for the '*' and '&' operators that have to be handled specially |
15500 | // by CheckArrayAccess (as there are special cases like &array[arraysize] |
15501 | // that are explicitly defined as valid by the standard). |
15502 | if (Opc != UO_AddrOf && Opc != UO_Deref) |
15503 | CheckArrayAccess(E: Input.get()); |
15504 | |
15505 | auto *UO = |
15506 | UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK, |
15507 | l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides()); |
15508 | |
15509 | if (Opc == UO_Deref && UO->getType()->hasAttr(AK: attr::NoDeref) && |
15510 | !isa<ArrayType>(Val: UO->getType().getDesugaredType(Context)) && |
15511 | !isUnevaluatedContext()) |
15512 | ExprEvalContexts.back().PossibleDerefs.insert(Ptr: UO); |
15513 | |
15514 | // Convert the result back to a half vector. |
15515 | if (ConvertHalfVec) |
15516 | return convertVector(E: UO, ElementType: Context.HalfTy, S&: *this); |
15517 | return UO; |
15518 | } |
15519 | |
15520 | bool Sema::isQualifiedMemberAccess(Expr *E) { |
15521 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
15522 | if (!DRE->getQualifier()) |
15523 | return false; |
15524 | |
15525 | ValueDecl *VD = DRE->getDecl(); |
15526 | if (!VD->isCXXClassMember()) |
15527 | return false; |
15528 | |
15529 | if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD)) |
15530 | return true; |
15531 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD)) |
15532 | return Method->isImplicitObjectMemberFunction(); |
15533 | |
15534 | return false; |
15535 | } |
15536 | |
15537 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) { |
15538 | if (!ULE->getQualifier()) |
15539 | return false; |
15540 | |
15541 | for (NamedDecl *D : ULE->decls()) { |
15542 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
15543 | if (Method->isImplicitObjectMemberFunction()) |
15544 | return true; |
15545 | } else { |
15546 | // Overload set does not contain methods. |
15547 | break; |
15548 | } |
15549 | } |
15550 | |
15551 | return false; |
15552 | } |
15553 | |
15554 | return false; |
15555 | } |
15556 | |
15557 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
15558 | UnaryOperatorKind Opc, Expr *Input, |
15559 | bool IsAfterAmp) { |
15560 | // First things first: handle placeholders so that the |
15561 | // overloaded-operator check considers the right type. |
15562 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { |
15563 | // Increment and decrement of pseudo-object references. |
15564 | if (pty->getKind() == BuiltinType::PseudoObject && |
15565 | UnaryOperator::isIncrementDecrementOp(Op: Opc)) |
15566 | return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input); |
15567 | |
15568 | // extension is always a builtin operator. |
15569 | if (Opc == UO_Extension) |
15570 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
15571 | |
15572 | // & gets special logic for several kinds of placeholder. |
15573 | // The builtin code knows what to do. |
15574 | if (Opc == UO_AddrOf && |
15575 | (pty->getKind() == BuiltinType::Overload || |
15576 | pty->getKind() == BuiltinType::UnknownAny || |
15577 | pty->getKind() == BuiltinType::BoundMember)) |
15578 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
15579 | |
15580 | // Anything else needs to be handled now. |
15581 | ExprResult Result = CheckPlaceholderExpr(E: Input); |
15582 | if (Result.isInvalid()) return ExprError(); |
15583 | Input = Result.get(); |
15584 | } |
15585 | |
15586 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && |
15587 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && |
15588 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) { |
15589 | // Find all of the overloaded operators visible from this point. |
15590 | UnresolvedSet<16> Functions; |
15591 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); |
15592 | if (S && OverOp != OO_None) |
15593 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
15594 | |
15595 | return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input); |
15596 | } |
15597 | |
15598 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp); |
15599 | } |
15600 | |
15601 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, |
15602 | Expr *Input, bool IsAfterAmp) { |
15603 | return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input, |
15604 | IsAfterAmp); |
15605 | } |
15606 | |
15607 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
15608 | LabelDecl *TheDecl) { |
15609 | TheDecl->markUsed(C&: Context); |
15610 | // Create the AST node. The address of a label always has type 'void*'. |
15611 | auto *Res = new (Context) AddrLabelExpr( |
15612 | OpLoc, LabLoc, TheDecl, Context.getPointerType(T: Context.VoidTy)); |
15613 | |
15614 | if (getCurFunction()) |
15615 | getCurFunction()->AddrLabels.push_back(Elt: Res); |
15616 | |
15617 | return Res; |
15618 | } |
15619 | |
15620 | void Sema::ActOnStartStmtExpr() { |
15621 | PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context); |
15622 | // Make sure we diagnose jumping into a statement expression. |
15623 | setFunctionHasBranchProtectedScope(); |
15624 | } |
15625 | |
15626 | void Sema::ActOnStmtExprError() { |
15627 | // Note that function is also called by TreeTransform when leaving a |
15628 | // StmtExpr scope without rebuilding anything. |
15629 | |
15630 | DiscardCleanupsInEvaluationContext(); |
15631 | PopExpressionEvaluationContext(); |
15632 | } |
15633 | |
15634 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, |
15635 | SourceLocation RPLoc) { |
15636 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S)); |
15637 | } |
15638 | |
15639 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
15640 | SourceLocation RPLoc, unsigned TemplateDepth) { |
15641 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!" ); |
15642 | CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt); |
15643 | |
15644 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
15645 | DiscardCleanupsInEvaluationContext(); |
15646 | assert(!Cleanup.exprNeedsCleanups() && |
15647 | "cleanups within StmtExpr not correctly bound!" ); |
15648 | PopExpressionEvaluationContext(); |
15649 | |
15650 | // FIXME: there are a variety of strange constraints to enforce here, for |
15651 | // example, it is not possible to goto into a stmt expression apparently. |
15652 | // More semantic analysis is needed. |
15653 | |
15654 | // If there are sub-stmts in the compound stmt, take the type of the last one |
15655 | // as the type of the stmtexpr. |
15656 | QualType Ty = Context.VoidTy; |
15657 | bool StmtExprMayBindToTemp = false; |
15658 | if (!Compound->body_empty()) { |
15659 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. |
15660 | if (const auto *LastStmt = |
15661 | dyn_cast<ValueStmt>(Val: Compound->getStmtExprResult())) { |
15662 | if (const Expr *Value = LastStmt->getExprStmt()) { |
15663 | StmtExprMayBindToTemp = true; |
15664 | Ty = Value->getType(); |
15665 | } |
15666 | } |
15667 | } |
15668 | |
15669 | // FIXME: Check that expression type is complete/non-abstract; statement |
15670 | // expressions are not lvalues. |
15671 | Expr *ResStmtExpr = |
15672 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); |
15673 | if (StmtExprMayBindToTemp) |
15674 | return MaybeBindToTemporary(E: ResStmtExpr); |
15675 | return ResStmtExpr; |
15676 | } |
15677 | |
15678 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { |
15679 | if (ER.isInvalid()) |
15680 | return ExprError(); |
15681 | |
15682 | // Do function/array conversion on the last expression, but not |
15683 | // lvalue-to-rvalue. However, initialize an unqualified type. |
15684 | ER = DefaultFunctionArrayConversion(E: ER.get()); |
15685 | if (ER.isInvalid()) |
15686 | return ExprError(); |
15687 | Expr *E = ER.get(); |
15688 | |
15689 | if (E->isTypeDependent()) |
15690 | return E; |
15691 | |
15692 | // In ARC, if the final expression ends in a consume, splice |
15693 | // the consume out and bind it later. In the alternate case |
15694 | // (when dealing with a retainable type), the result |
15695 | // initialization will create a produce. In both cases the |
15696 | // result will be +1, and we'll need to balance that out with |
15697 | // a bind. |
15698 | auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E); |
15699 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) |
15700 | return Cast->getSubExpr(); |
15701 | |
15702 | // FIXME: Provide a better location for the initialization. |
15703 | return PerformCopyInitialization( |
15704 | Entity: InitializedEntity::InitializeStmtExprResult( |
15705 | ReturnLoc: E->getBeginLoc(), Type: E->getType().getUnqualifiedType()), |
15706 | EqualLoc: SourceLocation(), Init: E); |
15707 | } |
15708 | |
15709 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
15710 | TypeSourceInfo *TInfo, |
15711 | ArrayRef<OffsetOfComponent> Components, |
15712 | SourceLocation RParenLoc) { |
15713 | QualType ArgTy = TInfo->getType(); |
15714 | bool Dependent = ArgTy->isDependentType(); |
15715 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); |
15716 | |
15717 | // We must have at least one component that refers to the type, and the first |
15718 | // one is known to be a field designator. Verify that the ArgTy represents |
15719 | // a struct/union/class. |
15720 | if (!Dependent && !ArgTy->isRecordType()) |
15721 | return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_offsetof_record_type) |
15722 | << ArgTy << TypeRange); |
15723 | |
15724 | // Type must be complete per C99 7.17p3 because a declaring a variable |
15725 | // with an incomplete type would be ill-formed. |
15726 | if (!Dependent |
15727 | && RequireCompleteType(Loc: BuiltinLoc, T: ArgTy, |
15728 | DiagID: diag::err_offsetof_incomplete_type, Args: TypeRange)) |
15729 | return ExprError(); |
15730 | |
15731 | bool DidWarnAboutNonPOD = false; |
15732 | QualType CurrentType = ArgTy; |
15733 | SmallVector<OffsetOfNode, 4> Comps; |
15734 | SmallVector<Expr*, 4> Exprs; |
15735 | for (const OffsetOfComponent &OC : Components) { |
15736 | if (OC.isBrackets) { |
15737 | // Offset of an array sub-field. TODO: Should we allow vector elements? |
15738 | if (!CurrentType->isDependentType()) { |
15739 | const ArrayType *AT = Context.getAsArrayType(T: CurrentType); |
15740 | if(!AT) |
15741 | return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_array_type) |
15742 | << CurrentType); |
15743 | CurrentType = AT->getElementType(); |
15744 | } else |
15745 | CurrentType = Context.DependentTy; |
15746 | |
15747 | ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E)); |
15748 | if (IdxRval.isInvalid()) |
15749 | return ExprError(); |
15750 | Expr *Idx = IdxRval.get(); |
15751 | |
15752 | // The expression must be an integral expression. |
15753 | // FIXME: An integral constant expression? |
15754 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && |
15755 | !Idx->getType()->isIntegerType()) |
15756 | return ExprError( |
15757 | Diag(Loc: Idx->getBeginLoc(), DiagID: diag::err_typecheck_subscript_not_integer) |
15758 | << Idx->getSourceRange()); |
15759 | |
15760 | // Record this array index. |
15761 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); |
15762 | Exprs.push_back(Elt: Idx); |
15763 | continue; |
15764 | } |
15765 | |
15766 | // Offset of a field. |
15767 | if (CurrentType->isDependentType()) { |
15768 | // We have the offset of a field, but we can't look into the dependent |
15769 | // type. Just record the identifier of the field. |
15770 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); |
15771 | CurrentType = Context.DependentTy; |
15772 | continue; |
15773 | } |
15774 | |
15775 | // We need to have a complete type to look into. |
15776 | if (RequireCompleteType(Loc: OC.LocStart, T: CurrentType, |
15777 | DiagID: diag::err_offsetof_incomplete_type)) |
15778 | return ExprError(); |
15779 | |
15780 | // Look for the designated field. |
15781 | const RecordType *RC = CurrentType->getAs<RecordType>(); |
15782 | if (!RC) |
15783 | return ExprError(Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_record_type) |
15784 | << CurrentType); |
15785 | RecordDecl *RD = RC->getDecl(); |
15786 | |
15787 | // C++ [lib.support.types]p5: |
15788 | // The macro offsetof accepts a restricted set of type arguments in this |
15789 | // International Standard. type shall be a POD structure or a POD union |
15790 | // (clause 9). |
15791 | // C++11 [support.types]p4: |
15792 | // If type is not a standard-layout class (Clause 9), the results are |
15793 | // undefined. |
15794 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
15795 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); |
15796 | unsigned DiagID = |
15797 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type |
15798 | : diag::ext_offsetof_non_pod_type; |
15799 | |
15800 | if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) { |
15801 | Diag(Loc: BuiltinLoc, DiagID) |
15802 | << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType; |
15803 | DidWarnAboutNonPOD = true; |
15804 | } |
15805 | } |
15806 | |
15807 | // Look for the field. |
15808 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); |
15809 | LookupQualifiedName(R, LookupCtx: RD); |
15810 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); |
15811 | IndirectFieldDecl *IndirectMemberDecl = nullptr; |
15812 | if (!MemberDecl) { |
15813 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) |
15814 | MemberDecl = IndirectMemberDecl->getAnonField(); |
15815 | } |
15816 | |
15817 | if (!MemberDecl) { |
15818 | // Lookup could be ambiguous when looking up a placeholder variable |
15819 | // __builtin_offsetof(S, _). |
15820 | // In that case we would already have emitted a diagnostic |
15821 | if (!R.isAmbiguous()) |
15822 | Diag(Loc: BuiltinLoc, DiagID: diag::err_no_member) |
15823 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd); |
15824 | return ExprError(); |
15825 | } |
15826 | |
15827 | // C99 7.17p3: |
15828 | // (If the specified member is a bit-field, the behavior is undefined.) |
15829 | // |
15830 | // We diagnose this as an error. |
15831 | if (MemberDecl->isBitField()) { |
15832 | Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_bitfield) |
15833 | << MemberDecl->getDeclName() |
15834 | << SourceRange(BuiltinLoc, RParenLoc); |
15835 | Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_bitfield_decl); |
15836 | return ExprError(); |
15837 | } |
15838 | |
15839 | RecordDecl *Parent = MemberDecl->getParent(); |
15840 | if (IndirectMemberDecl) |
15841 | Parent = cast<RecordDecl>(Val: IndirectMemberDecl->getDeclContext()); |
15842 | |
15843 | // If the member was found in a base class, introduce OffsetOfNodes for |
15844 | // the base class indirections. |
15845 | CXXBasePaths Paths; |
15846 | if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType, Base: Context.getTypeDeclType(Decl: Parent), |
15847 | Paths)) { |
15848 | if (Paths.getDetectedVirtual()) { |
15849 | Diag(Loc: OC.LocEnd, DiagID: diag::err_offsetof_field_of_virtual_base) |
15850 | << MemberDecl->getDeclName() |
15851 | << SourceRange(BuiltinLoc, RParenLoc); |
15852 | return ExprError(); |
15853 | } |
15854 | |
15855 | CXXBasePath &Path = Paths.front(); |
15856 | for (const CXXBasePathElement &B : Path) |
15857 | Comps.push_back(Elt: OffsetOfNode(B.Base)); |
15858 | } |
15859 | |
15860 | if (IndirectMemberDecl) { |
15861 | for (auto *FI : IndirectMemberDecl->chain()) { |
15862 | assert(isa<FieldDecl>(FI)); |
15863 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, |
15864 | cast<FieldDecl>(Val: FI), OC.LocEnd)); |
15865 | } |
15866 | } else |
15867 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); |
15868 | |
15869 | CurrentType = MemberDecl->getType().getNonReferenceType(); |
15870 | } |
15871 | |
15872 | return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo, |
15873 | comps: Comps, exprs: Exprs, RParenLoc); |
15874 | } |
15875 | |
15876 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, |
15877 | SourceLocation BuiltinLoc, |
15878 | SourceLocation TypeLoc, |
15879 | ParsedType ParsedArgTy, |
15880 | ArrayRef<OffsetOfComponent> Components, |
15881 | SourceLocation RParenLoc) { |
15882 | |
15883 | TypeSourceInfo *ArgTInfo; |
15884 | QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo); |
15885 | if (ArgTy.isNull()) |
15886 | return ExprError(); |
15887 | |
15888 | if (!ArgTInfo) |
15889 | ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc); |
15890 | |
15891 | return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc); |
15892 | } |
15893 | |
15894 | |
15895 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, |
15896 | Expr *CondExpr, |
15897 | Expr *LHSExpr, Expr *RHSExpr, |
15898 | SourceLocation RPLoc) { |
15899 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)" ); |
15900 | |
15901 | ExprValueKind VK = VK_PRValue; |
15902 | ExprObjectKind OK = OK_Ordinary; |
15903 | QualType resType; |
15904 | bool CondIsTrue = false; |
15905 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { |
15906 | resType = Context.DependentTy; |
15907 | } else { |
15908 | // The conditional expression is required to be a constant expression. |
15909 | llvm::APSInt condEval(32); |
15910 | ExprResult CondICE = VerifyIntegerConstantExpression( |
15911 | E: CondExpr, Result: &condEval, DiagID: diag::err_typecheck_choose_expr_requires_constant); |
15912 | if (CondICE.isInvalid()) |
15913 | return ExprError(); |
15914 | CondExpr = CondICE.get(); |
15915 | CondIsTrue = condEval.getZExtValue(); |
15916 | |
15917 | // If the condition is > zero, then the AST type is the same as the LHSExpr. |
15918 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; |
15919 | |
15920 | resType = ActiveExpr->getType(); |
15921 | VK = ActiveExpr->getValueKind(); |
15922 | OK = ActiveExpr->getObjectKind(); |
15923 | } |
15924 | |
15925 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, |
15926 | resType, VK, OK, RPLoc, CondIsTrue); |
15927 | } |
15928 | |
15929 | //===----------------------------------------------------------------------===// |
15930 | // Clang Extensions. |
15931 | //===----------------------------------------------------------------------===// |
15932 | |
15933 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { |
15934 | BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc); |
15935 | |
15936 | if (LangOpts.CPlusPlus) { |
15937 | MangleNumberingContext *MCtx; |
15938 | Decl *ManglingContextDecl; |
15939 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
15940 | getCurrentMangleNumberContext(DC: Block->getDeclContext()); |
15941 | if (MCtx) { |
15942 | unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block); |
15943 | Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl); |
15944 | } |
15945 | } |
15946 | |
15947 | PushBlockScope(BlockScope: CurScope, Block); |
15948 | CurContext->addDecl(D: Block); |
15949 | if (CurScope) |
15950 | PushDeclContext(S: CurScope, DC: Block); |
15951 | else |
15952 | CurContext = Block; |
15953 | |
15954 | getCurBlock()->HasImplicitReturnType = true; |
15955 | |
15956 | // Enter a new evaluation context to insulate the block from any |
15957 | // cleanups from the enclosing full-expression. |
15958 | PushExpressionEvaluationContext( |
15959 | NewContext: ExpressionEvaluationContext::PotentiallyEvaluated); |
15960 | } |
15961 | |
15962 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
15963 | Scope *CurScope) { |
15964 | assert(ParamInfo.getIdentifier() == nullptr && |
15965 | "block-id should have no identifier!" ); |
15966 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); |
15967 | BlockScopeInfo *CurBlock = getCurBlock(); |
15968 | |
15969 | TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo); |
15970 | QualType T = Sig->getType(); |
15971 | |
15972 | // FIXME: We should allow unexpanded parameter packs here, but that would, |
15973 | // in turn, make the block expression contain unexpanded parameter packs. |
15974 | if (DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block)) { |
15975 | // Drop the parameters. |
15976 | FunctionProtoType::ExtProtoInfo EPI; |
15977 | EPI.HasTrailingReturn = false; |
15978 | EPI.TypeQuals.addConst(); |
15979 | T = Context.getFunctionType(ResultTy: Context.DependentTy, Args: std::nullopt, EPI); |
15980 | Sig = Context.getTrivialTypeSourceInfo(T); |
15981 | } |
15982 | |
15983 | // GetTypeForDeclarator always produces a function type for a block |
15984 | // literal signature. Furthermore, it is always a FunctionProtoType |
15985 | // unless the function was written with a typedef. |
15986 | assert(T->isFunctionType() && |
15987 | "GetTypeForDeclarator made a non-function block signature" ); |
15988 | |
15989 | // Look for an explicit signature in that function type. |
15990 | FunctionProtoTypeLoc ExplicitSignature; |
15991 | |
15992 | if ((ExplicitSignature = Sig->getTypeLoc() |
15993 | .getAsAdjusted<FunctionProtoTypeLoc>())) { |
15994 | |
15995 | // Check whether that explicit signature was synthesized by |
15996 | // GetTypeForDeclarator. If so, don't save that as part of the |
15997 | // written signature. |
15998 | if (ExplicitSignature.getLocalRangeBegin() == |
15999 | ExplicitSignature.getLocalRangeEnd()) { |
16000 | // This would be much cheaper if we stored TypeLocs instead of |
16001 | // TypeSourceInfos. |
16002 | TypeLoc Result = ExplicitSignature.getReturnLoc(); |
16003 | unsigned Size = Result.getFullDataSize(); |
16004 | Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size); |
16005 | Sig->getTypeLoc().initializeFullCopy(Other: Result, Size); |
16006 | |
16007 | ExplicitSignature = FunctionProtoTypeLoc(); |
16008 | } |
16009 | } |
16010 | |
16011 | CurBlock->TheDecl->setSignatureAsWritten(Sig); |
16012 | CurBlock->FunctionType = T; |
16013 | |
16014 | const auto *Fn = T->castAs<FunctionType>(); |
16015 | QualType RetTy = Fn->getReturnType(); |
16016 | bool isVariadic = |
16017 | (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic()); |
16018 | |
16019 | CurBlock->TheDecl->setIsVariadic(isVariadic); |
16020 | |
16021 | // Context.DependentTy is used as a placeholder for a missing block |
16022 | // return type. TODO: what should we do with declarators like: |
16023 | // ^ * { ... } |
16024 | // If the answer is "apply template argument deduction".... |
16025 | if (RetTy != Context.DependentTy) { |
16026 | CurBlock->ReturnType = RetTy; |
16027 | CurBlock->TheDecl->setBlockMissingReturnType(false); |
16028 | CurBlock->HasImplicitReturnType = false; |
16029 | } |
16030 | |
16031 | // Push block parameters from the declarator if we had them. |
16032 | SmallVector<ParmVarDecl*, 8> Params; |
16033 | if (ExplicitSignature) { |
16034 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { |
16035 | ParmVarDecl *Param = ExplicitSignature.getParam(i: I); |
16036 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && |
16037 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { |
16038 | // Diagnose this as an extension in C17 and earlier. |
16039 | if (!getLangOpts().C23) |
16040 | Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23); |
16041 | } |
16042 | Params.push_back(Elt: Param); |
16043 | } |
16044 | |
16045 | // Fake up parameter variables if we have a typedef, like |
16046 | // ^ fntype { ... } |
16047 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { |
16048 | for (const auto &I : Fn->param_types()) { |
16049 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( |
16050 | DC: CurBlock->TheDecl, Loc: ParamInfo.getBeginLoc(), T: I); |
16051 | Params.push_back(Elt: Param); |
16052 | } |
16053 | } |
16054 | |
16055 | // Set the parameters on the block decl. |
16056 | if (!Params.empty()) { |
16057 | CurBlock->TheDecl->setParams(Params); |
16058 | CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(), |
16059 | /*CheckParameterNames=*/false); |
16060 | } |
16061 | |
16062 | // Finally we can process decl attributes. |
16063 | ProcessDeclAttributes(S: CurScope, D: CurBlock->TheDecl, PD: ParamInfo); |
16064 | |
16065 | // Put the parameter variables in scope. |
16066 | for (auto *AI : CurBlock->TheDecl->parameters()) { |
16067 | AI->setOwningFunction(CurBlock->TheDecl); |
16068 | |
16069 | // If this has an identifier, add it to the scope stack. |
16070 | if (AI->getIdentifier()) { |
16071 | CheckShadow(S: CurBlock->TheScope, D: AI); |
16072 | |
16073 | PushOnScopeChains(D: AI, S: CurBlock->TheScope); |
16074 | } |
16075 | |
16076 | if (AI->isInvalidDecl()) |
16077 | CurBlock->TheDecl->setInvalidDecl(); |
16078 | } |
16079 | } |
16080 | |
16081 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { |
16082 | // Leave the expression-evaluation context. |
16083 | DiscardCleanupsInEvaluationContext(); |
16084 | PopExpressionEvaluationContext(); |
16085 | |
16086 | // Pop off CurBlock, handle nested blocks. |
16087 | PopDeclContext(); |
16088 | PopFunctionScopeInfo(); |
16089 | } |
16090 | |
16091 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, |
16092 | Stmt *Body, Scope *CurScope) { |
16093 | // If blocks are disabled, emit an error. |
16094 | if (!LangOpts.Blocks) |
16095 | Diag(Loc: CaretLoc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL; |
16096 | |
16097 | // Leave the expression-evaluation context. |
16098 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
16099 | DiscardCleanupsInEvaluationContext(); |
16100 | assert(!Cleanup.exprNeedsCleanups() && |
16101 | "cleanups within block not correctly bound!" ); |
16102 | PopExpressionEvaluationContext(); |
16103 | |
16104 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back()); |
16105 | BlockDecl *BD = BSI->TheDecl; |
16106 | |
16107 | if (BSI->HasImplicitReturnType) |
16108 | deduceClosureReturnType(CSI&: *BSI); |
16109 | |
16110 | QualType RetTy = Context.VoidTy; |
16111 | if (!BSI->ReturnType.isNull()) |
16112 | RetTy = BSI->ReturnType; |
16113 | |
16114 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); |
16115 | QualType BlockTy; |
16116 | |
16117 | // If the user wrote a function type in some form, try to use that. |
16118 | if (!BSI->FunctionType.isNull()) { |
16119 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); |
16120 | |
16121 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); |
16122 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true); |
16123 | |
16124 | // Turn protoless block types into nullary block types. |
16125 | if (isa<FunctionNoProtoType>(Val: FTy)) { |
16126 | FunctionProtoType::ExtProtoInfo EPI; |
16127 | EPI.ExtInfo = Ext; |
16128 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: std::nullopt, EPI); |
16129 | |
16130 | // Otherwise, if we don't need to change anything about the function type, |
16131 | // preserve its sugar structure. |
16132 | } else if (FTy->getReturnType() == RetTy && |
16133 | (!NoReturn || FTy->getNoReturnAttr())) { |
16134 | BlockTy = BSI->FunctionType; |
16135 | |
16136 | // Otherwise, make the minimal modifications to the function type. |
16137 | } else { |
16138 | const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy); |
16139 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
16140 | EPI.TypeQuals = Qualifiers(); |
16141 | EPI.ExtInfo = Ext; |
16142 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI); |
16143 | } |
16144 | |
16145 | // If we don't have a function type, just build one from nothing. |
16146 | } else { |
16147 | FunctionProtoType::ExtProtoInfo EPI; |
16148 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn); |
16149 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: std::nullopt, EPI); |
16150 | } |
16151 | |
16152 | DiagnoseUnusedParameters(Parameters: BD->parameters()); |
16153 | BlockTy = Context.getBlockPointerType(T: BlockTy); |
16154 | |
16155 | // If needed, diagnose invalid gotos and switches in the block. |
16156 | if (getCurFunction()->NeedsScopeChecking() && |
16157 | !PP.isCodeCompletionEnabled()) |
16158 | DiagnoseInvalidJumps(Body: cast<CompoundStmt>(Val: Body)); |
16159 | |
16160 | BD->setBody(cast<CompoundStmt>(Val: Body)); |
16161 | |
16162 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) |
16163 | DiagnoseUnguardedAvailabilityViolations(FD: BD); |
16164 | |
16165 | // Try to apply the named return value optimization. We have to check again |
16166 | // if we can do this, though, because blocks keep return statements around |
16167 | // to deduce an implicit return type. |
16168 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && |
16169 | !BD->isDependentContext()) |
16170 | computeNRVO(Body, Scope: BSI); |
16171 | |
16172 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || |
16173 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) |
16174 | checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(), UseContext: NTCUC_FunctionReturn, |
16175 | NonTrivialKind: NTCUK_Destruct|NTCUK_Copy); |
16176 | |
16177 | PopDeclContext(); |
16178 | |
16179 | // Set the captured variables on the block. |
16180 | SmallVector<BlockDecl::Capture, 4> Captures; |
16181 | for (Capture &Cap : BSI->Captures) { |
16182 | if (Cap.isInvalid() || Cap.isThisCapture()) |
16183 | continue; |
16184 | // Cap.getVariable() is always a VarDecl because |
16185 | // blocks cannot capture structured bindings or other ValueDecl kinds. |
16186 | auto *Var = cast<VarDecl>(Val: Cap.getVariable()); |
16187 | Expr *CopyExpr = nullptr; |
16188 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { |
16189 | if (const RecordType *Record = |
16190 | Cap.getCaptureType()->getAs<RecordType>()) { |
16191 | // The capture logic needs the destructor, so make sure we mark it. |
16192 | // Usually this is unnecessary because most local variables have |
16193 | // their destructors marked at declaration time, but parameters are |
16194 | // an exception because it's technically only the call site that |
16195 | // actually requires the destructor. |
16196 | if (isa<ParmVarDecl>(Val: Var)) |
16197 | FinalizeVarWithDestructor(VD: Var, DeclInitType: Record); |
16198 | |
16199 | // Enter a separate potentially-evaluated context while building block |
16200 | // initializers to isolate their cleanups from those of the block |
16201 | // itself. |
16202 | // FIXME: Is this appropriate even when the block itself occurs in an |
16203 | // unevaluated operand? |
16204 | EnterExpressionEvaluationContext EvalContext( |
16205 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); |
16206 | |
16207 | SourceLocation Loc = Cap.getLocation(); |
16208 | |
16209 | ExprResult Result = BuildDeclarationNameExpr( |
16210 | SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var); |
16211 | |
16212 | // According to the blocks spec, the capture of a variable from |
16213 | // the stack requires a const copy constructor. This is not true |
16214 | // of the copy/move done to move a __block variable to the heap. |
16215 | if (!Result.isInvalid() && |
16216 | !Result.get()->getType().isConstQualified()) { |
16217 | Result = ImpCastExprToType(E: Result.get(), |
16218 | Type: Result.get()->getType().withConst(), |
16219 | CK: CK_NoOp, VK: VK_LValue); |
16220 | } |
16221 | |
16222 | if (!Result.isInvalid()) { |
16223 | Result = PerformCopyInitialization( |
16224 | Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(), |
16225 | Type: Cap.getCaptureType()), |
16226 | EqualLoc: Loc, Init: Result.get()); |
16227 | } |
16228 | |
16229 | // Build a full-expression copy expression if initialization |
16230 | // succeeded and used a non-trivial constructor. Recover from |
16231 | // errors by pretending that the copy isn't necessary. |
16232 | if (!Result.isInvalid() && |
16233 | !cast<CXXConstructExpr>(Val: Result.get())->getConstructor() |
16234 | ->isTrivial()) { |
16235 | Result = MaybeCreateExprWithCleanups(SubExpr: Result); |
16236 | CopyExpr = Result.get(); |
16237 | } |
16238 | } |
16239 | } |
16240 | |
16241 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), |
16242 | CopyExpr); |
16243 | Captures.push_back(Elt: NewCap); |
16244 | } |
16245 | BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0); |
16246 | |
16247 | // Pop the block scope now but keep it alive to the end of this function. |
16248 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); |
16249 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(WP: &WP, D: BD, BlockType: BlockTy); |
16250 | |
16251 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); |
16252 | |
16253 | // If the block isn't obviously global, i.e. it captures anything at |
16254 | // all, then we need to do a few things in the surrounding context: |
16255 | if (Result->getBlockDecl()->hasCaptures()) { |
16256 | // First, this expression has a new cleanup object. |
16257 | ExprCleanupObjects.push_back(Elt: Result->getBlockDecl()); |
16258 | Cleanup.setExprNeedsCleanups(true); |
16259 | |
16260 | // It also gets a branch-protected scope if any of the captured |
16261 | // variables needs destruction. |
16262 | for (const auto &CI : Result->getBlockDecl()->captures()) { |
16263 | const VarDecl *var = CI.getVariable(); |
16264 | if (var->getType().isDestructedType() != QualType::DK_none) { |
16265 | setFunctionHasBranchProtectedScope(); |
16266 | break; |
16267 | } |
16268 | } |
16269 | } |
16270 | |
16271 | if (getCurFunction()) |
16272 | getCurFunction()->addBlock(BD); |
16273 | |
16274 | if (BD->isInvalidDecl()) |
16275 | return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(), |
16276 | SubExprs: {Result}, T: Result->getType()); |
16277 | return Result; |
16278 | } |
16279 | |
16280 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
16281 | SourceLocation RPLoc) { |
16282 | TypeSourceInfo *TInfo; |
16283 | GetTypeFromParser(Ty, TInfo: &TInfo); |
16284 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); |
16285 | } |
16286 | |
16287 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, |
16288 | Expr *E, TypeSourceInfo *TInfo, |
16289 | SourceLocation RPLoc) { |
16290 | Expr *OrigExpr = E; |
16291 | bool IsMS = false; |
16292 | |
16293 | // CUDA device code does not support varargs. |
16294 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { |
16295 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) { |
16296 | CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F); |
16297 | if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device || |
16298 | T == CUDAFunctionTarget::HostDevice) |
16299 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device)); |
16300 | } |
16301 | } |
16302 | |
16303 | // NVPTX does not support va_arg expression. |
16304 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && |
16305 | Context.getTargetInfo().getTriple().isNVPTX()) |
16306 | targetDiag(Loc: E->getBeginLoc(), DiagID: diag::err_va_arg_in_device); |
16307 | |
16308 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() |
16309 | // as Microsoft ABI on an actual Microsoft platform, where |
16310 | // __builtin_ms_va_list and __builtin_va_list are the same.) |
16311 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && |
16312 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { |
16313 | QualType MSVaListType = Context.getBuiltinMSVaListType(); |
16314 | if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) { |
16315 | if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
16316 | return ExprError(); |
16317 | IsMS = true; |
16318 | } |
16319 | } |
16320 | |
16321 | // Get the va_list type |
16322 | QualType VaListType = Context.getBuiltinVaListType(); |
16323 | if (!IsMS) { |
16324 | if (VaListType->isArrayType()) { |
16325 | // Deal with implicit array decay; for example, on x86-64, |
16326 | // va_list is an array, but it's supposed to decay to |
16327 | // a pointer for va_arg. |
16328 | VaListType = Context.getArrayDecayedType(T: VaListType); |
16329 | // Make sure the input expression also decays appropriately. |
16330 | ExprResult Result = UsualUnaryConversions(E); |
16331 | if (Result.isInvalid()) |
16332 | return ExprError(); |
16333 | E = Result.get(); |
16334 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { |
16335 | // If va_list is a record type and we are compiling in C++ mode, |
16336 | // check the argument using reference binding. |
16337 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
16338 | Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false); |
16339 | ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E); |
16340 | if (Init.isInvalid()) |
16341 | return ExprError(); |
16342 | E = Init.getAs<Expr>(); |
16343 | } else { |
16344 | // Otherwise, the va_list argument must be an l-value because |
16345 | // it is modified by va_arg. |
16346 | if (!E->isTypeDependent() && |
16347 | CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
16348 | return ExprError(); |
16349 | } |
16350 | } |
16351 | |
16352 | if (!IsMS && !E->isTypeDependent() && |
16353 | !Context.hasSameType(T1: VaListType, T2: E->getType())) |
16354 | return ExprError( |
16355 | Diag(Loc: E->getBeginLoc(), |
16356 | DiagID: diag::err_first_argument_to_va_arg_not_of_type_va_list) |
16357 | << OrigExpr->getType() << E->getSourceRange()); |
16358 | |
16359 | if (!TInfo->getType()->isDependentType()) { |
16360 | if (RequireCompleteType(Loc: TInfo->getTypeLoc().getBeginLoc(), T: TInfo->getType(), |
16361 | DiagID: diag::err_second_parameter_to_va_arg_incomplete, |
16362 | Args: TInfo->getTypeLoc())) |
16363 | return ExprError(); |
16364 | |
16365 | if (RequireNonAbstractType(Loc: TInfo->getTypeLoc().getBeginLoc(), |
16366 | T: TInfo->getType(), |
16367 | DiagID: diag::err_second_parameter_to_va_arg_abstract, |
16368 | Args: TInfo->getTypeLoc())) |
16369 | return ExprError(); |
16370 | |
16371 | if (!TInfo->getType().isPODType(Context)) { |
16372 | Diag(Loc: TInfo->getTypeLoc().getBeginLoc(), |
16373 | DiagID: TInfo->getType()->isObjCLifetimeType() |
16374 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified |
16375 | : diag::warn_second_parameter_to_va_arg_not_pod) |
16376 | << TInfo->getType() |
16377 | << TInfo->getTypeLoc().getSourceRange(); |
16378 | } |
16379 | |
16380 | // Check for va_arg where arguments of the given type will be promoted |
16381 | // (i.e. this va_arg is guaranteed to have undefined behavior). |
16382 | QualType PromoteType; |
16383 | if (Context.isPromotableIntegerType(T: TInfo->getType())) { |
16384 | PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType()); |
16385 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, |
16386 | // and C23 7.16.1.1p2 says, in part: |
16387 | // If type is not compatible with the type of the actual next argument |
16388 | // (as promoted according to the default argument promotions), the |
16389 | // behavior is undefined, except for the following cases: |
16390 | // - both types are pointers to qualified or unqualified versions of |
16391 | // compatible types; |
16392 | // - one type is compatible with a signed integer type, the other |
16393 | // type is compatible with the corresponding unsigned integer type, |
16394 | // and the value is representable in both types; |
16395 | // - one type is pointer to qualified or unqualified void and the |
16396 | // other is a pointer to a qualified or unqualified character type; |
16397 | // - or, the type of the next argument is nullptr_t and type is a |
16398 | // pointer type that has the same representation and alignment |
16399 | // requirements as a pointer to a character type. |
16400 | // Given that type compatibility is the primary requirement (ignoring |
16401 | // qualifications), you would think we could call typesAreCompatible() |
16402 | // directly to test this. However, in C++, that checks for *same type*, |
16403 | // which causes false positives when passing an enumeration type to |
16404 | // va_arg. Instead, get the underlying type of the enumeration and pass |
16405 | // that. |
16406 | QualType UnderlyingType = TInfo->getType(); |
16407 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) |
16408 | UnderlyingType = ET->getDecl()->getIntegerType(); |
16409 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
16410 | /*CompareUnqualified*/ true)) |
16411 | PromoteType = QualType(); |
16412 | |
16413 | // If the types are still not compatible, we need to test whether the |
16414 | // promoted type and the underlying type are the same except for |
16415 | // signedness. Ask the AST for the correctly corresponding type and see |
16416 | // if that's compatible. |
16417 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && |
16418 | PromoteType->isUnsignedIntegerType() != |
16419 | UnderlyingType->isUnsignedIntegerType()) { |
16420 | UnderlyingType = |
16421 | UnderlyingType->isUnsignedIntegerType() |
16422 | ? Context.getCorrespondingSignedType(T: UnderlyingType) |
16423 | : Context.getCorrespondingUnsignedType(T: UnderlyingType); |
16424 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
16425 | /*CompareUnqualified*/ true)) |
16426 | PromoteType = QualType(); |
16427 | } |
16428 | } |
16429 | if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float)) |
16430 | PromoteType = Context.DoubleTy; |
16431 | if (!PromoteType.isNull()) |
16432 | DiagRuntimeBehavior(Loc: TInfo->getTypeLoc().getBeginLoc(), Statement: E, |
16433 | PD: PDiag(DiagID: diag::warn_second_parameter_to_va_arg_never_compatible) |
16434 | << TInfo->getType() |
16435 | << PromoteType |
16436 | << TInfo->getTypeLoc().getSourceRange()); |
16437 | } |
16438 | |
16439 | QualType T = TInfo->getType().getNonLValueExprType(Context); |
16440 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); |
16441 | } |
16442 | |
16443 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { |
16444 | // The type of __null will be int or long, depending on the size of |
16445 | // pointers on the target. |
16446 | QualType Ty; |
16447 | unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
16448 | if (pw == Context.getTargetInfo().getIntWidth()) |
16449 | Ty = Context.IntTy; |
16450 | else if (pw == Context.getTargetInfo().getLongWidth()) |
16451 | Ty = Context.LongTy; |
16452 | else if (pw == Context.getTargetInfo().getLongLongWidth()) |
16453 | Ty = Context.LongLongTy; |
16454 | else { |
16455 | llvm_unreachable("I don't know size of pointer!" ); |
16456 | } |
16457 | |
16458 | return new (Context) GNUNullExpr(Ty, TokenLoc); |
16459 | } |
16460 | |
16461 | static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { |
16462 | CXXRecordDecl *ImplDecl = nullptr; |
16463 | |
16464 | // Fetch the std::source_location::__impl decl. |
16465 | if (NamespaceDecl *Std = S.getStdNamespace()) { |
16466 | LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location" ), |
16467 | Loc, Sema::LookupOrdinaryName); |
16468 | if (S.LookupQualifiedName(R&: ResultSL, LookupCtx: Std)) { |
16469 | if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { |
16470 | LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl" ), |
16471 | Loc, Sema::LookupOrdinaryName); |
16472 | if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && |
16473 | S.LookupQualifiedName(R&: ResultImpl, LookupCtx: SLDecl)) { |
16474 | ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); |
16475 | } |
16476 | } |
16477 | } |
16478 | } |
16479 | |
16480 | if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { |
16481 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_not_found); |
16482 | return nullptr; |
16483 | } |
16484 | |
16485 | // Verify that __impl is a trivial struct type, with no base classes, and with |
16486 | // only the four expected fields. |
16487 | if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || |
16488 | ImplDecl->getNumBases() != 0) { |
16489 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed); |
16490 | return nullptr; |
16491 | } |
16492 | |
16493 | unsigned Count = 0; |
16494 | for (FieldDecl *F : ImplDecl->fields()) { |
16495 | StringRef Name = F->getName(); |
16496 | |
16497 | if (Name == "_M_file_name" ) { |
16498 | if (F->getType() != |
16499 | S.Context.getPointerType(T: S.Context.CharTy.withConst())) |
16500 | break; |
16501 | Count++; |
16502 | } else if (Name == "_M_function_name" ) { |
16503 | if (F->getType() != |
16504 | S.Context.getPointerType(T: S.Context.CharTy.withConst())) |
16505 | break; |
16506 | Count++; |
16507 | } else if (Name == "_M_line" ) { |
16508 | if (!F->getType()->isIntegerType()) |
16509 | break; |
16510 | Count++; |
16511 | } else if (Name == "_M_column" ) { |
16512 | if (!F->getType()->isIntegerType()) |
16513 | break; |
16514 | Count++; |
16515 | } else { |
16516 | Count = 100; // invalid |
16517 | break; |
16518 | } |
16519 | } |
16520 | if (Count != 4) { |
16521 | S.Diag(Loc, DiagID: diag::err_std_source_location_impl_malformed); |
16522 | return nullptr; |
16523 | } |
16524 | |
16525 | return ImplDecl; |
16526 | } |
16527 | |
16528 | ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind, |
16529 | SourceLocation BuiltinLoc, |
16530 | SourceLocation RPLoc) { |
16531 | QualType ResultTy; |
16532 | switch (Kind) { |
16533 | case SourceLocIdentKind::File: |
16534 | case SourceLocIdentKind::FileName: |
16535 | case SourceLocIdentKind::Function: |
16536 | case SourceLocIdentKind::FuncSig: { |
16537 | QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0); |
16538 | ResultTy = |
16539 | Context.getPointerType(T: ArrTy->getAsArrayTypeUnsafe()->getElementType()); |
16540 | break; |
16541 | } |
16542 | case SourceLocIdentKind::Line: |
16543 | case SourceLocIdentKind::Column: |
16544 | ResultTy = Context.UnsignedIntTy; |
16545 | break; |
16546 | case SourceLocIdentKind::SourceLocStruct: |
16547 | if (!StdSourceLocationImplDecl) { |
16548 | StdSourceLocationImplDecl = |
16549 | LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc); |
16550 | if (!StdSourceLocationImplDecl) |
16551 | return ExprError(); |
16552 | } |
16553 | ResultTy = Context.getPointerType( |
16554 | T: Context.getRecordType(Decl: StdSourceLocationImplDecl).withConst()); |
16555 | break; |
16556 | } |
16557 | |
16558 | return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext); |
16559 | } |
16560 | |
16561 | ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, |
16562 | SourceLocation BuiltinLoc, |
16563 | SourceLocation RPLoc, |
16564 | DeclContext *ParentContext) { |
16565 | return new (Context) |
16566 | SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); |
16567 | } |
16568 | |
16569 | ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, |
16570 | StringLiteral *BinaryData) { |
16571 | EmbedDataStorage *Data = new (Context) EmbedDataStorage; |
16572 | Data->BinaryData = BinaryData; |
16573 | return new (Context) |
16574 | EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0, |
16575 | Data->getDataElementCount()); |
16576 | } |
16577 | |
16578 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, |
16579 | const Expr *SrcExpr) { |
16580 | if (!DstType->isFunctionPointerType() || |
16581 | !SrcExpr->getType()->isFunctionType()) |
16582 | return false; |
16583 | |
16584 | auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts()); |
16585 | if (!DRE) |
16586 | return false; |
16587 | |
16588 | auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()); |
16589 | if (!FD) |
16590 | return false; |
16591 | |
16592 | return !S.checkAddressOfFunctionIsAvailable(Function: FD, |
16593 | /*Complain=*/true, |
16594 | Loc: SrcExpr->getBeginLoc()); |
16595 | } |
16596 | |
16597 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, |
16598 | SourceLocation Loc, |
16599 | QualType DstType, QualType SrcType, |
16600 | Expr *SrcExpr, AssignmentAction Action, |
16601 | bool *Complained) { |
16602 | if (Complained) |
16603 | *Complained = false; |
16604 | |
16605 | // Decode the result (notice that AST's are still created for extensions). |
16606 | bool CheckInferredResultType = false; |
16607 | bool isInvalid = false; |
16608 | unsigned DiagKind = 0; |
16609 | ConversionFixItGenerator ConvHints; |
16610 | bool MayHaveConvFixit = false; |
16611 | bool MayHaveFunctionDiff = false; |
16612 | const ObjCInterfaceDecl *IFace = nullptr; |
16613 | const ObjCProtocolDecl *PDecl = nullptr; |
16614 | |
16615 | switch (ConvTy) { |
16616 | case Compatible: |
16617 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); |
16618 | return false; |
16619 | |
16620 | case PointerToInt: |
16621 | if (getLangOpts().CPlusPlus) { |
16622 | DiagKind = diag::err_typecheck_convert_pointer_int; |
16623 | isInvalid = true; |
16624 | } else { |
16625 | DiagKind = diag::ext_typecheck_convert_pointer_int; |
16626 | } |
16627 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16628 | MayHaveConvFixit = true; |
16629 | break; |
16630 | case IntToPointer: |
16631 | if (getLangOpts().CPlusPlus) { |
16632 | DiagKind = diag::err_typecheck_convert_int_pointer; |
16633 | isInvalid = true; |
16634 | } else { |
16635 | DiagKind = diag::ext_typecheck_convert_int_pointer; |
16636 | } |
16637 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16638 | MayHaveConvFixit = true; |
16639 | break; |
16640 | case IncompatibleFunctionPointerStrict: |
16641 | DiagKind = |
16642 | diag::warn_typecheck_convert_incompatible_function_pointer_strict; |
16643 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16644 | MayHaveConvFixit = true; |
16645 | break; |
16646 | case IncompatibleFunctionPointer: |
16647 | if (getLangOpts().CPlusPlus) { |
16648 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; |
16649 | isInvalid = true; |
16650 | } else { |
16651 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; |
16652 | } |
16653 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16654 | MayHaveConvFixit = true; |
16655 | break; |
16656 | case IncompatiblePointer: |
16657 | if (Action == AA_Passing_CFAudited) { |
16658 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; |
16659 | } else if (getLangOpts().CPlusPlus) { |
16660 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; |
16661 | isInvalid = true; |
16662 | } else { |
16663 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; |
16664 | } |
16665 | CheckInferredResultType = DstType->isObjCObjectPointerType() && |
16666 | SrcType->isObjCObjectPointerType(); |
16667 | if (CheckInferredResultType) { |
16668 | SrcType = SrcType.getUnqualifiedType(); |
16669 | DstType = DstType.getUnqualifiedType(); |
16670 | } else { |
16671 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16672 | } |
16673 | MayHaveConvFixit = true; |
16674 | break; |
16675 | case IncompatiblePointerSign: |
16676 | if (getLangOpts().CPlusPlus) { |
16677 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; |
16678 | isInvalid = true; |
16679 | } else { |
16680 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; |
16681 | } |
16682 | break; |
16683 | case FunctionVoidPointer: |
16684 | if (getLangOpts().CPlusPlus) { |
16685 | DiagKind = diag::err_typecheck_convert_pointer_void_func; |
16686 | isInvalid = true; |
16687 | } else { |
16688 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; |
16689 | } |
16690 | break; |
16691 | case IncompatiblePointerDiscardsQualifiers: { |
16692 | // Perform array-to-pointer decay if necessary. |
16693 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType); |
16694 | |
16695 | isInvalid = true; |
16696 | |
16697 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); |
16698 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); |
16699 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { |
16700 | DiagKind = diag::err_typecheck_incompatible_address_space; |
16701 | break; |
16702 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { |
16703 | DiagKind = diag::err_typecheck_incompatible_ownership; |
16704 | break; |
16705 | } |
16706 | |
16707 | llvm_unreachable("unknown error case for discarding qualifiers!" ); |
16708 | // fallthrough |
16709 | } |
16710 | case CompatiblePointerDiscardsQualifiers: |
16711 | // If the qualifiers lost were because we were applying the |
16712 | // (deprecated) C++ conversion from a string literal to a char* |
16713 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: |
16714 | // Ideally, this check would be performed in |
16715 | // checkPointerTypesForAssignment. However, that would require a |
16716 | // bit of refactoring (so that the second argument is an |
16717 | // expression, rather than a type), which should be done as part |
16718 | // of a larger effort to fix checkPointerTypesForAssignment for |
16719 | // C++ semantics. |
16720 | if (getLangOpts().CPlusPlus && |
16721 | IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType)) |
16722 | return false; |
16723 | if (getLangOpts().CPlusPlus) { |
16724 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; |
16725 | isInvalid = true; |
16726 | } else { |
16727 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; |
16728 | } |
16729 | |
16730 | break; |
16731 | case IncompatibleNestedPointerQualifiers: |
16732 | if (getLangOpts().CPlusPlus) { |
16733 | isInvalid = true; |
16734 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; |
16735 | } else { |
16736 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; |
16737 | } |
16738 | break; |
16739 | case IncompatibleNestedPointerAddressSpaceMismatch: |
16740 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; |
16741 | isInvalid = true; |
16742 | break; |
16743 | case IntToBlockPointer: |
16744 | DiagKind = diag::err_int_to_block_pointer; |
16745 | isInvalid = true; |
16746 | break; |
16747 | case IncompatibleBlockPointer: |
16748 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; |
16749 | isInvalid = true; |
16750 | break; |
16751 | case IncompatibleObjCQualifiedId: { |
16752 | if (SrcType->isObjCQualifiedIdType()) { |
16753 | const ObjCObjectPointerType *srcOPT = |
16754 | SrcType->castAs<ObjCObjectPointerType>(); |
16755 | for (auto *srcProto : srcOPT->quals()) { |
16756 | PDecl = srcProto; |
16757 | break; |
16758 | } |
16759 | if (const ObjCInterfaceType *IFaceT = |
16760 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
16761 | IFace = IFaceT->getDecl(); |
16762 | } |
16763 | else if (DstType->isObjCQualifiedIdType()) { |
16764 | const ObjCObjectPointerType *dstOPT = |
16765 | DstType->castAs<ObjCObjectPointerType>(); |
16766 | for (auto *dstProto : dstOPT->quals()) { |
16767 | PDecl = dstProto; |
16768 | break; |
16769 | } |
16770 | if (const ObjCInterfaceType *IFaceT = |
16771 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
16772 | IFace = IFaceT->getDecl(); |
16773 | } |
16774 | if (getLangOpts().CPlusPlus) { |
16775 | DiagKind = diag::err_incompatible_qualified_id; |
16776 | isInvalid = true; |
16777 | } else { |
16778 | DiagKind = diag::warn_incompatible_qualified_id; |
16779 | } |
16780 | break; |
16781 | } |
16782 | case IncompatibleVectors: |
16783 | if (getLangOpts().CPlusPlus) { |
16784 | DiagKind = diag::err_incompatible_vectors; |
16785 | isInvalid = true; |
16786 | } else { |
16787 | DiagKind = diag::warn_incompatible_vectors; |
16788 | } |
16789 | break; |
16790 | case IncompatibleObjCWeakRef: |
16791 | DiagKind = diag::err_arc_weak_unavailable_assign; |
16792 | isInvalid = true; |
16793 | break; |
16794 | case Incompatible: |
16795 | if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) { |
16796 | if (Complained) |
16797 | *Complained = true; |
16798 | return true; |
16799 | } |
16800 | |
16801 | DiagKind = diag::err_typecheck_convert_incompatible; |
16802 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
16803 | MayHaveConvFixit = true; |
16804 | isInvalid = true; |
16805 | MayHaveFunctionDiff = true; |
16806 | break; |
16807 | } |
16808 | |
16809 | QualType FirstType, SecondType; |
16810 | switch (Action) { |
16811 | case AA_Assigning: |
16812 | case AA_Initializing: |
16813 | // The destination type comes first. |
16814 | FirstType = DstType; |
16815 | SecondType = SrcType; |
16816 | break; |
16817 | |
16818 | case AA_Returning: |
16819 | case AA_Passing: |
16820 | case AA_Passing_CFAudited: |
16821 | case AA_Converting: |
16822 | case AA_Sending: |
16823 | case AA_Casting: |
16824 | // The source type comes first. |
16825 | FirstType = SrcType; |
16826 | SecondType = DstType; |
16827 | break; |
16828 | } |
16829 | |
16830 | PartialDiagnostic FDiag = PDiag(DiagID: DiagKind); |
16831 | AssignmentAction ActionForDiag = Action; |
16832 | if (Action == AA_Passing_CFAudited) |
16833 | ActionForDiag = AA_Passing; |
16834 | |
16835 | FDiag << FirstType << SecondType << ActionForDiag |
16836 | << SrcExpr->getSourceRange(); |
16837 | |
16838 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || |
16839 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { |
16840 | auto isPlainChar = [](const clang::Type *Type) { |
16841 | return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
16842 | Type->isSpecificBuiltinType(K: BuiltinType::Char_U); |
16843 | }; |
16844 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || |
16845 | isPlainChar(SecondType->getPointeeOrArrayElementType())); |
16846 | } |
16847 | |
16848 | // If we can fix the conversion, suggest the FixIts. |
16849 | if (!ConvHints.isNull()) { |
16850 | for (FixItHint &H : ConvHints.Hints) |
16851 | FDiag << H; |
16852 | } |
16853 | |
16854 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } |
16855 | |
16856 | if (MayHaveFunctionDiff) |
16857 | HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType); |
16858 | |
16859 | Diag(Loc, PD: FDiag); |
16860 | if ((DiagKind == diag::warn_incompatible_qualified_id || |
16861 | DiagKind == diag::err_incompatible_qualified_id) && |
16862 | PDecl && IFace && !IFace->hasDefinition()) |
16863 | Diag(Loc: IFace->getLocation(), DiagID: diag::note_incomplete_class_and_qualified_id) |
16864 | << IFace << PDecl; |
16865 | |
16866 | if (SecondType == Context.OverloadTy) |
16867 | NoteAllOverloadCandidates(E: OverloadExpr::find(E: SrcExpr).Expression, |
16868 | DestType: FirstType, /*TakingAddress=*/true); |
16869 | |
16870 | if (CheckInferredResultType) |
16871 | ObjC().EmitRelatedResultTypeNote(E: SrcExpr); |
16872 | |
16873 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) |
16874 | ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType); |
16875 | |
16876 | if (Complained) |
16877 | *Complained = true; |
16878 | return isInvalid; |
16879 | } |
16880 | |
16881 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
16882 | llvm::APSInt *Result, |
16883 | AllowFoldKind CanFold) { |
16884 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { |
16885 | public: |
16886 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, |
16887 | QualType T) override { |
16888 | return S.Diag(Loc, DiagID: diag::err_ice_not_integral) |
16889 | << T << S.LangOpts.CPlusPlus; |
16890 | } |
16891 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
16892 | return S.Diag(Loc, DiagID: diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; |
16893 | } |
16894 | } Diagnoser; |
16895 | |
16896 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
16897 | } |
16898 | |
16899 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
16900 | llvm::APSInt *Result, |
16901 | unsigned DiagID, |
16902 | AllowFoldKind CanFold) { |
16903 | class IDDiagnoser : public VerifyICEDiagnoser { |
16904 | unsigned DiagID; |
16905 | |
16906 | public: |
16907 | IDDiagnoser(unsigned DiagID) |
16908 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } |
16909 | |
16910 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
16911 | return S.Diag(Loc, DiagID); |
16912 | } |
16913 | } Diagnoser(DiagID); |
16914 | |
16915 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
16916 | } |
16917 | |
16918 | Sema::SemaDiagnosticBuilder |
16919 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, |
16920 | QualType T) { |
16921 | return diagnoseNotICE(S, Loc); |
16922 | } |
16923 | |
16924 | Sema::SemaDiagnosticBuilder |
16925 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { |
16926 | return S.Diag(Loc, DiagID: diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; |
16927 | } |
16928 | |
16929 | ExprResult |
16930 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
16931 | VerifyICEDiagnoser &Diagnoser, |
16932 | AllowFoldKind CanFold) { |
16933 | SourceLocation DiagLoc = E->getBeginLoc(); |
16934 | |
16935 | if (getLangOpts().CPlusPlus11) { |
16936 | // C++11 [expr.const]p5: |
16937 | // If an expression of literal class type is used in a context where an |
16938 | // integral constant expression is required, then that class type shall |
16939 | // have a single non-explicit conversion function to an integral or |
16940 | // unscoped enumeration type |
16941 | ExprResult Converted; |
16942 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { |
16943 | VerifyICEDiagnoser &BaseDiagnoser; |
16944 | public: |
16945 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) |
16946 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, |
16947 | BaseDiagnoser.Suppress, true), |
16948 | BaseDiagnoser(BaseDiagnoser) {} |
16949 | |
16950 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
16951 | QualType T) override { |
16952 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); |
16953 | } |
16954 | |
16955 | SemaDiagnosticBuilder diagnoseIncomplete( |
16956 | Sema &S, SourceLocation Loc, QualType T) override { |
16957 | return S.Diag(Loc, DiagID: diag::err_ice_incomplete_type) << T; |
16958 | } |
16959 | |
16960 | SemaDiagnosticBuilder diagnoseExplicitConv( |
16961 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
16962 | return S.Diag(Loc, DiagID: diag::err_ice_explicit_conversion) << T << ConvTy; |
16963 | } |
16964 | |
16965 | SemaDiagnosticBuilder noteExplicitConv( |
16966 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
16967 | return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here) |
16968 | << ConvTy->isEnumeralType() << ConvTy; |
16969 | } |
16970 | |
16971 | SemaDiagnosticBuilder diagnoseAmbiguous( |
16972 | Sema &S, SourceLocation Loc, QualType T) override { |
16973 | return S.Diag(Loc, DiagID: diag::err_ice_ambiguous_conversion) << T; |
16974 | } |
16975 | |
16976 | SemaDiagnosticBuilder noteAmbiguous( |
16977 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
16978 | return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_ice_conversion_here) |
16979 | << ConvTy->isEnumeralType() << ConvTy; |
16980 | } |
16981 | |
16982 | SemaDiagnosticBuilder diagnoseConversion( |
16983 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
16984 | llvm_unreachable("conversion functions are permitted" ); |
16985 | } |
16986 | } ConvertDiagnoser(Diagnoser); |
16987 | |
16988 | Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E, |
16989 | Converter&: ConvertDiagnoser); |
16990 | if (Converted.isInvalid()) |
16991 | return Converted; |
16992 | E = Converted.get(); |
16993 | // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we |
16994 | // don't try to evaluate it later. We also don't want to return the |
16995 | // RecoveryExpr here, as it results in this call succeeding, thus callers of |
16996 | // this function will attempt to use 'Value'. |
16997 | if (isa<RecoveryExpr>(Val: E)) |
16998 | return ExprError(); |
16999 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) |
17000 | return ExprError(); |
17001 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { |
17002 | // An ICE must be of integral or unscoped enumeration type. |
17003 | if (!Diagnoser.Suppress) |
17004 | Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType()) |
17005 | << E->getSourceRange(); |
17006 | return ExprError(); |
17007 | } |
17008 | |
17009 | ExprResult RValueExpr = DefaultLvalueConversion(E); |
17010 | if (RValueExpr.isInvalid()) |
17011 | return ExprError(); |
17012 | |
17013 | E = RValueExpr.get(); |
17014 | |
17015 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice |
17016 | // in the non-ICE case. |
17017 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) { |
17018 | SmallVector<PartialDiagnosticAt, 8> Notes; |
17019 | if (Result) |
17020 | *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes); |
17021 | if (!isa<ConstantExpr>(Val: E)) |
17022 | E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result)) |
17023 | : ConstantExpr::Create(Context, E); |
17024 | |
17025 | if (Notes.empty()) |
17026 | return E; |
17027 | |
17028 | // If our only note is the usual "invalid subexpression" note, just point |
17029 | // the caret at its location rather than producing an essentially |
17030 | // redundant note. |
17031 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
17032 | diag::note_invalid_subexpr_in_const_expr) { |
17033 | DiagLoc = Notes[0].first; |
17034 | Notes.clear(); |
17035 | } |
17036 | |
17037 | if (getLangOpts().CPlusPlus) { |
17038 | if (!Diagnoser.Suppress) { |
17039 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17040 | for (const PartialDiagnosticAt &Note : Notes) |
17041 | Diag(Loc: Note.first, PD: Note.second); |
17042 | } |
17043 | return ExprError(); |
17044 | } |
17045 | |
17046 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17047 | for (const PartialDiagnosticAt &Note : Notes) |
17048 | Diag(Loc: Note.first, PD: Note.second); |
17049 | |
17050 | return E; |
17051 | } |
17052 | |
17053 | Expr::EvalResult EvalResult; |
17054 | SmallVector<PartialDiagnosticAt, 8> Notes; |
17055 | EvalResult.Diag = &Notes; |
17056 | |
17057 | // Try to evaluate the expression, and produce diagnostics explaining why it's |
17058 | // not a constant expression as a side-effect. |
17059 | bool Folded = |
17060 | E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) && |
17061 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects && |
17062 | (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior); |
17063 | |
17064 | if (!isa<ConstantExpr>(Val: E)) |
17065 | E = ConstantExpr::Create(Context, E, Result: EvalResult.Val); |
17066 | |
17067 | // In C++11, we can rely on diagnostics being produced for any expression |
17068 | // which is not a constant expression. If no diagnostics were produced, then |
17069 | // this is a constant expression. |
17070 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { |
17071 | if (Result) |
17072 | *Result = EvalResult.Val.getInt(); |
17073 | return E; |
17074 | } |
17075 | |
17076 | // If our only note is the usual "invalid subexpression" note, just point |
17077 | // the caret at its location rather than producing an essentially |
17078 | // redundant note. |
17079 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
17080 | diag::note_invalid_subexpr_in_const_expr) { |
17081 | DiagLoc = Notes[0].first; |
17082 | Notes.clear(); |
17083 | } |
17084 | |
17085 | if (!Folded || !CanFold) { |
17086 | if (!Diagnoser.Suppress) { |
17087 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17088 | for (const PartialDiagnosticAt &Note : Notes) |
17089 | Diag(Loc: Note.first, PD: Note.second); |
17090 | } |
17091 | |
17092 | return ExprError(); |
17093 | } |
17094 | |
17095 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17096 | for (const PartialDiagnosticAt &Note : Notes) |
17097 | Diag(Loc: Note.first, PD: Note.second); |
17098 | |
17099 | if (Result) |
17100 | *Result = EvalResult.Val.getInt(); |
17101 | return E; |
17102 | } |
17103 | |
17104 | namespace { |
17105 | // Handle the case where we conclude a expression which we speculatively |
17106 | // considered to be unevaluated is actually evaluated. |
17107 | class TransformToPE : public TreeTransform<TransformToPE> { |
17108 | typedef TreeTransform<TransformToPE> BaseTransform; |
17109 | |
17110 | public: |
17111 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } |
17112 | |
17113 | // Make sure we redo semantic analysis |
17114 | bool AlwaysRebuild() { return true; } |
17115 | bool ReplacingOriginal() { return true; } |
17116 | |
17117 | // We need to special-case DeclRefExprs referring to FieldDecls which |
17118 | // are not part of a member pointer formation; normal TreeTransforming |
17119 | // doesn't catch this case because of the way we represent them in the AST. |
17120 | // FIXME: This is a bit ugly; is it really the best way to handle this |
17121 | // case? |
17122 | // |
17123 | // Error on DeclRefExprs referring to FieldDecls. |
17124 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
17125 | if (isa<FieldDecl>(Val: E->getDecl()) && |
17126 | !SemaRef.isUnevaluatedContext()) |
17127 | return SemaRef.Diag(Loc: E->getLocation(), |
17128 | DiagID: diag::err_invalid_non_static_member_use) |
17129 | << E->getDecl() << E->getSourceRange(); |
17130 | |
17131 | return BaseTransform::TransformDeclRefExpr(E); |
17132 | } |
17133 | |
17134 | // Exception: filter out member pointer formation |
17135 | ExprResult TransformUnaryOperator(UnaryOperator *E) { |
17136 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) |
17137 | return E; |
17138 | |
17139 | return BaseTransform::TransformUnaryOperator(E); |
17140 | } |
17141 | |
17142 | // The body of a lambda-expression is in a separate expression evaluation |
17143 | // context so never needs to be transformed. |
17144 | // FIXME: Ideally we wouldn't transform the closure type either, and would |
17145 | // just recreate the capture expressions and lambda expression. |
17146 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
17147 | return SkipLambdaBody(E, Body); |
17148 | } |
17149 | }; |
17150 | } |
17151 | |
17152 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { |
17153 | assert(isUnevaluatedContext() && |
17154 | "Should only transform unevaluated expressions" ); |
17155 | ExprEvalContexts.back().Context = |
17156 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; |
17157 | if (isUnevaluatedContext()) |
17158 | return E; |
17159 | return TransformToPE(*this).TransformExpr(E); |
17160 | } |
17161 | |
17162 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { |
17163 | assert(isUnevaluatedContext() && |
17164 | "Should only transform unevaluated expressions" ); |
17165 | ExprEvalContexts.back().Context = parentEvaluationContext().Context; |
17166 | if (isUnevaluatedContext()) |
17167 | return TInfo; |
17168 | return TransformToPE(*this).TransformType(DI: TInfo); |
17169 | } |
17170 | |
17171 | void |
17172 | Sema::PushExpressionEvaluationContext( |
17173 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, |
17174 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
17175 | ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup, |
17176 | Args&: LambdaContextDecl, Args&: ExprContext); |
17177 | |
17178 | // Discarded statements and immediate contexts nested in other |
17179 | // discarded statements or immediate context are themselves |
17180 | // a discarded statement or an immediate context, respectively. |
17181 | ExprEvalContexts.back().InDiscardedStatement = |
17182 | parentEvaluationContext().isDiscardedStatementContext(); |
17183 | |
17184 | // C++23 [expr.const]/p15 |
17185 | // An expression or conversion is in an immediate function context if [...] |
17186 | // it is a subexpression of a manifestly constant-evaluated expression or |
17187 | // conversion. |
17188 | const auto &Prev = parentEvaluationContext(); |
17189 | ExprEvalContexts.back().InImmediateFunctionContext = |
17190 | Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated(); |
17191 | |
17192 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext = |
17193 | Prev.InImmediateEscalatingFunctionContext; |
17194 | |
17195 | Cleanup.reset(); |
17196 | if (!MaybeODRUseExprs.empty()) |
17197 | std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs); |
17198 | } |
17199 | |
17200 | void |
17201 | Sema::PushExpressionEvaluationContext( |
17202 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
17203 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
17204 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
17205 | PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext); |
17206 | } |
17207 | |
17208 | namespace { |
17209 | |
17210 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { |
17211 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); |
17212 | if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) { |
17213 | if (E->getOpcode() == UO_Deref) |
17214 | return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr()); |
17215 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) { |
17216 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
17217 | } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) { |
17218 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
17219 | } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) { |
17220 | QualType Inner; |
17221 | QualType Ty = E->getType(); |
17222 | if (const auto *Ptr = Ty->getAs<PointerType>()) |
17223 | Inner = Ptr->getPointeeType(); |
17224 | else if (const auto *Arr = S.Context.getAsArrayType(T: Ty)) |
17225 | Inner = Arr->getElementType(); |
17226 | else |
17227 | return nullptr; |
17228 | |
17229 | if (Inner->hasAttr(AK: attr::NoDeref)) |
17230 | return E; |
17231 | } |
17232 | return nullptr; |
17233 | } |
17234 | |
17235 | } // namespace |
17236 | |
17237 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { |
17238 | for (const Expr *E : Rec.PossibleDerefs) { |
17239 | const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E); |
17240 | if (DeclRef) { |
17241 | const ValueDecl *Decl = DeclRef->getDecl(); |
17242 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type) |
17243 | << Decl->getName() << E->getSourceRange(); |
17244 | Diag(Loc: Decl->getLocation(), DiagID: diag::note_previous_decl) << Decl->getName(); |
17245 | } else { |
17246 | Diag(Loc: E->getExprLoc(), DiagID: diag::warn_dereference_of_noderef_type_no_decl) |
17247 | << E->getSourceRange(); |
17248 | } |
17249 | } |
17250 | Rec.PossibleDerefs.clear(); |
17251 | } |
17252 | |
17253 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { |
17254 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) |
17255 | return; |
17256 | |
17257 | // Note: ignoring parens here is not justified by the standard rules, but |
17258 | // ignoring parentheses seems like a more reasonable approach, and this only |
17259 | // drives a deprecation warning so doesn't affect conformance. |
17260 | if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) { |
17261 | if (BO->getOpcode() == BO_Assign) { |
17262 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; |
17263 | llvm::erase(C&: LHSs, V: BO->getLHS()); |
17264 | } |
17265 | } |
17266 | } |
17267 | |
17268 | void Sema::MarkExpressionAsImmediateEscalating(Expr *E) { |
17269 | assert(getLangOpts().CPlusPlus20 && |
17270 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
17271 | "Cannot mark an immediate escalating expression outside of an " |
17272 | "immediate escalating context" ); |
17273 | if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit()); |
17274 | Call && Call->getCallee()) { |
17275 | if (auto *DeclRef = |
17276 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
17277 | DeclRef->setIsImmediateEscalating(true); |
17278 | } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) { |
17279 | Ctr->setIsImmediateEscalating(true); |
17280 | } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) { |
17281 | DeclRef->setIsImmediateEscalating(true); |
17282 | } else { |
17283 | assert(false && "expected an immediately escalating expression" ); |
17284 | } |
17285 | if (FunctionScopeInfo *FI = getCurFunction()) |
17286 | FI->FoundImmediateEscalatingExpression = true; |
17287 | } |
17288 | |
17289 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { |
17290 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || |
17291 | !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() || |
17292 | isCheckingDefaultArgumentOrInitializer() || |
17293 | RebuildingImmediateInvocation || isImmediateFunctionContext()) |
17294 | return E; |
17295 | |
17296 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. |
17297 | /// It's OK if this fails; we'll also remove this in |
17298 | /// HandleImmediateInvocations, but catching it here allows us to avoid |
17299 | /// walking the AST looking for it in simple cases. |
17300 | if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit())) |
17301 | if (auto *DeclRef = |
17302 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
17303 | ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef); |
17304 | |
17305 | // C++23 [expr.const]/p16 |
17306 | // An expression or conversion is immediate-escalating if it is not initially |
17307 | // in an immediate function context and it is [...] an immediate invocation |
17308 | // that is not a constant expression and is not a subexpression of an |
17309 | // immediate invocation. |
17310 | APValue Cached; |
17311 | auto CheckConstantExpressionAndKeepResult = [&]() { |
17312 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
17313 | Expr::EvalResult Eval; |
17314 | Eval.Diag = &Notes; |
17315 | bool Res = E.get()->EvaluateAsConstantExpr( |
17316 | Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation); |
17317 | if (Res && Notes.empty()) { |
17318 | Cached = std::move(Eval.Val); |
17319 | return true; |
17320 | } |
17321 | return false; |
17322 | }; |
17323 | |
17324 | if (!E.get()->isValueDependent() && |
17325 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
17326 | !CheckConstantExpressionAndKeepResult()) { |
17327 | MarkExpressionAsImmediateEscalating(E: E.get()); |
17328 | return E; |
17329 | } |
17330 | |
17331 | if (Cleanup.exprNeedsCleanups()) { |
17332 | // Since an immediate invocation is a full expression itself - it requires |
17333 | // an additional ExprWithCleanups node, but it can participate to a bigger |
17334 | // full expression which actually requires cleanups to be run after so |
17335 | // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it |
17336 | // may discard cleanups for outer expression too early. |
17337 | |
17338 | // Note that ExprWithCleanups created here must always have empty cleanup |
17339 | // objects: |
17340 | // - compound literals do not create cleanup objects in C++ and immediate |
17341 | // invocations are C++-only. |
17342 | // - blocks are not allowed inside constant expressions and compiler will |
17343 | // issue an error if they appear there. |
17344 | // |
17345 | // Hence, in correct code any cleanup objects created inside current |
17346 | // evaluation context must be outside the immediate invocation. |
17347 | E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(), |
17348 | CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {}); |
17349 | } |
17350 | |
17351 | ConstantExpr *Res = ConstantExpr::Create( |
17352 | Context: getASTContext(), E: E.get(), |
17353 | Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(), |
17354 | Context: getASTContext()), |
17355 | /*IsImmediateInvocation*/ true); |
17356 | if (Cached.hasValue()) |
17357 | Res->MoveIntoResult(Value&: Cached, Context: getASTContext()); |
17358 | /// Value-dependent constant expressions should not be immediately |
17359 | /// evaluated until they are instantiated. |
17360 | if (!Res->isValueDependent()) |
17361 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0); |
17362 | return Res; |
17363 | } |
17364 | |
17365 | static void EvaluateAndDiagnoseImmediateInvocation( |
17366 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { |
17367 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
17368 | Expr::EvalResult Eval; |
17369 | Eval.Diag = &Notes; |
17370 | ConstantExpr *CE = Candidate.getPointer(); |
17371 | bool Result = CE->EvaluateAsConstantExpr( |
17372 | Result&: Eval, Ctx: SemaRef.getASTContext(), Kind: ConstantExprKind::ImmediateInvocation); |
17373 | if (!Result || !Notes.empty()) { |
17374 | SemaRef.FailedImmediateInvocations.insert(Ptr: CE); |
17375 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); |
17376 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(Val: InnerExpr)) |
17377 | InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit(); |
17378 | FunctionDecl *FD = nullptr; |
17379 | if (auto *Call = dyn_cast<CallExpr>(Val: InnerExpr)) |
17380 | FD = cast<FunctionDecl>(Val: Call->getCalleeDecl()); |
17381 | else if (auto *Call = dyn_cast<CXXConstructExpr>(Val: InnerExpr)) |
17382 | FD = Call->getConstructor(); |
17383 | else if (auto *Cast = dyn_cast<CastExpr>(Val: InnerExpr)) |
17384 | FD = dyn_cast_or_null<FunctionDecl>(Val: Cast->getConversionFunction()); |
17385 | |
17386 | assert(FD && FD->isImmediateFunction() && |
17387 | "could not find an immediate function in this expression" ); |
17388 | if (FD->isInvalidDecl()) |
17389 | return; |
17390 | SemaRef.Diag(Loc: CE->getBeginLoc(), DiagID: diag::err_invalid_consteval_call) |
17391 | << FD << FD->isConsteval(); |
17392 | if (auto Context = |
17393 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
17394 | SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer) |
17395 | << Context->Decl; |
17396 | SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at); |
17397 | } |
17398 | if (!FD->isConsteval()) |
17399 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
17400 | for (auto &Note : Notes) |
17401 | SemaRef.Diag(Loc: Note.first, PD: Note.second); |
17402 | return; |
17403 | } |
17404 | CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext()); |
17405 | } |
17406 | |
17407 | static void RemoveNestedImmediateInvocation( |
17408 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, |
17409 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { |
17410 | struct ComplexRemove : TreeTransform<ComplexRemove> { |
17411 | using Base = TreeTransform<ComplexRemove>; |
17412 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
17413 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; |
17414 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator |
17415 | CurrentII; |
17416 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, |
17417 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, |
17418 | SmallVector<Sema::ImmediateInvocationCandidate, |
17419 | 4>::reverse_iterator Current) |
17420 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} |
17421 | void RemoveImmediateInvocation(ConstantExpr* E) { |
17422 | auto It = std::find_if(first: CurrentII, last: IISet.rend(), |
17423 | pred: [E](Sema::ImmediateInvocationCandidate Elem) { |
17424 | return Elem.getPointer() == E; |
17425 | }); |
17426 | // It is possible that some subexpression of the current immediate |
17427 | // invocation was handled from another expression evaluation context. Do |
17428 | // not handle the current immediate invocation if some of its |
17429 | // subexpressions failed before. |
17430 | if (It == IISet.rend()) { |
17431 | if (SemaRef.FailedImmediateInvocations.contains(Ptr: E)) |
17432 | CurrentII->setInt(1); |
17433 | } else { |
17434 | It->setInt(1); // Mark as deleted |
17435 | } |
17436 | } |
17437 | ExprResult TransformConstantExpr(ConstantExpr *E) { |
17438 | if (!E->isImmediateInvocation()) |
17439 | return Base::TransformConstantExpr(E); |
17440 | RemoveImmediateInvocation(E); |
17441 | return Base::TransformExpr(E: E->getSubExpr()); |
17442 | } |
17443 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so |
17444 | /// we need to remove its DeclRefExpr from the DRSet. |
17445 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
17446 | DRSet.erase(Ptr: cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit())); |
17447 | return Base::TransformCXXOperatorCallExpr(E); |
17448 | } |
17449 | /// Base::TransformUserDefinedLiteral doesn't preserve the |
17450 | /// UserDefinedLiteral node. |
17451 | ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; } |
17452 | /// Base::TransformInitializer skips ConstantExpr so we need to visit them |
17453 | /// here. |
17454 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { |
17455 | if (!Init) |
17456 | return Init; |
17457 | /// ConstantExpr are the first layer of implicit node to be removed so if |
17458 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. |
17459 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Init)) |
17460 | if (CE->isImmediateInvocation()) |
17461 | RemoveImmediateInvocation(E: CE); |
17462 | return Base::TransformInitializer(Init, NotCopyInit); |
17463 | } |
17464 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
17465 | DRSet.erase(Ptr: E); |
17466 | return E; |
17467 | } |
17468 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
17469 | // Do not rebuild lambdas to avoid creating a new type. |
17470 | // Lambdas have already been processed inside their eval context. |
17471 | return E; |
17472 | } |
17473 | bool AlwaysRebuild() { return false; } |
17474 | bool ReplacingOriginal() { return true; } |
17475 | bool AllowSkippingCXXConstructExpr() { |
17476 | bool Res = AllowSkippingFirstCXXConstructExpr; |
17477 | AllowSkippingFirstCXXConstructExpr = true; |
17478 | return Res; |
17479 | } |
17480 | bool AllowSkippingFirstCXXConstructExpr = true; |
17481 | } Transformer(SemaRef, Rec.ReferenceToConsteval, |
17482 | Rec.ImmediateInvocationCandidates, It); |
17483 | |
17484 | /// CXXConstructExpr with a single argument are getting skipped by |
17485 | /// TreeTransform in some situtation because they could be implicit. This |
17486 | /// can only occur for the top-level CXXConstructExpr because it is used |
17487 | /// nowhere in the expression being transformed therefore will not be rebuilt. |
17488 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from |
17489 | /// skipping the first CXXConstructExpr. |
17490 | if (isa<CXXConstructExpr>(Val: It->getPointer()->IgnoreImplicit())) |
17491 | Transformer.AllowSkippingFirstCXXConstructExpr = false; |
17492 | |
17493 | ExprResult Res = Transformer.TransformExpr(E: It->getPointer()->getSubExpr()); |
17494 | // The result may not be usable in case of previous compilation errors. |
17495 | // In this case evaluation of the expression may result in crash so just |
17496 | // don't do anything further with the result. |
17497 | if (Res.isUsable()) { |
17498 | Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res); |
17499 | It->getPointer()->setSubExpr(Res.get()); |
17500 | } |
17501 | } |
17502 | |
17503 | static void |
17504 | HandleImmediateInvocations(Sema &SemaRef, |
17505 | Sema::ExpressionEvaluationContextRecord &Rec) { |
17506 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && |
17507 | Rec.ReferenceToConsteval.size() == 0) || |
17508 | Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation) |
17509 | return; |
17510 | |
17511 | /// When we have more than 1 ImmediateInvocationCandidates or previously |
17512 | /// failed immediate invocations, we need to check for nested |
17513 | /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics. |
17514 | /// Otherwise we only need to remove ReferenceToConsteval in the immediate |
17515 | /// invocation. |
17516 | if (Rec.ImmediateInvocationCandidates.size() > 1 || |
17517 | !SemaRef.FailedImmediateInvocations.empty()) { |
17518 | |
17519 | /// Prevent sema calls during the tree transform from adding pointers that |
17520 | /// are already in the sets. |
17521 | llvm::SaveAndRestore DisableIITracking( |
17522 | SemaRef.RebuildingImmediateInvocation, true); |
17523 | |
17524 | /// Prevent diagnostic during tree transfrom as they are duplicates |
17525 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); |
17526 | |
17527 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); |
17528 | It != Rec.ImmediateInvocationCandidates.rend(); It++) |
17529 | if (!It->getInt()) |
17530 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); |
17531 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && |
17532 | Rec.ReferenceToConsteval.size()) { |
17533 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { |
17534 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
17535 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} |
17536 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
17537 | DRSet.erase(Ptr: E); |
17538 | return DRSet.size(); |
17539 | } |
17540 | } Visitor(Rec.ReferenceToConsteval); |
17541 | Visitor.TraverseStmt( |
17542 | S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); |
17543 | } |
17544 | for (auto CE : Rec.ImmediateInvocationCandidates) |
17545 | if (!CE.getInt()) |
17546 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE); |
17547 | for (auto *DR : Rec.ReferenceToConsteval) { |
17548 | // If the expression is immediate escalating, it is not an error; |
17549 | // The outer context itself becomes immediate and further errors, |
17550 | // if any, will be handled by DiagnoseImmediateEscalatingReason. |
17551 | if (DR->isImmediateEscalating()) |
17552 | continue; |
17553 | auto *FD = cast<FunctionDecl>(Val: DR->getDecl()); |
17554 | const NamedDecl *ND = FD; |
17555 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND); |
17556 | MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD))) |
17557 | ND = MD->getParent(); |
17558 | |
17559 | // C++23 [expr.const]/p16 |
17560 | // An expression or conversion is immediate-escalating if it is not |
17561 | // initially in an immediate function context and it is [...] a |
17562 | // potentially-evaluated id-expression that denotes an immediate function |
17563 | // that is not a subexpression of an immediate invocation. |
17564 | bool ImmediateEscalating = false; |
17565 | bool IsPotentiallyEvaluated = |
17566 | Rec.Context == |
17567 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated || |
17568 | Rec.Context == |
17569 | Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed; |
17570 | if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated) |
17571 | ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext; |
17572 | |
17573 | if (!Rec.InImmediateEscalatingFunctionContext || |
17574 | (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) { |
17575 | SemaRef.Diag(Loc: DR->getBeginLoc(), DiagID: diag::err_invalid_consteval_take_address) |
17576 | << ND << isa<CXXRecordDecl>(Val: ND) << FD->isConsteval(); |
17577 | SemaRef.Diag(Loc: ND->getLocation(), DiagID: diag::note_declared_at); |
17578 | if (auto Context = |
17579 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
17580 | SemaRef.Diag(Loc: Context->Loc, DiagID: diag::note_invalid_consteval_initializer) |
17581 | << Context->Decl; |
17582 | SemaRef.Diag(Loc: Context->Decl->getBeginLoc(), DiagID: diag::note_declared_at); |
17583 | } |
17584 | if (FD->isImmediateEscalating() && !FD->isConsteval()) |
17585 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
17586 | |
17587 | } else { |
17588 | SemaRef.MarkExpressionAsImmediateEscalating(E: DR); |
17589 | } |
17590 | } |
17591 | } |
17592 | |
17593 | void Sema::PopExpressionEvaluationContext() { |
17594 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); |
17595 | unsigned NumTypos = Rec.NumTypos; |
17596 | |
17597 | if (!Rec.Lambdas.empty()) { |
17598 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; |
17599 | if (!getLangOpts().CPlusPlus20 && |
17600 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || |
17601 | Rec.isUnevaluated() || |
17602 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { |
17603 | unsigned D; |
17604 | if (Rec.isUnevaluated()) { |
17605 | // C++11 [expr.prim.lambda]p2: |
17606 | // A lambda-expression shall not appear in an unevaluated operand |
17607 | // (Clause 5). |
17608 | D = diag::err_lambda_unevaluated_operand; |
17609 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { |
17610 | // C++1y [expr.const]p2: |
17611 | // A conditional-expression e is a core constant expression unless the |
17612 | // evaluation of e, following the rules of the abstract machine, would |
17613 | // evaluate [...] a lambda-expression. |
17614 | D = diag::err_lambda_in_constant_expression; |
17615 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { |
17616 | // C++17 [expr.prim.lamda]p2: |
17617 | // A lambda-expression shall not appear [...] in a template-argument. |
17618 | D = diag::err_lambda_in_invalid_context; |
17619 | } else |
17620 | llvm_unreachable("Couldn't infer lambda error message." ); |
17621 | |
17622 | for (const auto *L : Rec.Lambdas) |
17623 | Diag(Loc: L->getBeginLoc(), DiagID: D); |
17624 | } |
17625 | } |
17626 | |
17627 | // Append the collected materialized temporaries into previous context before |
17628 | // exit if the previous also is a lifetime extending context. |
17629 | auto &PrevRecord = parentEvaluationContext(); |
17630 | if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext && |
17631 | PrevRecord.InLifetimeExtendingContext && |
17632 | !Rec.ForRangeLifetimeExtendTemps.empty()) { |
17633 | PrevRecord.ForRangeLifetimeExtendTemps.append( |
17634 | RHS: Rec.ForRangeLifetimeExtendTemps); |
17635 | } |
17636 | |
17637 | WarnOnPendingNoDerefs(Rec); |
17638 | HandleImmediateInvocations(SemaRef&: *this, Rec); |
17639 | |
17640 | // Warn on any volatile-qualified simple-assignments that are not discarded- |
17641 | // value expressions nor unevaluated operands (those cases get removed from |
17642 | // this list by CheckUnusedVolatileAssignment). |
17643 | for (auto *BO : Rec.VolatileAssignmentLHSs) |
17644 | Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_deprecated_simple_assign_volatile) |
17645 | << BO->getType(); |
17646 | |
17647 | // When are coming out of an unevaluated context, clear out any |
17648 | // temporaries that we may have created as part of the evaluation of |
17649 | // the expression in that context: they aren't relevant because they |
17650 | // will never be constructed. |
17651 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { |
17652 | ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects, |
17653 | CE: ExprCleanupObjects.end()); |
17654 | Cleanup = Rec.ParentCleanup; |
17655 | CleanupVarDeclMarking(); |
17656 | std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs); |
17657 | // Otherwise, merge the contexts together. |
17658 | } else { |
17659 | Cleanup.mergeFrom(Rhs: Rec.ParentCleanup); |
17660 | MaybeODRUseExprs.insert(Start: Rec.SavedMaybeODRUseExprs.begin(), |
17661 | End: Rec.SavedMaybeODRUseExprs.end()); |
17662 | } |
17663 | |
17664 | // Pop the current expression evaluation context off the stack. |
17665 | ExprEvalContexts.pop_back(); |
17666 | |
17667 | // The global expression evaluation context record is never popped. |
17668 | ExprEvalContexts.back().NumTypos += NumTypos; |
17669 | } |
17670 | |
17671 | void Sema::DiscardCleanupsInEvaluationContext() { |
17672 | ExprCleanupObjects.erase( |
17673 | CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, |
17674 | CE: ExprCleanupObjects.end()); |
17675 | Cleanup.reset(); |
17676 | MaybeODRUseExprs.clear(); |
17677 | } |
17678 | |
17679 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { |
17680 | ExprResult Result = CheckPlaceholderExpr(E); |
17681 | if (Result.isInvalid()) |
17682 | return ExprError(); |
17683 | E = Result.get(); |
17684 | if (!E->getType()->isVariablyModifiedType()) |
17685 | return E; |
17686 | return TransformToPotentiallyEvaluated(E); |
17687 | } |
17688 | |
17689 | /// Are we in a context that is potentially constant evaluated per C++20 |
17690 | /// [expr.const]p12? |
17691 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { |
17692 | /// C++2a [expr.const]p12: |
17693 | // An expression or conversion is potentially constant evaluated if it is |
17694 | switch (SemaRef.ExprEvalContexts.back().Context) { |
17695 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
17696 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: |
17697 | |
17698 | // -- a manifestly constant-evaluated expression, |
17699 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
17700 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
17701 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
17702 | // -- a potentially-evaluated expression, |
17703 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
17704 | // -- an immediate subexpression of a braced-init-list, |
17705 | |
17706 | // -- [FIXME] an expression of the form & cast-expression that occurs |
17707 | // within a templated entity |
17708 | // -- a subexpression of one of the above that is not a subexpression of |
17709 | // a nested unevaluated operand. |
17710 | return true; |
17711 | |
17712 | case Sema::ExpressionEvaluationContext::Unevaluated: |
17713 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
17714 | // Expressions in this context are never evaluated. |
17715 | return false; |
17716 | } |
17717 | llvm_unreachable("Invalid context" ); |
17718 | } |
17719 | |
17720 | /// Return true if this function has a calling convention that requires mangling |
17721 | /// in the size of the parameter pack. |
17722 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { |
17723 | // These manglings don't do anything on non-Windows or non-x86 platforms, so |
17724 | // we don't need parameter type sizes. |
17725 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); |
17726 | if (!TT.isOSWindows() || !TT.isX86()) |
17727 | return false; |
17728 | |
17729 | // If this is C++ and this isn't an extern "C" function, parameters do not |
17730 | // need to be complete. In this case, C++ mangling will apply, which doesn't |
17731 | // use the size of the parameters. |
17732 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) |
17733 | return false; |
17734 | |
17735 | // Stdcall, fastcall, and vectorcall need this special treatment. |
17736 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
17737 | switch (CC) { |
17738 | case CC_X86StdCall: |
17739 | case CC_X86FastCall: |
17740 | case CC_X86VectorCall: |
17741 | return true; |
17742 | default: |
17743 | break; |
17744 | } |
17745 | return false; |
17746 | } |
17747 | |
17748 | /// Require that all of the parameter types of function be complete. Normally, |
17749 | /// parameter types are only required to be complete when a function is called |
17750 | /// or defined, but to mangle functions with certain calling conventions, the |
17751 | /// mangler needs to know the size of the parameter list. In this situation, |
17752 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles |
17753 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually |
17754 | /// result in a linker error. Clang doesn't implement this behavior, and instead |
17755 | /// attempts to error at compile time. |
17756 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, |
17757 | SourceLocation Loc) { |
17758 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { |
17759 | FunctionDecl *FD; |
17760 | ParmVarDecl *Param; |
17761 | |
17762 | public: |
17763 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) |
17764 | : FD(FD), Param(Param) {} |
17765 | |
17766 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
17767 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
17768 | StringRef CCName; |
17769 | switch (CC) { |
17770 | case CC_X86StdCall: |
17771 | CCName = "stdcall" ; |
17772 | break; |
17773 | case CC_X86FastCall: |
17774 | CCName = "fastcall" ; |
17775 | break; |
17776 | case CC_X86VectorCall: |
17777 | CCName = "vectorcall" ; |
17778 | break; |
17779 | default: |
17780 | llvm_unreachable("CC does not need mangling" ); |
17781 | } |
17782 | |
17783 | S.Diag(Loc, DiagID: diag::err_cconv_incomplete_param_type) |
17784 | << Param->getDeclName() << FD->getDeclName() << CCName; |
17785 | } |
17786 | }; |
17787 | |
17788 | for (ParmVarDecl *Param : FD->parameters()) { |
17789 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); |
17790 | S.RequireCompleteType(Loc, T: Param->getType(), Diagnoser); |
17791 | } |
17792 | } |
17793 | |
17794 | namespace { |
17795 | enum class OdrUseContext { |
17796 | /// Declarations in this context are not odr-used. |
17797 | None, |
17798 | /// Declarations in this context are formally odr-used, but this is a |
17799 | /// dependent context. |
17800 | Dependent, |
17801 | /// Declarations in this context are odr-used but not actually used (yet). |
17802 | FormallyOdrUsed, |
17803 | /// Declarations in this context are used. |
17804 | Used |
17805 | }; |
17806 | } |
17807 | |
17808 | /// Are we within a context in which references to resolved functions or to |
17809 | /// variables result in odr-use? |
17810 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { |
17811 | OdrUseContext Result; |
17812 | |
17813 | switch (SemaRef.ExprEvalContexts.back().Context) { |
17814 | case Sema::ExpressionEvaluationContext::Unevaluated: |
17815 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
17816 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
17817 | return OdrUseContext::None; |
17818 | |
17819 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
17820 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: |
17821 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
17822 | Result = OdrUseContext::Used; |
17823 | break; |
17824 | |
17825 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
17826 | Result = OdrUseContext::FormallyOdrUsed; |
17827 | break; |
17828 | |
17829 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
17830 | // A default argument formally results in odr-use, but doesn't actually |
17831 | // result in a use in any real sense until it itself is used. |
17832 | Result = OdrUseContext::FormallyOdrUsed; |
17833 | break; |
17834 | } |
17835 | |
17836 | if (SemaRef.CurContext->isDependentContext()) |
17837 | return OdrUseContext::Dependent; |
17838 | |
17839 | return Result; |
17840 | } |
17841 | |
17842 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { |
17843 | if (!Func->isConstexpr()) |
17844 | return false; |
17845 | |
17846 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) |
17847 | return true; |
17848 | auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func); |
17849 | return CCD && CCD->getInheritedConstructor(); |
17850 | } |
17851 | |
17852 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
17853 | bool MightBeOdrUse) { |
17854 | assert(Func && "No function?" ); |
17855 | |
17856 | Func->setReferenced(); |
17857 | |
17858 | // Recursive functions aren't really used until they're used from some other |
17859 | // context. |
17860 | bool IsRecursiveCall = CurContext == Func; |
17861 | |
17862 | // C++11 [basic.def.odr]p3: |
17863 | // A function whose name appears as a potentially-evaluated expression is |
17864 | // odr-used if it is the unique lookup result or the selected member of a |
17865 | // set of overloaded functions [...]. |
17866 | // |
17867 | // We (incorrectly) mark overload resolution as an unevaluated context, so we |
17868 | // can just check that here. |
17869 | OdrUseContext OdrUse = |
17870 | MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None; |
17871 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) |
17872 | OdrUse = OdrUseContext::FormallyOdrUsed; |
17873 | |
17874 | // Trivial default constructors and destructors are never actually used. |
17875 | // FIXME: What about other special members? |
17876 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && |
17877 | OdrUse == OdrUseContext::Used) { |
17878 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) |
17879 | if (Constructor->isDefaultConstructor()) |
17880 | OdrUse = OdrUseContext::FormallyOdrUsed; |
17881 | if (isa<CXXDestructorDecl>(Val: Func)) |
17882 | OdrUse = OdrUseContext::FormallyOdrUsed; |
17883 | } |
17884 | |
17885 | // C++20 [expr.const]p12: |
17886 | // A function [...] is needed for constant evaluation if it is [...] a |
17887 | // constexpr function that is named by an expression that is potentially |
17888 | // constant evaluated |
17889 | bool NeededForConstantEvaluation = |
17890 | isPotentiallyConstantEvaluatedContext(SemaRef&: *this) && |
17891 | isImplicitlyDefinableConstexprFunction(Func); |
17892 | |
17893 | // Determine whether we require a function definition to exist, per |
17894 | // C++11 [temp.inst]p3: |
17895 | // Unless a function template specialization has been explicitly |
17896 | // instantiated or explicitly specialized, the function template |
17897 | // specialization is implicitly instantiated when the specialization is |
17898 | // referenced in a context that requires a function definition to exist. |
17899 | // C++20 [temp.inst]p7: |
17900 | // The existence of a definition of a [...] function is considered to |
17901 | // affect the semantics of the program if the [...] function is needed for |
17902 | // constant evaluation by an expression |
17903 | // C++20 [basic.def.odr]p10: |
17904 | // Every program shall contain exactly one definition of every non-inline |
17905 | // function or variable that is odr-used in that program outside of a |
17906 | // discarded statement |
17907 | // C++20 [special]p1: |
17908 | // The implementation will implicitly define [defaulted special members] |
17909 | // if they are odr-used or needed for constant evaluation. |
17910 | // |
17911 | // Note that we skip the implicit instantiation of templates that are only |
17912 | // used in unused default arguments or by recursive calls to themselves. |
17913 | // This is formally non-conforming, but seems reasonable in practice. |
17914 | bool NeedDefinition = |
17915 | !IsRecursiveCall && |
17916 | (OdrUse == OdrUseContext::Used || |
17917 | (NeededForConstantEvaluation && !Func->isPureVirtual())); |
17918 | |
17919 | // C++14 [temp.expl.spec]p6: |
17920 | // If a template [...] is explicitly specialized then that specialization |
17921 | // shall be declared before the first use of that specialization that would |
17922 | // cause an implicit instantiation to take place, in every translation unit |
17923 | // in which such a use occurs |
17924 | if (NeedDefinition && |
17925 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || |
17926 | Func->getMemberSpecializationInfo())) |
17927 | checkSpecializationReachability(Loc, Spec: Func); |
17928 | |
17929 | if (getLangOpts().CUDA) |
17930 | CUDA().CheckCall(Loc, Callee: Func); |
17931 | |
17932 | // If we need a definition, try to create one. |
17933 | if (NeedDefinition && !Func->getBody()) { |
17934 | runWithSufficientStackSpace(Loc, Fn: [&] { |
17935 | if (CXXConstructorDecl *Constructor = |
17936 | dyn_cast<CXXConstructorDecl>(Val: Func)) { |
17937 | Constructor = cast<CXXConstructorDecl>(Val: Constructor->getFirstDecl()); |
17938 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { |
17939 | if (Constructor->isDefaultConstructor()) { |
17940 | if (Constructor->isTrivial() && |
17941 | !Constructor->hasAttr<DLLExportAttr>()) |
17942 | return; |
17943 | DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
17944 | } else if (Constructor->isCopyConstructor()) { |
17945 | DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor); |
17946 | } else if (Constructor->isMoveConstructor()) { |
17947 | DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor); |
17948 | } |
17949 | } else if (Constructor->getInheritedConstructor()) { |
17950 | DefineInheritingConstructor(UseLoc: Loc, Constructor); |
17951 | } |
17952 | } else if (CXXDestructorDecl *Destructor = |
17953 | dyn_cast<CXXDestructorDecl>(Val: Func)) { |
17954 | Destructor = cast<CXXDestructorDecl>(Val: Destructor->getFirstDecl()); |
17955 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { |
17956 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) |
17957 | return; |
17958 | DefineImplicitDestructor(CurrentLocation: Loc, Destructor); |
17959 | } |
17960 | if (Destructor->isVirtual() && getLangOpts().AppleKext) |
17961 | MarkVTableUsed(Loc, Class: Destructor->getParent()); |
17962 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) { |
17963 | if (MethodDecl->isOverloadedOperator() && |
17964 | MethodDecl->getOverloadedOperator() == OO_Equal) { |
17965 | MethodDecl = cast<CXXMethodDecl>(Val: MethodDecl->getFirstDecl()); |
17966 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { |
17967 | if (MethodDecl->isCopyAssignmentOperator()) |
17968 | DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl); |
17969 | else if (MethodDecl->isMoveAssignmentOperator()) |
17970 | DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl); |
17971 | } |
17972 | } else if (isa<CXXConversionDecl>(Val: MethodDecl) && |
17973 | MethodDecl->getParent()->isLambda()) { |
17974 | CXXConversionDecl *Conversion = |
17975 | cast<CXXConversionDecl>(Val: MethodDecl->getFirstDecl()); |
17976 | if (Conversion->isLambdaToBlockPointerConversion()) |
17977 | DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
17978 | else |
17979 | DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
17980 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) |
17981 | MarkVTableUsed(Loc, Class: MethodDecl->getParent()); |
17982 | } |
17983 | |
17984 | if (Func->isDefaulted() && !Func->isDeleted()) { |
17985 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func); |
17986 | if (DCK != DefaultedComparisonKind::None) |
17987 | DefineDefaultedComparison(Loc, FD: Func, DCK); |
17988 | } |
17989 | |
17990 | // Implicit instantiation of function templates and member functions of |
17991 | // class templates. |
17992 | if (Func->isImplicitlyInstantiable()) { |
17993 | TemplateSpecializationKind TSK = |
17994 | Func->getTemplateSpecializationKindForInstantiation(); |
17995 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); |
17996 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
17997 | if (FirstInstantiation) { |
17998 | PointOfInstantiation = Loc; |
17999 | if (auto *MSI = Func->getMemberSpecializationInfo()) |
18000 | MSI->setPointOfInstantiation(Loc); |
18001 | // FIXME: Notify listener. |
18002 | else |
18003 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
18004 | } else if (TSK != TSK_ImplicitInstantiation) { |
18005 | // Use the point of use as the point of instantiation, instead of the |
18006 | // point of explicit instantiation (which we track as the actual point |
18007 | // of instantiation). This gives better backtraces in diagnostics. |
18008 | PointOfInstantiation = Loc; |
18009 | } |
18010 | |
18011 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || |
18012 | Func->isConstexpr()) { |
18013 | if (isa<CXXRecordDecl>(Val: Func->getDeclContext()) && |
18014 | cast<CXXRecordDecl>(Val: Func->getDeclContext())->isLocalClass() && |
18015 | CodeSynthesisContexts.size()) |
18016 | PendingLocalImplicitInstantiations.push_back( |
18017 | x: std::make_pair(x&: Func, y&: PointOfInstantiation)); |
18018 | else if (Func->isConstexpr()) |
18019 | // Do not defer instantiations of constexpr functions, to avoid the |
18020 | // expression evaluator needing to call back into Sema if it sees a |
18021 | // call to such a function. |
18022 | InstantiateFunctionDefinition(PointOfInstantiation, Function: Func); |
18023 | else { |
18024 | Func->setInstantiationIsPending(true); |
18025 | PendingInstantiations.push_back( |
18026 | x: std::make_pair(x&: Func, y&: PointOfInstantiation)); |
18027 | // Notify the consumer that a function was implicitly instantiated. |
18028 | Consumer.HandleCXXImplicitFunctionInstantiation(D: Func); |
18029 | } |
18030 | } |
18031 | } else { |
18032 | // Walk redefinitions, as some of them may be instantiable. |
18033 | for (auto *i : Func->redecls()) { |
18034 | if (!i->isUsed(CheckUsedAttr: false) && i->isImplicitlyInstantiable()) |
18035 | MarkFunctionReferenced(Loc, Func: i, MightBeOdrUse); |
18036 | } |
18037 | } |
18038 | }); |
18039 | } |
18040 | |
18041 | // If a constructor was defined in the context of a default parameter |
18042 | // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed |
18043 | // context), its initializers may not be referenced yet. |
18044 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) { |
18045 | EnterExpressionEvaluationContext EvalContext( |
18046 | *this, |
18047 | Constructor->isImmediateFunction() |
18048 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
18049 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
18050 | Constructor); |
18051 | for (CXXCtorInitializer *Init : Constructor->inits()) { |
18052 | if (Init->isInClassMemberInitializer()) |
18053 | runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() { |
18054 | MarkDeclarationsReferencedInExpr(E: Init->getInit()); |
18055 | }); |
18056 | } |
18057 | } |
18058 | |
18059 | // C++14 [except.spec]p17: |
18060 | // An exception-specification is considered to be needed when: |
18061 | // - the function is odr-used or, if it appears in an unevaluated operand, |
18062 | // would be odr-used if the expression were potentially-evaluated; |
18063 | // |
18064 | // Note, we do this even if MightBeOdrUse is false. That indicates that the |
18065 | // function is a pure virtual function we're calling, and in that case the |
18066 | // function was selected by overload resolution and we need to resolve its |
18067 | // exception specification for a different reason. |
18068 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); |
18069 | if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) |
18070 | ResolveExceptionSpec(Loc, FPT); |
18071 | |
18072 | // A callee could be called by a host function then by a device function. |
18073 | // If we only try recording once, we will miss recording the use on device |
18074 | // side. Therefore keep trying until it is recorded. |
18075 | if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice && |
18076 | !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func)) |
18077 | CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func); |
18078 | |
18079 | // If this is the first "real" use, act on that. |
18080 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { |
18081 | // Keep track of used but undefined functions. |
18082 | if (!Func->isDefined()) { |
18083 | if (mightHaveNonExternalLinkage(FD: Func)) |
18084 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18085 | else if (Func->getMostRecentDecl()->isInlined() && |
18086 | !LangOpts.GNUInline && |
18087 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) |
18088 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18089 | else if (isExternalWithNoLinkageType(VD: Func)) |
18090 | UndefinedButUsed.insert(KV: std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18091 | } |
18092 | |
18093 | // Some x86 Windows calling conventions mangle the size of the parameter |
18094 | // pack into the name. Computing the size of the parameters requires the |
18095 | // parameter types to be complete. Check that now. |
18096 | if (funcHasParameterSizeMangling(S&: *this, FD: Func)) |
18097 | CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc); |
18098 | |
18099 | // In the MS C++ ABI, the compiler emits destructor variants where they are |
18100 | // used. If the destructor is used here but defined elsewhere, mark the |
18101 | // virtual base destructors referenced. If those virtual base destructors |
18102 | // are inline, this will ensure they are defined when emitting the complete |
18103 | // destructor variant. This checking may be redundant if the destructor is |
18104 | // provided later in this TU. |
18105 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
18106 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) { |
18107 | CXXRecordDecl *Parent = Dtor->getParent(); |
18108 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) |
18109 | CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor); |
18110 | } |
18111 | } |
18112 | |
18113 | Func->markUsed(C&: Context); |
18114 | } |
18115 | } |
18116 | |
18117 | /// Directly mark a variable odr-used. Given a choice, prefer to use |
18118 | /// MarkVariableReferenced since it does additional checks and then |
18119 | /// calls MarkVarDeclODRUsed. |
18120 | /// If the variable must be captured: |
18121 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext |
18122 | /// - else capture it in the DeclContext that maps to the |
18123 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. |
18124 | static void |
18125 | MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, |
18126 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { |
18127 | // Keep track of used but undefined variables. |
18128 | // FIXME: We shouldn't suppress this warning for static data members. |
18129 | VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); |
18130 | assert(Var && "expected a capturable variable" ); |
18131 | |
18132 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && |
18133 | (!Var->isExternallyVisible() || Var->isInline() || |
18134 | SemaRef.isExternalWithNoLinkageType(VD: Var)) && |
18135 | !(Var->isStaticDataMember() && Var->hasInit())) { |
18136 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; |
18137 | if (old.isInvalid()) |
18138 | old = Loc; |
18139 | } |
18140 | QualType CaptureType, DeclRefType; |
18141 | if (SemaRef.LangOpts.OpenMP) |
18142 | SemaRef.OpenMP().tryCaptureOpenMPLambdas(V); |
18143 | SemaRef.tryCaptureVariable(Var: V, Loc, Kind: Sema::TryCapture_Implicit, |
18144 | /*EllipsisLoc*/ SourceLocation(), |
18145 | /*BuildAndDiagnose*/ true, CaptureType, |
18146 | DeclRefType, FunctionScopeIndexToStopAt); |
18147 | |
18148 | if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { |
18149 | auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext); |
18150 | auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var); |
18151 | auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD); |
18152 | if (VarTarget == SemaCUDA::CVT_Host && |
18153 | (UserTarget == CUDAFunctionTarget::Device || |
18154 | UserTarget == CUDAFunctionTarget::HostDevice || |
18155 | UserTarget == CUDAFunctionTarget::Global)) { |
18156 | // Diagnose ODR-use of host global variables in device functions. |
18157 | // Reference of device global variables in host functions is allowed |
18158 | // through shadow variables therefore it is not diagnosed. |
18159 | if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) { |
18160 | SemaRef.targetDiag(Loc, DiagID: diag::err_ref_bad_target) |
18161 | << /*host*/ 2 << /*variable*/ 1 << Var |
18162 | << llvm::to_underlying(E: UserTarget); |
18163 | SemaRef.targetDiag(Loc: Var->getLocation(), |
18164 | DiagID: Var->getType().isConstQualified() |
18165 | ? diag::note_cuda_const_var_unpromoted |
18166 | : diag::note_cuda_host_var); |
18167 | } |
18168 | } else if (VarTarget == SemaCUDA::CVT_Device && |
18169 | !Var->hasAttr<CUDASharedAttr>() && |
18170 | (UserTarget == CUDAFunctionTarget::Host || |
18171 | UserTarget == CUDAFunctionTarget::HostDevice)) { |
18172 | // Record a CUDA/HIP device side variable if it is ODR-used |
18173 | // by host code. This is done conservatively, when the variable is |
18174 | // referenced in any of the following contexts: |
18175 | // - a non-function context |
18176 | // - a host function |
18177 | // - a host device function |
18178 | // This makes the ODR-use of the device side variable by host code to |
18179 | // be visible in the device compilation for the compiler to be able to |
18180 | // emit template variables instantiated by host code only and to |
18181 | // externalize the static device side variable ODR-used by host code. |
18182 | if (!Var->hasExternalStorage()) |
18183 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var); |
18184 | else if (SemaRef.LangOpts.GPURelocatableDeviceCode && |
18185 | (!FD || (!FD->getDescribedFunctionTemplate() && |
18186 | SemaRef.getASTContext().GetGVALinkageForFunction(FD) == |
18187 | GVA_StrongExternal))) |
18188 | SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(V: Var); |
18189 | } |
18190 | } |
18191 | |
18192 | V->markUsed(C&: SemaRef.Context); |
18193 | } |
18194 | |
18195 | void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, |
18196 | SourceLocation Loc, |
18197 | unsigned CapturingScopeIndex) { |
18198 | MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex); |
18199 | } |
18200 | |
18201 | void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, |
18202 | ValueDecl *var) { |
18203 | DeclContext *VarDC = var->getDeclContext(); |
18204 | |
18205 | // If the parameter still belongs to the translation unit, then |
18206 | // we're actually just using one parameter in the declaration of |
18207 | // the next. |
18208 | if (isa<ParmVarDecl>(Val: var) && |
18209 | isa<TranslationUnitDecl>(Val: VarDC)) |
18210 | return; |
18211 | |
18212 | // For C code, don't diagnose about capture if we're not actually in code |
18213 | // right now; it's impossible to write a non-constant expression outside of |
18214 | // function context, so we'll get other (more useful) diagnostics later. |
18215 | // |
18216 | // For C++, things get a bit more nasty... it would be nice to suppress this |
18217 | // diagnostic for certain cases like using a local variable in an array bound |
18218 | // for a member of a local class, but the correct predicate is not obvious. |
18219 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) |
18220 | return; |
18221 | |
18222 | unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0; |
18223 | unsigned ContextKind = 3; // unknown |
18224 | if (isa<CXXMethodDecl>(Val: VarDC) && |
18225 | cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) { |
18226 | ContextKind = 2; |
18227 | } else if (isa<FunctionDecl>(Val: VarDC)) { |
18228 | ContextKind = 0; |
18229 | } else if (isa<BlockDecl>(Val: VarDC)) { |
18230 | ContextKind = 1; |
18231 | } |
18232 | |
18233 | S.Diag(Loc: loc, DiagID: diag::err_reference_to_local_in_enclosing_context) |
18234 | << var << ValueKind << ContextKind << VarDC; |
18235 | S.Diag(Loc: var->getLocation(), DiagID: diag::note_entity_declared_at) |
18236 | << var; |
18237 | |
18238 | // FIXME: Add additional diagnostic info about class etc. which prevents |
18239 | // capture. |
18240 | } |
18241 | |
18242 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, |
18243 | ValueDecl *Var, |
18244 | bool &SubCapturesAreNested, |
18245 | QualType &CaptureType, |
18246 | QualType &DeclRefType) { |
18247 | // Check whether we've already captured it. |
18248 | if (CSI->CaptureMap.count(Val: Var)) { |
18249 | // If we found a capture, any subcaptures are nested. |
18250 | SubCapturesAreNested = true; |
18251 | |
18252 | // Retrieve the capture type for this variable. |
18253 | CaptureType = CSI->getCapture(Var).getCaptureType(); |
18254 | |
18255 | // Compute the type of an expression that refers to this variable. |
18256 | DeclRefType = CaptureType.getNonReferenceType(); |
18257 | |
18258 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy |
18259 | // are mutable in the sense that user can change their value - they are |
18260 | // private instances of the captured declarations. |
18261 | const Capture &Cap = CSI->getCapture(Var); |
18262 | if (Cap.isCopyCapture() && |
18263 | !(isa<LambdaScopeInfo>(Val: CSI) && |
18264 | !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) && |
18265 | !(isa<CapturedRegionScopeInfo>(Val: CSI) && |
18266 | cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP)) |
18267 | DeclRefType.addConst(); |
18268 | return true; |
18269 | } |
18270 | return false; |
18271 | } |
18272 | |
18273 | // Only block literals, captured statements, and lambda expressions can |
18274 | // capture; other scopes don't work. |
18275 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, |
18276 | ValueDecl *Var, |
18277 | SourceLocation Loc, |
18278 | const bool Diagnose, |
18279 | Sema &S) { |
18280 | if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC)) |
18281 | return getLambdaAwareParentOfDeclContext(DC); |
18282 | |
18283 | VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); |
18284 | if (Underlying) { |
18285 | if (Underlying->hasLocalStorage() && Diagnose) |
18286 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
18287 | } |
18288 | return nullptr; |
18289 | } |
18290 | |
18291 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
18292 | // certain types of variables (unnamed, variably modified types etc.) |
18293 | // so check for eligibility. |
18294 | static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, |
18295 | SourceLocation Loc, const bool Diagnose, |
18296 | Sema &S) { |
18297 | |
18298 | assert((isa<VarDecl, BindingDecl>(Var)) && |
18299 | "Only variables and structured bindings can be captured" ); |
18300 | |
18301 | bool IsBlock = isa<BlockScopeInfo>(Val: CSI); |
18302 | bool IsLambda = isa<LambdaScopeInfo>(Val: CSI); |
18303 | |
18304 | // Lambdas are not allowed to capture unnamed variables |
18305 | // (e.g. anonymous unions). |
18306 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm |
18307 | // assuming that's the intent. |
18308 | if (IsLambda && !Var->getDeclName()) { |
18309 | if (Diagnose) { |
18310 | S.Diag(Loc, DiagID: diag::err_lambda_capture_anonymous_var); |
18311 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_declared_at); |
18312 | } |
18313 | return false; |
18314 | } |
18315 | |
18316 | // Prohibit variably-modified types in blocks; they're difficult to deal with. |
18317 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { |
18318 | if (Diagnose) { |
18319 | S.Diag(Loc, DiagID: diag::err_ref_vm_type); |
18320 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18321 | } |
18322 | return false; |
18323 | } |
18324 | // Prohibit structs with flexible array members too. |
18325 | // We cannot capture what is in the tail end of the struct. |
18326 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { |
18327 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { |
18328 | if (Diagnose) { |
18329 | if (IsBlock) |
18330 | S.Diag(Loc, DiagID: diag::err_ref_flexarray_type); |
18331 | else |
18332 | S.Diag(Loc, DiagID: diag::err_lambda_capture_flexarray_type) << Var; |
18333 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18334 | } |
18335 | return false; |
18336 | } |
18337 | } |
18338 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
18339 | // Lambdas and captured statements are not allowed to capture __block |
18340 | // variables; they don't support the expected semantics. |
18341 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) { |
18342 | if (Diagnose) { |
18343 | S.Diag(Loc, DiagID: diag::err_capture_block_variable) << Var << !IsLambda; |
18344 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18345 | } |
18346 | return false; |
18347 | } |
18348 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks |
18349 | if (S.getLangOpts().OpenCL && IsBlock && |
18350 | Var->getType()->isBlockPointerType()) { |
18351 | if (Diagnose) |
18352 | S.Diag(Loc, DiagID: diag::err_opencl_block_ref_block); |
18353 | return false; |
18354 | } |
18355 | |
18356 | if (isa<BindingDecl>(Val: Var)) { |
18357 | if (!IsLambda || !S.getLangOpts().CPlusPlus) { |
18358 | if (Diagnose) |
18359 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
18360 | return false; |
18361 | } else if (Diagnose && S.getLangOpts().CPlusPlus) { |
18362 | S.Diag(Loc, DiagID: S.LangOpts.CPlusPlus20 |
18363 | ? diag::warn_cxx17_compat_capture_binding |
18364 | : diag::ext_capture_binding) |
18365 | << Var; |
18366 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var; |
18367 | } |
18368 | } |
18369 | |
18370 | return true; |
18371 | } |
18372 | |
18373 | // Returns true if the capture by block was successful. |
18374 | static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, |
18375 | SourceLocation Loc, const bool BuildAndDiagnose, |
18376 | QualType &CaptureType, QualType &DeclRefType, |
18377 | const bool Nested, Sema &S, bool Invalid) { |
18378 | bool ByRef = false; |
18379 | |
18380 | // Blocks are not allowed to capture arrays, excepting OpenCL. |
18381 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference |
18382 | // (decayed to pointers). |
18383 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { |
18384 | if (BuildAndDiagnose) { |
18385 | S.Diag(Loc, DiagID: diag::err_ref_array_type); |
18386 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18387 | Invalid = true; |
18388 | } else { |
18389 | return false; |
18390 | } |
18391 | } |
18392 | |
18393 | // Forbid the block-capture of autoreleasing variables. |
18394 | if (!Invalid && |
18395 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
18396 | if (BuildAndDiagnose) { |
18397 | S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) |
18398 | << /*block*/ 0; |
18399 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18400 | Invalid = true; |
18401 | } else { |
18402 | return false; |
18403 | } |
18404 | } |
18405 | |
18406 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. |
18407 | if (const auto *PT = CaptureType->getAs<PointerType>()) { |
18408 | QualType PointeeTy = PT->getPointeeType(); |
18409 | |
18410 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && |
18411 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && |
18412 | !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) { |
18413 | if (BuildAndDiagnose) { |
18414 | SourceLocation VarLoc = Var->getLocation(); |
18415 | S.Diag(Loc, DiagID: diag::warn_block_capture_autoreleasing); |
18416 | S.Diag(Loc: VarLoc, DiagID: diag::note_declare_parameter_strong); |
18417 | } |
18418 | } |
18419 | } |
18420 | |
18421 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
18422 | if (HasBlocksAttr || CaptureType->isReferenceType() || |
18423 | (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) { |
18424 | // Block capture by reference does not change the capture or |
18425 | // declaration reference types. |
18426 | ByRef = true; |
18427 | } else { |
18428 | // Block capture by copy introduces 'const'. |
18429 | CaptureType = CaptureType.getNonReferenceType().withConst(); |
18430 | DeclRefType = CaptureType; |
18431 | } |
18432 | |
18433 | // Actually capture the variable. |
18434 | if (BuildAndDiagnose) |
18435 | BSI->addCapture(Var, isBlock: HasBlocksAttr, isByref: ByRef, isNested: Nested, Loc, EllipsisLoc: SourceLocation(), |
18436 | CaptureType, Invalid); |
18437 | |
18438 | return !Invalid; |
18439 | } |
18440 | |
18441 | /// Capture the given variable in the captured region. |
18442 | static bool captureInCapturedRegion( |
18443 | CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, |
18444 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, |
18445 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, |
18446 | bool IsTopScope, Sema &S, bool Invalid) { |
18447 | // By default, capture variables by reference. |
18448 | bool ByRef = true; |
18449 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { |
18450 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); |
18451 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { |
18452 | // Using an LValue reference type is consistent with Lambdas (see below). |
18453 | if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) { |
18454 | bool HasConst = DeclRefType.isConstQualified(); |
18455 | DeclRefType = DeclRefType.getUnqualifiedType(); |
18456 | // Don't lose diagnostics about assignments to const. |
18457 | if (HasConst) |
18458 | DeclRefType.addConst(); |
18459 | } |
18460 | // Do not capture firstprivates in tasks. |
18461 | if (S.OpenMP().isOpenMPPrivateDecl(D: Var, Level: RSI->OpenMPLevel, |
18462 | CapLevel: RSI->OpenMPCaptureLevel) != OMPC_unknown) |
18463 | return true; |
18464 | ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel, |
18465 | OpenMPCaptureLevel: RSI->OpenMPCaptureLevel); |
18466 | } |
18467 | |
18468 | if (ByRef) |
18469 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
18470 | else |
18471 | CaptureType = DeclRefType; |
18472 | |
18473 | // Actually capture the variable. |
18474 | if (BuildAndDiagnose) |
18475 | RSI->addCapture(Var, /*isBlock*/ false, isByref: ByRef, isNested: RefersToCapturedVariable, |
18476 | Loc, EllipsisLoc: SourceLocation(), CaptureType, Invalid); |
18477 | |
18478 | return !Invalid; |
18479 | } |
18480 | |
18481 | /// Capture the given variable in the lambda. |
18482 | static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, |
18483 | SourceLocation Loc, const bool BuildAndDiagnose, |
18484 | QualType &CaptureType, QualType &DeclRefType, |
18485 | const bool RefersToCapturedVariable, |
18486 | const Sema::TryCaptureKind Kind, |
18487 | SourceLocation EllipsisLoc, const bool IsTopScope, |
18488 | Sema &S, bool Invalid) { |
18489 | // Determine whether we are capturing by reference or by value. |
18490 | bool ByRef = false; |
18491 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { |
18492 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); |
18493 | } else { |
18494 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); |
18495 | } |
18496 | |
18497 | if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() && |
18498 | CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) { |
18499 | S.Diag(Loc, DiagID: diag::err_wasm_ca_reference) << 0; |
18500 | Invalid = true; |
18501 | } |
18502 | |
18503 | // Compute the type of the field that will capture this variable. |
18504 | if (ByRef) { |
18505 | // C++11 [expr.prim.lambda]p15: |
18506 | // An entity is captured by reference if it is implicitly or |
18507 | // explicitly captured but not captured by copy. It is |
18508 | // unspecified whether additional unnamed non-static data |
18509 | // members are declared in the closure type for entities |
18510 | // captured by reference. |
18511 | // |
18512 | // FIXME: It is not clear whether we want to build an lvalue reference |
18513 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears |
18514 | // to do the former, while EDG does the latter. Core issue 1249 will |
18515 | // clarify, but for now we follow GCC because it's a more permissive and |
18516 | // easily defensible position. |
18517 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
18518 | } else { |
18519 | // C++11 [expr.prim.lambda]p14: |
18520 | // For each entity captured by copy, an unnamed non-static |
18521 | // data member is declared in the closure type. The |
18522 | // declaration order of these members is unspecified. The type |
18523 | // of such a data member is the type of the corresponding |
18524 | // captured entity if the entity is not a reference to an |
18525 | // object, or the referenced type otherwise. [Note: If the |
18526 | // captured entity is a reference to a function, the |
18527 | // corresponding data member is also a reference to a |
18528 | // function. - end note ] |
18529 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ |
18530 | if (!RefType->getPointeeType()->isFunctionType()) |
18531 | CaptureType = RefType->getPointeeType(); |
18532 | } |
18533 | |
18534 | // Forbid the lambda copy-capture of autoreleasing variables. |
18535 | if (!Invalid && |
18536 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
18537 | if (BuildAndDiagnose) { |
18538 | S.Diag(Loc, DiagID: diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; |
18539 | S.Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) |
18540 | << Var->getDeclName(); |
18541 | Invalid = true; |
18542 | } else { |
18543 | return false; |
18544 | } |
18545 | } |
18546 | |
18547 | // Make sure that by-copy captures are of a complete and non-abstract type. |
18548 | if (!Invalid && BuildAndDiagnose) { |
18549 | if (!CaptureType->isDependentType() && |
18550 | S.RequireCompleteSizedType( |
18551 | Loc, T: CaptureType, |
18552 | DiagID: diag::err_capture_of_incomplete_or_sizeless_type, |
18553 | Args: Var->getDeclName())) |
18554 | Invalid = true; |
18555 | else if (S.RequireNonAbstractType(Loc, T: CaptureType, |
18556 | DiagID: diag::err_capture_of_abstract_type)) |
18557 | Invalid = true; |
18558 | } |
18559 | } |
18560 | |
18561 | // Compute the type of a reference to this captured variable. |
18562 | if (ByRef) |
18563 | DeclRefType = CaptureType.getNonReferenceType(); |
18564 | else { |
18565 | // C++ [expr.prim.lambda]p5: |
18566 | // The closure type for a lambda-expression has a public inline |
18567 | // function call operator [...]. This function call operator is |
18568 | // declared const (9.3.1) if and only if the lambda-expression's |
18569 | // parameter-declaration-clause is not followed by mutable. |
18570 | DeclRefType = CaptureType.getNonReferenceType(); |
18571 | bool Const = LSI->lambdaCaptureShouldBeConst(); |
18572 | if (Const && !CaptureType->isReferenceType()) |
18573 | DeclRefType.addConst(); |
18574 | } |
18575 | |
18576 | // Add the capture. |
18577 | if (BuildAndDiagnose) |
18578 | LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef, isNested: RefersToCapturedVariable, |
18579 | Loc, EllipsisLoc, CaptureType, Invalid); |
18580 | |
18581 | return !Invalid; |
18582 | } |
18583 | |
18584 | static bool canCaptureVariableByCopy(ValueDecl *Var, |
18585 | const ASTContext &Context) { |
18586 | // Offer a Copy fix even if the type is dependent. |
18587 | if (Var->getType()->isDependentType()) |
18588 | return true; |
18589 | QualType T = Var->getType().getNonReferenceType(); |
18590 | if (T.isTriviallyCopyableType(Context)) |
18591 | return true; |
18592 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
18593 | |
18594 | if (!(RD = RD->getDefinition())) |
18595 | return false; |
18596 | if (RD->hasSimpleCopyConstructor()) |
18597 | return true; |
18598 | if (RD->hasUserDeclaredCopyConstructor()) |
18599 | for (CXXConstructorDecl *Ctor : RD->ctors()) |
18600 | if (Ctor->isCopyConstructor()) |
18601 | return !Ctor->isDeleted(); |
18602 | } |
18603 | return false; |
18604 | } |
18605 | |
18606 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or |
18607 | /// default capture. Fixes may be omitted if they aren't allowed by the |
18608 | /// standard, for example we can't emit a default copy capture fix-it if we |
18609 | /// already explicitly copy capture capture another variable. |
18610 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, |
18611 | ValueDecl *Var) { |
18612 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); |
18613 | // Don't offer Capture by copy of default capture by copy fixes if Var is |
18614 | // known not to be copy constructible. |
18615 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext()); |
18616 | |
18617 | SmallString<32> FixBuffer; |
18618 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "" ; |
18619 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { |
18620 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); |
18621 | if (ShouldOfferCopyFix) { |
18622 | // Offer fixes to insert an explicit capture for the variable. |
18623 | // [] -> [VarName] |
18624 | // [OtherCapture] -> [OtherCapture, VarName] |
18625 | FixBuffer.assign(Refs: {Separator, Var->getName()}); |
18626 | Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit) |
18627 | << Var << /*value*/ 0 |
18628 | << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer); |
18629 | } |
18630 | // As above but capture by reference. |
18631 | FixBuffer.assign(Refs: {Separator, "&" , Var->getName()}); |
18632 | Sema.Diag(Loc: VarInsertLoc, DiagID: diag::note_lambda_variable_capture_fixit) |
18633 | << Var << /*reference*/ 1 |
18634 | << FixItHint::CreateInsertion(InsertionLoc: VarInsertLoc, Code: FixBuffer); |
18635 | } |
18636 | |
18637 | // Only try to offer default capture if there are no captures excluding this |
18638 | // and init captures. |
18639 | // [this]: OK. |
18640 | // [X = Y]: OK. |
18641 | // [&A, &B]: Don't offer. |
18642 | // [A, B]: Don't offer. |
18643 | if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) { |
18644 | return !C.isThisCapture() && !C.isInitCapture(); |
18645 | })) |
18646 | return; |
18647 | |
18648 | // The default capture specifiers, '=' or '&', must appear first in the |
18649 | // capture body. |
18650 | SourceLocation DefaultInsertLoc = |
18651 | LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1); |
18652 | |
18653 | if (ShouldOfferCopyFix) { |
18654 | bool CanDefaultCopyCapture = true; |
18655 | // [=, *this] OK since c++17 |
18656 | // [=, this] OK since c++20 |
18657 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) |
18658 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 |
18659 | ? LSI->getCXXThisCapture().isCopyCapture() |
18660 | : false; |
18661 | // We can't use default capture by copy if any captures already specified |
18662 | // capture by copy. |
18663 | if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
18664 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); |
18665 | })) { |
18666 | FixBuffer.assign(Refs: {"=" , Separator}); |
18667 | Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit) |
18668 | << /*value*/ 0 |
18669 | << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer); |
18670 | } |
18671 | } |
18672 | |
18673 | // We can't use default capture by reference if any captures already specified |
18674 | // capture by reference. |
18675 | if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
18676 | return !C.isInitCapture() && C.isReferenceCapture() && |
18677 | !C.isThisCapture(); |
18678 | })) { |
18679 | FixBuffer.assign(Refs: {"&" , Separator}); |
18680 | Sema.Diag(Loc: DefaultInsertLoc, DiagID: diag::note_lambda_default_capture_fixit) |
18681 | << /*reference*/ 1 |
18682 | << FixItHint::CreateInsertion(InsertionLoc: DefaultInsertLoc, Code: FixBuffer); |
18683 | } |
18684 | } |
18685 | |
18686 | bool Sema::tryCaptureVariable( |
18687 | ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, |
18688 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, |
18689 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { |
18690 | // An init-capture is notionally from the context surrounding its |
18691 | // declaration, but its parent DC is the lambda class. |
18692 | DeclContext *VarDC = Var->getDeclContext(); |
18693 | DeclContext *DC = CurContext; |
18694 | |
18695 | // Skip past RequiresExprBodys because they don't constitute function scopes. |
18696 | while (DC->isRequiresExprBody()) |
18697 | DC = DC->getParent(); |
18698 | |
18699 | // tryCaptureVariable is called every time a DeclRef is formed, |
18700 | // it can therefore have non-negigible impact on performances. |
18701 | // For local variables and when there is no capturing scope, |
18702 | // we can bailout early. |
18703 | if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC)) |
18704 | return true; |
18705 | |
18706 | // Exception: Function parameters are not tied to the function's DeclContext |
18707 | // until we enter the function definition. Capturing them anyway would result |
18708 | // in an out-of-bounds error while traversing DC and its parents. |
18709 | if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod()) |
18710 | return true; |
18711 | |
18712 | const auto *VD = dyn_cast<VarDecl>(Val: Var); |
18713 | if (VD) { |
18714 | if (VD->isInitCapture()) |
18715 | VarDC = VarDC->getParent(); |
18716 | } else { |
18717 | VD = Var->getPotentiallyDecomposedVarDecl(); |
18718 | } |
18719 | assert(VD && "Cannot capture a null variable" ); |
18720 | |
18721 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
18722 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; |
18723 | // We need to sync up the Declaration Context with the |
18724 | // FunctionScopeIndexToStopAt |
18725 | if (FunctionScopeIndexToStopAt) { |
18726 | unsigned FSIndex = FunctionScopes.size() - 1; |
18727 | while (FSIndex != MaxFunctionScopesIndex) { |
18728 | DC = getLambdaAwareParentOfDeclContext(DC); |
18729 | --FSIndex; |
18730 | } |
18731 | } |
18732 | |
18733 | // Capture global variables if it is required to use private copy of this |
18734 | // variable. |
18735 | bool IsGlobal = !VD->hasLocalStorage(); |
18736 | if (IsGlobal && !(LangOpts.OpenMP && |
18737 | OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true, |
18738 | StopAt: MaxFunctionScopesIndex))) |
18739 | return true; |
18740 | |
18741 | if (isa<VarDecl>(Val: Var)) |
18742 | Var = cast<VarDecl>(Val: Var->getCanonicalDecl()); |
18743 | |
18744 | // Walk up the stack to determine whether we can capture the variable, |
18745 | // performing the "simple" checks that don't depend on type. We stop when |
18746 | // we've either hit the declared scope of the variable or find an existing |
18747 | // capture of that variable. We start from the innermost capturing-entity |
18748 | // (the DC) and ensure that all intervening capturing-entities |
18749 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s |
18750 | // declcontext can either capture the variable or have already captured |
18751 | // the variable. |
18752 | CaptureType = Var->getType(); |
18753 | DeclRefType = CaptureType.getNonReferenceType(); |
18754 | bool Nested = false; |
18755 | bool Explicit = (Kind != TryCapture_Implicit); |
18756 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; |
18757 | do { |
18758 | |
18759 | LambdaScopeInfo *LSI = nullptr; |
18760 | if (!FunctionScopes.empty()) |
18761 | LSI = dyn_cast_or_null<LambdaScopeInfo>( |
18762 | Val: FunctionScopes[FunctionScopesIndex]); |
18763 | |
18764 | bool IsInScopeDeclarationContext = |
18765 | !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator; |
18766 | |
18767 | if (LSI && !LSI->AfterParameterList) { |
18768 | // This allows capturing parameters from a default value which does not |
18769 | // seems correct |
18770 | if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod()) |
18771 | return true; |
18772 | } |
18773 | // If the variable is declared in the current context, there is no need to |
18774 | // capture it. |
18775 | if (IsInScopeDeclarationContext && |
18776 | FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC) |
18777 | return true; |
18778 | |
18779 | // Only block literals, captured statements, and lambda expressions can |
18780 | // capture; other scopes don't work. |
18781 | DeclContext *ParentDC = |
18782 | !IsInScopeDeclarationContext |
18783 | ? DC->getParent() |
18784 | : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc, |
18785 | Diagnose: BuildAndDiagnose, S&: *this); |
18786 | // We need to check for the parent *first* because, if we *have* |
18787 | // private-captured a global variable, we need to recursively capture it in |
18788 | // intermediate blocks, lambdas, etc. |
18789 | if (!ParentDC) { |
18790 | if (IsGlobal) { |
18791 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; |
18792 | break; |
18793 | } |
18794 | return true; |
18795 | } |
18796 | |
18797 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; |
18798 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI); |
18799 | |
18800 | // Check whether we've already captured it. |
18801 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType, |
18802 | DeclRefType)) { |
18803 | CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose); |
18804 | break; |
18805 | } |
18806 | |
18807 | // When evaluating some attributes (like enable_if) we might refer to a |
18808 | // function parameter appertaining to the same declaration as that |
18809 | // attribute. |
18810 | if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var); |
18811 | Parm && Parm->getDeclContext() == DC) |
18812 | return true; |
18813 | |
18814 | // If we are instantiating a generic lambda call operator body, |
18815 | // we do not want to capture new variables. What was captured |
18816 | // during either a lambdas transformation or initial parsing |
18817 | // should be used. |
18818 | if (isGenericLambdaCallOperatorSpecialization(DC)) { |
18819 | if (BuildAndDiagnose) { |
18820 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
18821 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { |
18822 | Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var; |
18823 | Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18824 | Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl); |
18825 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
18826 | } else |
18827 | diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var); |
18828 | } |
18829 | return true; |
18830 | } |
18831 | |
18832 | // Try to capture variable-length arrays types. |
18833 | if (Var->getType()->isVariablyModifiedType()) { |
18834 | // We're going to walk down into the type and look for VLA |
18835 | // expressions. |
18836 | QualType QTy = Var->getType(); |
18837 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
18838 | QTy = PVD->getOriginalType(); |
18839 | captureVariablyModifiedType(Context, T: QTy, CSI); |
18840 | } |
18841 | |
18842 | if (getLangOpts().OpenMP) { |
18843 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
18844 | // OpenMP private variables should not be captured in outer scope, so |
18845 | // just break here. Similarly, global variables that are captured in a |
18846 | // target region should not be captured outside the scope of the region. |
18847 | if (RSI->CapRegionKind == CR_OpenMP) { |
18848 | // FIXME: We should support capturing structured bindings in OpenMP. |
18849 | if (isa<BindingDecl>(Val: Var)) { |
18850 | if (BuildAndDiagnose) { |
18851 | Diag(Loc: ExprLoc, DiagID: diag::err_capture_binding_openmp) << Var; |
18852 | Diag(Loc: Var->getLocation(), DiagID: diag::note_entity_declared_at) << Var; |
18853 | } |
18854 | return true; |
18855 | } |
18856 | OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl( |
18857 | D: Var, Level: RSI->OpenMPLevel, CapLevel: RSI->OpenMPCaptureLevel); |
18858 | // If the variable is private (i.e. not captured) and has variably |
18859 | // modified type, we still need to capture the type for correct |
18860 | // codegen in all regions, associated with the construct. Currently, |
18861 | // it is captured in the innermost captured region only. |
18862 | if (IsOpenMPPrivateDecl != OMPC_unknown && |
18863 | Var->getType()->isVariablyModifiedType()) { |
18864 | QualType QTy = Var->getType(); |
18865 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
18866 | QTy = PVD->getOriginalType(); |
18867 | for (int I = 1, |
18868 | E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel); |
18869 | I < E; ++I) { |
18870 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( |
18871 | Val: FunctionScopes[FunctionScopesIndex - I]); |
18872 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && |
18873 | "Wrong number of captured regions associated with the " |
18874 | "OpenMP construct." ); |
18875 | captureVariablyModifiedType(Context, T: QTy, CSI: OuterRSI); |
18876 | } |
18877 | } |
18878 | bool IsTargetCap = |
18879 | IsOpenMPPrivateDecl != OMPC_private && |
18880 | OpenMP().isOpenMPTargetCapturedDecl(D: Var, Level: RSI->OpenMPLevel, |
18881 | CaptureLevel: RSI->OpenMPCaptureLevel); |
18882 | // Do not capture global if it is not privatized in outer regions. |
18883 | bool IsGlobalCap = |
18884 | IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl( |
18885 | D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel); |
18886 | |
18887 | // When we detect target captures we are looking from inside the |
18888 | // target region, therefore we need to propagate the capture from the |
18889 | // enclosing region. Therefore, the capture is not initially nested. |
18890 | if (IsTargetCap) |
18891 | OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex, |
18892 | Level: RSI->OpenMPLevel); |
18893 | |
18894 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || |
18895 | (IsGlobal && !IsGlobalCap)) { |
18896 | Nested = !IsTargetCap; |
18897 | bool HasConst = DeclRefType.isConstQualified(); |
18898 | DeclRefType = DeclRefType.getUnqualifiedType(); |
18899 | // Don't lose diagnostics about assignments to const. |
18900 | if (HasConst) |
18901 | DeclRefType.addConst(); |
18902 | CaptureType = Context.getLValueReferenceType(T: DeclRefType); |
18903 | break; |
18904 | } |
18905 | } |
18906 | } |
18907 | } |
18908 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { |
18909 | // No capture-default, and this is not an explicit capture |
18910 | // so cannot capture this variable. |
18911 | if (BuildAndDiagnose) { |
18912 | Diag(Loc: ExprLoc, DiagID: diag::err_lambda_impcap) << Var; |
18913 | Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << Var; |
18914 | auto *LSI = cast<LambdaScopeInfo>(Val: CSI); |
18915 | if (LSI->Lambda) { |
18916 | Diag(Loc: LSI->Lambda->getBeginLoc(), DiagID: diag::note_lambda_decl); |
18917 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
18918 | } |
18919 | // FIXME: If we error out because an outer lambda can not implicitly |
18920 | // capture a variable that an inner lambda explicitly captures, we |
18921 | // should have the inner lambda do the explicit capture - because |
18922 | // it makes for cleaner diagnostics later. This would purely be done |
18923 | // so that the diagnostic does not misleadingly claim that a variable |
18924 | // can not be captured by a lambda implicitly even though it is captured |
18925 | // explicitly. Suggestion: |
18926 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit |
18927 | // at the function head |
18928 | // - cache the StartingDeclContext - this must be a lambda |
18929 | // - captureInLambda in the innermost lambda the variable. |
18930 | } |
18931 | return true; |
18932 | } |
18933 | Explicit = false; |
18934 | FunctionScopesIndex--; |
18935 | if (IsInScopeDeclarationContext) |
18936 | DC = ParentDC; |
18937 | } while (!VarDC->Equals(DC)); |
18938 | |
18939 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) |
18940 | // computing the type of the capture at each step, checking type-specific |
18941 | // requirements, and adding captures if requested. |
18942 | // If the variable had already been captured previously, we start capturing |
18943 | // at the lambda nested within that one. |
18944 | bool Invalid = false; |
18945 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; |
18946 | ++I) { |
18947 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]); |
18948 | |
18949 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
18950 | // certain types of variables (unnamed, variably modified types etc.) |
18951 | // so check for eligibility. |
18952 | if (!Invalid) |
18953 | Invalid = |
18954 | !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this); |
18955 | |
18956 | // After encountering an error, if we're actually supposed to capture, keep |
18957 | // capturing in nested contexts to suppress any follow-on diagnostics. |
18958 | if (Invalid && !BuildAndDiagnose) |
18959 | return true; |
18960 | |
18961 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) { |
18962 | Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
18963 | DeclRefType, Nested, S&: *this, Invalid); |
18964 | Nested = true; |
18965 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
18966 | Invalid = !captureInCapturedRegion( |
18967 | RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested, |
18968 | Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
18969 | Nested = true; |
18970 | } else { |
18971 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
18972 | Invalid = |
18973 | !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
18974 | DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc, |
18975 | /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
18976 | Nested = true; |
18977 | } |
18978 | |
18979 | if (Invalid && !BuildAndDiagnose) |
18980 | return true; |
18981 | } |
18982 | return Invalid; |
18983 | } |
18984 | |
18985 | bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, |
18986 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { |
18987 | QualType CaptureType; |
18988 | QualType DeclRefType; |
18989 | return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc, |
18990 | /*BuildAndDiagnose=*/true, CaptureType, |
18991 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
18992 | } |
18993 | |
18994 | bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { |
18995 | QualType CaptureType; |
18996 | QualType DeclRefType; |
18997 | return !tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(), |
18998 | /*BuildAndDiagnose=*/false, CaptureType, |
18999 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
19000 | } |
19001 | |
19002 | QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { |
19003 | QualType CaptureType; |
19004 | QualType DeclRefType; |
19005 | |
19006 | // Determine whether we can capture this variable. |
19007 | if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(), |
19008 | /*BuildAndDiagnose=*/false, CaptureType, |
19009 | DeclRefType, FunctionScopeIndexToStopAt: nullptr)) |
19010 | return QualType(); |
19011 | |
19012 | return DeclRefType; |
19013 | } |
19014 | |
19015 | namespace { |
19016 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. |
19017 | // The produced TemplateArgumentListInfo* points to data stored within this |
19018 | // object, so should only be used in contexts where the pointer will not be |
19019 | // used after the CopiedTemplateArgs object is destroyed. |
19020 | class CopiedTemplateArgs { |
19021 | bool HasArgs; |
19022 | TemplateArgumentListInfo TemplateArgStorage; |
19023 | public: |
19024 | template<typename RefExpr> |
19025 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { |
19026 | if (HasArgs) |
19027 | E->copyTemplateArgumentsInto(TemplateArgStorage); |
19028 | } |
19029 | operator TemplateArgumentListInfo*() |
19030 | #ifdef __has_cpp_attribute |
19031 | #if __has_cpp_attribute(clang::lifetimebound) |
19032 | [[clang::lifetimebound]] |
19033 | #endif |
19034 | #endif |
19035 | { |
19036 | return HasArgs ? &TemplateArgStorage : nullptr; |
19037 | } |
19038 | }; |
19039 | } |
19040 | |
19041 | /// Walk the set of potential results of an expression and mark them all as |
19042 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. |
19043 | /// |
19044 | /// \return A new expression if we found any potential results, ExprEmpty() if |
19045 | /// not, and ExprError() if we diagnosed an error. |
19046 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, |
19047 | NonOdrUseReason NOUR) { |
19048 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is |
19049 | // an object that satisfies the requirements for appearing in a |
19050 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) |
19051 | // is immediately applied." This function handles the lvalue-to-rvalue |
19052 | // conversion part. |
19053 | // |
19054 | // If we encounter a node that claims to be an odr-use but shouldn't be, we |
19055 | // transform it into the relevant kind of non-odr-use node and rebuild the |
19056 | // tree of nodes leading to it. |
19057 | // |
19058 | // This is a mini-TreeTransform that only transforms a restricted subset of |
19059 | // nodes (and only certain operands of them). |
19060 | |
19061 | // Rebuild a subexpression. |
19062 | auto Rebuild = [&](Expr *Sub) { |
19063 | return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR); |
19064 | }; |
19065 | |
19066 | // Check whether a potential result satisfies the requirements of NOUR. |
19067 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { |
19068 | // Any entity other than a VarDecl is always odr-used whenever it's named |
19069 | // in a potentially-evaluated expression. |
19070 | auto *VD = dyn_cast<VarDecl>(Val: D); |
19071 | if (!VD) |
19072 | return true; |
19073 | |
19074 | // C++2a [basic.def.odr]p4: |
19075 | // A variable x whose name appears as a potentially-evalauted expression |
19076 | // e is odr-used by e unless |
19077 | // -- x is a reference that is usable in constant expressions, or |
19078 | // -- x is a variable of non-reference type that is usable in constant |
19079 | // expressions and has no mutable subobjects, and e is an element of |
19080 | // the set of potential results of an expression of |
19081 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
19082 | // conversion is applied, or |
19083 | // -- x is a variable of non-reference type, and e is an element of the |
19084 | // set of potential results of a discarded-value expression to which |
19085 | // the lvalue-to-rvalue conversion is not applied |
19086 | // |
19087 | // We check the first bullet and the "potentially-evaluated" condition in |
19088 | // BuildDeclRefExpr. We check the type requirements in the second bullet |
19089 | // in CheckLValueToRValueConversionOperand below. |
19090 | switch (NOUR) { |
19091 | case NOUR_None: |
19092 | case NOUR_Unevaluated: |
19093 | llvm_unreachable("unexpected non-odr-use-reason" ); |
19094 | |
19095 | case NOUR_Constant: |
19096 | // Constant references were handled when they were built. |
19097 | if (VD->getType()->isReferenceType()) |
19098 | return true; |
19099 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) |
19100 | if (RD->hasMutableFields()) |
19101 | return true; |
19102 | if (!VD->isUsableInConstantExpressions(C: S.Context)) |
19103 | return true; |
19104 | break; |
19105 | |
19106 | case NOUR_Discarded: |
19107 | if (VD->getType()->isReferenceType()) |
19108 | return true; |
19109 | break; |
19110 | } |
19111 | return false; |
19112 | }; |
19113 | |
19114 | // Mark that this expression does not constitute an odr-use. |
19115 | auto MarkNotOdrUsed = [&] { |
19116 | S.MaybeODRUseExprs.remove(X: E); |
19117 | if (LambdaScopeInfo *LSI = S.getCurLambda()) |
19118 | LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E); |
19119 | }; |
19120 | |
19121 | // C++2a [basic.def.odr]p2: |
19122 | // The set of potential results of an expression e is defined as follows: |
19123 | switch (E->getStmtClass()) { |
19124 | // -- If e is an id-expression, ... |
19125 | case Expr::DeclRefExprClass: { |
19126 | auto *DRE = cast<DeclRefExpr>(Val: E); |
19127 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) |
19128 | break; |
19129 | |
19130 | // Rebuild as a non-odr-use DeclRefExpr. |
19131 | MarkNotOdrUsed(); |
19132 | return DeclRefExpr::Create( |
19133 | Context: S.Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: DRE->getTemplateKeywordLoc(), |
19134 | D: DRE->getDecl(), RefersToEnclosingVariableOrCapture: DRE->refersToEnclosingVariableOrCapture(), |
19135 | NameInfo: DRE->getNameInfo(), T: DRE->getType(), VK: DRE->getValueKind(), |
19136 | FoundD: DRE->getFoundDecl(), TemplateArgs: CopiedTemplateArgs(DRE), NOUR); |
19137 | } |
19138 | |
19139 | case Expr::FunctionParmPackExprClass: { |
19140 | auto *FPPE = cast<FunctionParmPackExpr>(Val: E); |
19141 | // If any of the declarations in the pack is odr-used, then the expression |
19142 | // as a whole constitutes an odr-use. |
19143 | for (VarDecl *D : *FPPE) |
19144 | if (IsPotentialResultOdrUsed(D)) |
19145 | return ExprEmpty(); |
19146 | |
19147 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, |
19148 | // nothing cares about whether we marked this as an odr-use, but it might |
19149 | // be useful for non-compiler tools. |
19150 | MarkNotOdrUsed(); |
19151 | break; |
19152 | } |
19153 | |
19154 | // -- If e is a subscripting operation with an array operand... |
19155 | case Expr::ArraySubscriptExprClass: { |
19156 | auto *ASE = cast<ArraySubscriptExpr>(Val: E); |
19157 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); |
19158 | if (!OldBase->getType()->isArrayType()) |
19159 | break; |
19160 | ExprResult Base = Rebuild(OldBase); |
19161 | if (!Base.isUsable()) |
19162 | return Base; |
19163 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); |
19164 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); |
19165 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. |
19166 | return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS, |
19167 | rbLoc: ASE->getRBracketLoc()); |
19168 | } |
19169 | |
19170 | case Expr::MemberExprClass: { |
19171 | auto *ME = cast<MemberExpr>(Val: E); |
19172 | // -- If e is a class member access expression [...] naming a non-static |
19173 | // data member... |
19174 | if (isa<FieldDecl>(Val: ME->getMemberDecl())) { |
19175 | ExprResult Base = Rebuild(ME->getBase()); |
19176 | if (!Base.isUsable()) |
19177 | return Base; |
19178 | return MemberExpr::Create( |
19179 | C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
19180 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), |
19181 | MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), |
19182 | TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(), |
19183 | OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse()); |
19184 | } |
19185 | |
19186 | if (ME->getMemberDecl()->isCXXInstanceMember()) |
19187 | break; |
19188 | |
19189 | // -- If e is a class member access expression naming a static data member, |
19190 | // ... |
19191 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) |
19192 | break; |
19193 | |
19194 | // Rebuild as a non-odr-use MemberExpr. |
19195 | MarkNotOdrUsed(); |
19196 | return MemberExpr::Create( |
19197 | C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
19198 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(), |
19199 | FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME), |
19200 | T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR); |
19201 | } |
19202 | |
19203 | case Expr::BinaryOperatorClass: { |
19204 | auto *BO = cast<BinaryOperator>(Val: E); |
19205 | Expr *LHS = BO->getLHS(); |
19206 | Expr *RHS = BO->getRHS(); |
19207 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... |
19208 | if (BO->getOpcode() == BO_PtrMemD) { |
19209 | ExprResult Sub = Rebuild(LHS); |
19210 | if (!Sub.isUsable()) |
19211 | return Sub; |
19212 | BO->setLHS(Sub.get()); |
19213 | // -- If e is a comma expression, ... |
19214 | } else if (BO->getOpcode() == BO_Comma) { |
19215 | ExprResult Sub = Rebuild(RHS); |
19216 | if (!Sub.isUsable()) |
19217 | return Sub; |
19218 | BO->setRHS(Sub.get()); |
19219 | } else { |
19220 | break; |
19221 | } |
19222 | return ExprResult(BO); |
19223 | } |
19224 | |
19225 | // -- If e has the form (e1)... |
19226 | case Expr::ParenExprClass: { |
19227 | auto *PE = cast<ParenExpr>(Val: E); |
19228 | ExprResult Sub = Rebuild(PE->getSubExpr()); |
19229 | if (!Sub.isUsable()) |
19230 | return Sub; |
19231 | return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get()); |
19232 | } |
19233 | |
19234 | // -- If e is a glvalue conditional expression, ... |
19235 | // We don't apply this to a binary conditional operator. FIXME: Should we? |
19236 | case Expr::ConditionalOperatorClass: { |
19237 | auto *CO = cast<ConditionalOperator>(Val: E); |
19238 | ExprResult LHS = Rebuild(CO->getLHS()); |
19239 | if (LHS.isInvalid()) |
19240 | return ExprError(); |
19241 | ExprResult RHS = Rebuild(CO->getRHS()); |
19242 | if (RHS.isInvalid()) |
19243 | return ExprError(); |
19244 | if (!LHS.isUsable() && !RHS.isUsable()) |
19245 | return ExprEmpty(); |
19246 | if (!LHS.isUsable()) |
19247 | LHS = CO->getLHS(); |
19248 | if (!RHS.isUsable()) |
19249 | RHS = CO->getRHS(); |
19250 | return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(), |
19251 | CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
19252 | } |
19253 | |
19254 | // [Clang extension] |
19255 | // -- If e has the form __extension__ e1... |
19256 | case Expr::UnaryOperatorClass: { |
19257 | auto *UO = cast<UnaryOperator>(Val: E); |
19258 | if (UO->getOpcode() != UO_Extension) |
19259 | break; |
19260 | ExprResult Sub = Rebuild(UO->getSubExpr()); |
19261 | if (!Sub.isUsable()) |
19262 | return Sub; |
19263 | return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension, |
19264 | Input: Sub.get()); |
19265 | } |
19266 | |
19267 | // [Clang extension] |
19268 | // -- If e has the form _Generic(...), the set of potential results is the |
19269 | // union of the sets of potential results of the associated expressions. |
19270 | case Expr::GenericSelectionExprClass: { |
19271 | auto *GSE = cast<GenericSelectionExpr>(Val: E); |
19272 | |
19273 | SmallVector<Expr *, 4> AssocExprs; |
19274 | bool AnyChanged = false; |
19275 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { |
19276 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); |
19277 | if (AssocExpr.isInvalid()) |
19278 | return ExprError(); |
19279 | if (AssocExpr.isUsable()) { |
19280 | AssocExprs.push_back(Elt: AssocExpr.get()); |
19281 | AnyChanged = true; |
19282 | } else { |
19283 | AssocExprs.push_back(Elt: OrigAssocExpr); |
19284 | } |
19285 | } |
19286 | |
19287 | void *ExOrTy = nullptr; |
19288 | bool IsExpr = GSE->isExprPredicate(); |
19289 | if (IsExpr) |
19290 | ExOrTy = GSE->getControllingExpr(); |
19291 | else |
19292 | ExOrTy = GSE->getControllingType(); |
19293 | return AnyChanged ? S.CreateGenericSelectionExpr( |
19294 | KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(), |
19295 | RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy, |
19296 | Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs) |
19297 | : ExprEmpty(); |
19298 | } |
19299 | |
19300 | // [Clang extension] |
19301 | // -- If e has the form __builtin_choose_expr(...), the set of potential |
19302 | // results is the union of the sets of potential results of the |
19303 | // second and third subexpressions. |
19304 | case Expr::ChooseExprClass: { |
19305 | auto *CE = cast<ChooseExpr>(Val: E); |
19306 | |
19307 | ExprResult LHS = Rebuild(CE->getLHS()); |
19308 | if (LHS.isInvalid()) |
19309 | return ExprError(); |
19310 | |
19311 | ExprResult RHS = Rebuild(CE->getLHS()); |
19312 | if (RHS.isInvalid()) |
19313 | return ExprError(); |
19314 | |
19315 | if (!LHS.get() && !RHS.get()) |
19316 | return ExprEmpty(); |
19317 | if (!LHS.isUsable()) |
19318 | LHS = CE->getLHS(); |
19319 | if (!RHS.isUsable()) |
19320 | RHS = CE->getRHS(); |
19321 | |
19322 | return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(), |
19323 | RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc()); |
19324 | } |
19325 | |
19326 | // Step through non-syntactic nodes. |
19327 | case Expr::ConstantExprClass: { |
19328 | auto *CE = cast<ConstantExpr>(Val: E); |
19329 | ExprResult Sub = Rebuild(CE->getSubExpr()); |
19330 | if (!Sub.isUsable()) |
19331 | return Sub; |
19332 | return ConstantExpr::Create(Context: S.Context, E: Sub.get()); |
19333 | } |
19334 | |
19335 | // We could mostly rely on the recursive rebuilding to rebuild implicit |
19336 | // casts, but not at the top level, so rebuild them here. |
19337 | case Expr::ImplicitCastExprClass: { |
19338 | auto *ICE = cast<ImplicitCastExpr>(Val: E); |
19339 | // Only step through the narrow set of cast kinds we expect to encounter. |
19340 | // Anything else suggests we've left the region in which potential results |
19341 | // can be found. |
19342 | switch (ICE->getCastKind()) { |
19343 | case CK_NoOp: |
19344 | case CK_DerivedToBase: |
19345 | case CK_UncheckedDerivedToBase: { |
19346 | ExprResult Sub = Rebuild(ICE->getSubExpr()); |
19347 | if (!Sub.isUsable()) |
19348 | return Sub; |
19349 | CXXCastPath Path(ICE->path()); |
19350 | return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(), |
19351 | VK: ICE->getValueKind(), BasePath: &Path); |
19352 | } |
19353 | |
19354 | default: |
19355 | break; |
19356 | } |
19357 | break; |
19358 | } |
19359 | |
19360 | default: |
19361 | break; |
19362 | } |
19363 | |
19364 | // Can't traverse through this node. Nothing to do. |
19365 | return ExprEmpty(); |
19366 | } |
19367 | |
19368 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { |
19369 | // Check whether the operand is or contains an object of non-trivial C union |
19370 | // type. |
19371 | if (E->getType().isVolatileQualified() && |
19372 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || |
19373 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) |
19374 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
19375 | UseContext: Sema::NTCUC_LValueToRValueVolatile, |
19376 | NonTrivialKind: NTCUK_Destruct|NTCUK_Copy); |
19377 | |
19378 | // C++2a [basic.def.odr]p4: |
19379 | // [...] an expression of non-volatile-qualified non-class type to which |
19380 | // the lvalue-to-rvalue conversion is applied [...] |
19381 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) |
19382 | return E; |
19383 | |
19384 | ExprResult Result = |
19385 | rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant); |
19386 | if (Result.isInvalid()) |
19387 | return ExprError(); |
19388 | return Result.get() ? Result : E; |
19389 | } |
19390 | |
19391 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { |
19392 | Res = CorrectDelayedTyposInExpr(ER: Res); |
19393 | |
19394 | if (!Res.isUsable()) |
19395 | return Res; |
19396 | |
19397 | // If a constant-expression is a reference to a variable where we delay |
19398 | // deciding whether it is an odr-use, just assume we will apply the |
19399 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen |
19400 | // (a non-type template argument), we have special handling anyway. |
19401 | return CheckLValueToRValueConversionOperand(E: Res.get()); |
19402 | } |
19403 | |
19404 | void Sema::CleanupVarDeclMarking() { |
19405 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive |
19406 | // call. |
19407 | MaybeODRUseExprSet LocalMaybeODRUseExprs; |
19408 | std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs); |
19409 | |
19410 | for (Expr *E : LocalMaybeODRUseExprs) { |
19411 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
19412 | MarkVarDeclODRUsed(V: cast<VarDecl>(Val: DRE->getDecl()), |
19413 | Loc: DRE->getLocation(), SemaRef&: *this); |
19414 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
19415 | MarkVarDeclODRUsed(V: cast<VarDecl>(Val: ME->getMemberDecl()), Loc: ME->getMemberLoc(), |
19416 | SemaRef&: *this); |
19417 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) { |
19418 | for (VarDecl *VD : *FP) |
19419 | MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this); |
19420 | } else { |
19421 | llvm_unreachable("Unexpected expression" ); |
19422 | } |
19423 | } |
19424 | |
19425 | assert(MaybeODRUseExprs.empty() && |
19426 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ); |
19427 | } |
19428 | |
19429 | static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, |
19430 | ValueDecl *Var, Expr *E) { |
19431 | VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); |
19432 | if (!VD) |
19433 | return; |
19434 | |
19435 | const bool RefersToEnclosingScope = |
19436 | (SemaRef.CurContext != VD->getDeclContext() && |
19437 | VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); |
19438 | if (RefersToEnclosingScope) { |
19439 | LambdaScopeInfo *const LSI = |
19440 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); |
19441 | if (LSI && (!LSI->CallOperator || |
19442 | !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) { |
19443 | // If a variable could potentially be odr-used, defer marking it so |
19444 | // until we finish analyzing the full expression for any |
19445 | // lvalue-to-rvalue |
19446 | // or discarded value conversions that would obviate odr-use. |
19447 | // Add it to the list of potential captures that will be analyzed |
19448 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking |
19449 | // unless the variable is a reference that was initialized by a constant |
19450 | // expression (this will never need to be captured or odr-used). |
19451 | // |
19452 | // FIXME: We can simplify this a lot after implementing P0588R1. |
19453 | assert(E && "Capture variable should be used in an expression." ); |
19454 | if (!Var->getType()->isReferenceType() || |
19455 | !VD->isUsableInConstantExpressions(C: SemaRef.Context)) |
19456 | LSI->addPotentialCapture(VarExpr: E->IgnoreParens()); |
19457 | } |
19458 | } |
19459 | } |
19460 | |
19461 | static void DoMarkVarDeclReferenced( |
19462 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, |
19463 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
19464 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || |
19465 | isa<FunctionParmPackExpr>(E)) && |
19466 | "Invalid Expr argument to DoMarkVarDeclReferenced" ); |
19467 | Var->setReferenced(); |
19468 | |
19469 | if (Var->isInvalidDecl()) |
19470 | return; |
19471 | |
19472 | auto *MSI = Var->getMemberSpecializationInfo(); |
19473 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() |
19474 | : Var->getTemplateSpecializationKind(); |
19475 | |
19476 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
19477 | bool UsableInConstantExpr = |
19478 | Var->mightBeUsableInConstantExpressions(C: SemaRef.Context); |
19479 | |
19480 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { |
19481 | RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++; |
19482 | } |
19483 | |
19484 | // C++20 [expr.const]p12: |
19485 | // A variable [...] is needed for constant evaluation if it is [...] a |
19486 | // variable whose name appears as a potentially constant evaluated |
19487 | // expression that is either a contexpr variable or is of non-volatile |
19488 | // const-qualified integral type or of reference type |
19489 | bool NeededForConstantEvaluation = |
19490 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; |
19491 | |
19492 | bool NeedDefinition = |
19493 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; |
19494 | |
19495 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && |
19496 | "Can't instantiate a partial template specialization." ); |
19497 | |
19498 | // If this might be a member specialization of a static data member, check |
19499 | // the specialization is visible. We already did the checks for variable |
19500 | // template specializations when we created them. |
19501 | if (NeedDefinition && TSK != TSK_Undeclared && |
19502 | !isa<VarTemplateSpecializationDecl>(Val: Var)) |
19503 | SemaRef.checkSpecializationVisibility(Loc, Spec: Var); |
19504 | |
19505 | // Perform implicit instantiation of static data members, static data member |
19506 | // templates of class templates, and variable template specializations. Delay |
19507 | // instantiations of variable templates, except for those that could be used |
19508 | // in a constant expression. |
19509 | if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) { |
19510 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit |
19511 | // instantiation declaration if a variable is usable in a constant |
19512 | // expression (among other cases). |
19513 | bool TryInstantiating = |
19514 | TSK == TSK_ImplicitInstantiation || |
19515 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); |
19516 | |
19517 | if (TryInstantiating) { |
19518 | SourceLocation PointOfInstantiation = |
19519 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); |
19520 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
19521 | if (FirstInstantiation) { |
19522 | PointOfInstantiation = Loc; |
19523 | if (MSI) |
19524 | MSI->setPointOfInstantiation(PointOfInstantiation); |
19525 | // FIXME: Notify listener. |
19526 | else |
19527 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
19528 | } |
19529 | |
19530 | if (UsableInConstantExpr) { |
19531 | // Do not defer instantiations of variables that could be used in a |
19532 | // constant expression. |
19533 | SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] { |
19534 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); |
19535 | }); |
19536 | |
19537 | // Re-set the member to trigger a recomputation of the dependence bits |
19538 | // for the expression. |
19539 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
19540 | DRE->setDecl(DRE->getDecl()); |
19541 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
19542 | ME->setMemberDecl(ME->getMemberDecl()); |
19543 | } else if (FirstInstantiation) { |
19544 | SemaRef.PendingInstantiations |
19545 | .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation)); |
19546 | } else { |
19547 | bool Inserted = false; |
19548 | for (auto &I : SemaRef.SavedPendingInstantiations) { |
19549 | auto Iter = llvm::find_if( |
19550 | Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) { |
19551 | return P.first == Var; |
19552 | }); |
19553 | if (Iter != I.end()) { |
19554 | SemaRef.PendingInstantiations.push_back(x: *Iter); |
19555 | I.erase(position: Iter); |
19556 | Inserted = true; |
19557 | break; |
19558 | } |
19559 | } |
19560 | |
19561 | // FIXME: For a specialization of a variable template, we don't |
19562 | // distinguish between "declaration and type implicitly instantiated" |
19563 | // and "implicit instantiation of definition requested", so we have |
19564 | // no direct way to avoid enqueueing the pending instantiation |
19565 | // multiple times. |
19566 | if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted) |
19567 | SemaRef.PendingInstantiations |
19568 | .push_back(x: std::make_pair(x&: Var, y&: PointOfInstantiation)); |
19569 | } |
19570 | } |
19571 | } |
19572 | |
19573 | // C++2a [basic.def.odr]p4: |
19574 | // A variable x whose name appears as a potentially-evaluated expression e |
19575 | // is odr-used by e unless |
19576 | // -- x is a reference that is usable in constant expressions |
19577 | // -- x is a variable of non-reference type that is usable in constant |
19578 | // expressions and has no mutable subobjects [FIXME], and e is an |
19579 | // element of the set of potential results of an expression of |
19580 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
19581 | // conversion is applied |
19582 | // -- x is a variable of non-reference type, and e is an element of the set |
19583 | // of potential results of a discarded-value expression to which the |
19584 | // lvalue-to-rvalue conversion is not applied [FIXME] |
19585 | // |
19586 | // We check the first part of the second bullet here, and |
19587 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. |
19588 | // FIXME: To get the third bullet right, we need to delay this even for |
19589 | // variables that are not usable in constant expressions. |
19590 | |
19591 | // If we already know this isn't an odr-use, there's nothing more to do. |
19592 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
19593 | if (DRE->isNonOdrUse()) |
19594 | return; |
19595 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
19596 | if (ME->isNonOdrUse()) |
19597 | return; |
19598 | |
19599 | switch (OdrUse) { |
19600 | case OdrUseContext::None: |
19601 | // In some cases, a variable may not have been marked unevaluated, if it |
19602 | // appears in a defaukt initializer. |
19603 | assert((!E || isa<FunctionParmPackExpr>(E) || |
19604 | SemaRef.isUnevaluatedContext()) && |
19605 | "missing non-odr-use marking for unevaluated decl ref" ); |
19606 | break; |
19607 | |
19608 | case OdrUseContext::FormallyOdrUsed: |
19609 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture |
19610 | // behavior. |
19611 | break; |
19612 | |
19613 | case OdrUseContext::Used: |
19614 | // If we might later find that this expression isn't actually an odr-use, |
19615 | // delay the marking. |
19616 | if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context)) |
19617 | SemaRef.MaybeODRUseExprs.insert(X: E); |
19618 | else |
19619 | MarkVarDeclODRUsed(V: Var, Loc, SemaRef); |
19620 | break; |
19621 | |
19622 | case OdrUseContext::Dependent: |
19623 | // If this is a dependent context, we don't need to mark variables as |
19624 | // odr-used, but we may still need to track them for lambda capture. |
19625 | // FIXME: Do we also need to do this inside dependent typeid expressions |
19626 | // (which are modeled as unevaluated at this point)? |
19627 | DoMarkPotentialCapture(SemaRef, Loc, Var, E); |
19628 | break; |
19629 | } |
19630 | } |
19631 | |
19632 | static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, |
19633 | BindingDecl *BD, Expr *E) { |
19634 | BD->setReferenced(); |
19635 | |
19636 | if (BD->isInvalidDecl()) |
19637 | return; |
19638 | |
19639 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
19640 | if (OdrUse == OdrUseContext::Used) { |
19641 | QualType CaptureType, DeclRefType; |
19642 | SemaRef.tryCaptureVariable(Var: BD, ExprLoc: Loc, Kind: Sema::TryCapture_Implicit, |
19643 | /*EllipsisLoc*/ SourceLocation(), |
19644 | /*BuildAndDiagnose*/ true, CaptureType, |
19645 | DeclRefType, |
19646 | /*FunctionScopeIndexToStopAt*/ nullptr); |
19647 | } else if (OdrUse == OdrUseContext::Dependent) { |
19648 | DoMarkPotentialCapture(SemaRef, Loc, Var: BD, E); |
19649 | } |
19650 | } |
19651 | |
19652 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { |
19653 | DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments); |
19654 | } |
19655 | |
19656 | // C++ [temp.dep.expr]p3: |
19657 | // An id-expression is type-dependent if it contains: |
19658 | // - an identifier associated by name lookup with an entity captured by copy |
19659 | // in a lambda-expression that has an explicit object parameter whose type |
19660 | // is dependent ([dcl.fct]), |
19661 | static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter( |
19662 | Sema &SemaRef, ValueDecl *D, Expr *E) { |
19663 | auto *ID = dyn_cast<DeclRefExpr>(Val: E); |
19664 | if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture()) |
19665 | return; |
19666 | |
19667 | // If any enclosing lambda with a dependent explicit object parameter either |
19668 | // explicitly captures the variable by value, or has a capture default of '=' |
19669 | // and does not capture the variable by reference, then the type of the DRE |
19670 | // is dependent on the type of that lambda's explicit object parameter. |
19671 | auto IsDependent = [&]() { |
19672 | for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) { |
19673 | auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope); |
19674 | if (!LSI) |
19675 | continue; |
19676 | |
19677 | if (LSI->Lambda && !LSI->Lambda->Encloses(DC: SemaRef.CurContext) && |
19678 | LSI->AfterParameterList) |
19679 | return false; |
19680 | |
19681 | const auto *MD = LSI->CallOperator; |
19682 | if (MD->getType().isNull()) |
19683 | continue; |
19684 | |
19685 | const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
19686 | if (!Ty || !MD->isExplicitObjectMemberFunction() || |
19687 | !Ty->getParamType(i: 0)->isDependentType()) |
19688 | continue; |
19689 | |
19690 | if (auto *C = LSI->CaptureMap.count(Val: D) ? &LSI->getCapture(Var: D) : nullptr) { |
19691 | if (C->isCopyCapture()) |
19692 | return true; |
19693 | continue; |
19694 | } |
19695 | |
19696 | if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval) |
19697 | return true; |
19698 | } |
19699 | return false; |
19700 | }(); |
19701 | |
19702 | ID->setCapturedByCopyInLambdaWithExplicitObjectParameter( |
19703 | Set: IsDependent, Context: SemaRef.getASTContext()); |
19704 | } |
19705 | |
19706 | static void |
19707 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, |
19708 | bool MightBeOdrUse, |
19709 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
19710 | if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext()) |
19711 | SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D); |
19712 | |
19713 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) { |
19714 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); |
19715 | if (SemaRef.getLangOpts().CPlusPlus) |
19716 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
19717 | D: Var, E); |
19718 | return; |
19719 | } |
19720 | |
19721 | if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) { |
19722 | DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E); |
19723 | if (SemaRef.getLangOpts().CPlusPlus) |
19724 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
19725 | D: Decl, E); |
19726 | return; |
19727 | } |
19728 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); |
19729 | |
19730 | // If this is a call to a method via a cast, also mark the method in the |
19731 | // derived class used in case codegen can devirtualize the call. |
19732 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
19733 | if (!ME) |
19734 | return; |
19735 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl()); |
19736 | if (!MD) |
19737 | return; |
19738 | // Only attempt to devirtualize if this is truly a virtual call. |
19739 | bool IsVirtualCall = MD->isVirtual() && |
19740 | ME->performsVirtualDispatch(LO: SemaRef.getLangOpts()); |
19741 | if (!IsVirtualCall) |
19742 | return; |
19743 | |
19744 | // If it's possible to devirtualize the call, mark the called function |
19745 | // referenced. |
19746 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( |
19747 | Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext); |
19748 | if (DM) |
19749 | SemaRef.MarkAnyDeclReferenced(Loc, D: DM, MightBeOdrUse); |
19750 | } |
19751 | |
19752 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { |
19753 | // TODO: update this with DR# once a defect report is filed. |
19754 | // C++11 defect. The address of a pure member should not be an ODR use, even |
19755 | // if it's a qualified reference. |
19756 | bool OdrUse = true; |
19757 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl())) |
19758 | if (Method->isVirtual() && |
19759 | !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext)) |
19760 | OdrUse = false; |
19761 | |
19762 | if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) { |
19763 | if (!isUnevaluatedContext() && !isConstantEvaluatedContext() && |
19764 | !isImmediateFunctionContext() && |
19765 | !isCheckingDefaultArgumentOrInitializer() && |
19766 | FD->isImmediateFunction() && !RebuildingImmediateInvocation && |
19767 | !FD->isDependentContext()) |
19768 | ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E); |
19769 | } |
19770 | MarkExprReferenced(SemaRef&: *this, Loc: E->getLocation(), D: E->getDecl(), E, MightBeOdrUse: OdrUse, |
19771 | RefsMinusAssignments); |
19772 | } |
19773 | |
19774 | void Sema::MarkMemberReferenced(MemberExpr *E) { |
19775 | // C++11 [basic.def.odr]p2: |
19776 | // A non-overloaded function whose name appears as a potentially-evaluated |
19777 | // expression or a member of a set of candidate functions, if selected by |
19778 | // overload resolution when referred to from a potentially-evaluated |
19779 | // expression, is odr-used, unless it is a pure virtual function and its |
19780 | // name is not explicitly qualified. |
19781 | bool MightBeOdrUse = true; |
19782 | if (E->performsVirtualDispatch(LO: getLangOpts())) { |
19783 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl())) |
19784 | if (Method->isPureVirtual()) |
19785 | MightBeOdrUse = false; |
19786 | } |
19787 | SourceLocation Loc = |
19788 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); |
19789 | MarkExprReferenced(SemaRef&: *this, Loc, D: E->getMemberDecl(), E, MightBeOdrUse, |
19790 | RefsMinusAssignments); |
19791 | } |
19792 | |
19793 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { |
19794 | for (VarDecl *VD : *E) |
19795 | MarkExprReferenced(SemaRef&: *this, Loc: E->getParameterPackLocation(), D: VD, E, MightBeOdrUse: true, |
19796 | RefsMinusAssignments); |
19797 | } |
19798 | |
19799 | /// Perform marking for a reference to an arbitrary declaration. It |
19800 | /// marks the declaration referenced, and performs odr-use checking for |
19801 | /// functions and variables. This method should not be used when building a |
19802 | /// normal expression which refers to a variable. |
19803 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, |
19804 | bool MightBeOdrUse) { |
19805 | if (MightBeOdrUse) { |
19806 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) { |
19807 | MarkVariableReferenced(Loc, Var: VD); |
19808 | return; |
19809 | } |
19810 | } |
19811 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
19812 | MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse); |
19813 | return; |
19814 | } |
19815 | D->setReferenced(); |
19816 | } |
19817 | |
19818 | namespace { |
19819 | // Mark all of the declarations used by a type as referenced. |
19820 | // FIXME: Not fully implemented yet! We need to have a better understanding |
19821 | // of when we're entering a context we should not recurse into. |
19822 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to |
19823 | // TreeTransforms rebuilding the type in a new context. Rather than |
19824 | // duplicating the TreeTransform logic, we should consider reusing it here. |
19825 | // Currently that causes problems when rebuilding LambdaExprs. |
19826 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { |
19827 | Sema &S; |
19828 | SourceLocation Loc; |
19829 | |
19830 | public: |
19831 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; |
19832 | |
19833 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } |
19834 | |
19835 | bool TraverseTemplateArgument(const TemplateArgument &Arg); |
19836 | }; |
19837 | } |
19838 | |
19839 | bool MarkReferencedDecls::TraverseTemplateArgument( |
19840 | const TemplateArgument &Arg) { |
19841 | { |
19842 | // A non-type template argument is a constant-evaluated context. |
19843 | EnterExpressionEvaluationContext Evaluated( |
19844 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
19845 | if (Arg.getKind() == TemplateArgument::Declaration) { |
19846 | if (Decl *D = Arg.getAsDecl()) |
19847 | S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true); |
19848 | } else if (Arg.getKind() == TemplateArgument::Expression) { |
19849 | S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false); |
19850 | } |
19851 | } |
19852 | |
19853 | return Inherited::TraverseTemplateArgument(Arg); |
19854 | } |
19855 | |
19856 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { |
19857 | MarkReferencedDecls Marker(*this, Loc); |
19858 | Marker.TraverseType(T); |
19859 | } |
19860 | |
19861 | namespace { |
19862 | /// Helper class that marks all of the declarations referenced by |
19863 | /// potentially-evaluated subexpressions as "referenced". |
19864 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { |
19865 | public: |
19866 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; |
19867 | bool SkipLocalVariables; |
19868 | ArrayRef<const Expr *> StopAt; |
19869 | |
19870 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, |
19871 | ArrayRef<const Expr *> StopAt) |
19872 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} |
19873 | |
19874 | void visitUsedDecl(SourceLocation Loc, Decl *D) { |
19875 | S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D)); |
19876 | } |
19877 | |
19878 | void Visit(Expr *E) { |
19879 | if (llvm::is_contained(Range&: StopAt, Element: E)) |
19880 | return; |
19881 | Inherited::Visit(S: E); |
19882 | } |
19883 | |
19884 | void VisitConstantExpr(ConstantExpr *E) { |
19885 | // Don't mark declarations within a ConstantExpression, as this expression |
19886 | // will be evaluated and folded to a value. |
19887 | } |
19888 | |
19889 | void VisitDeclRefExpr(DeclRefExpr *E) { |
19890 | // If we were asked not to visit local variables, don't. |
19891 | if (SkipLocalVariables) { |
19892 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl())) |
19893 | if (VD->hasLocalStorage()) |
19894 | return; |
19895 | } |
19896 | |
19897 | // FIXME: This can trigger the instantiation of the initializer of a |
19898 | // variable, which can cause the expression to become value-dependent |
19899 | // or error-dependent. Do we need to propagate the new dependence bits? |
19900 | S.MarkDeclRefReferenced(E); |
19901 | } |
19902 | |
19903 | void VisitMemberExpr(MemberExpr *E) { |
19904 | S.MarkMemberReferenced(E); |
19905 | Visit(E: E->getBase()); |
19906 | } |
19907 | }; |
19908 | } // namespace |
19909 | |
19910 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, |
19911 | bool SkipLocalVariables, |
19912 | ArrayRef<const Expr*> StopAt) { |
19913 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); |
19914 | } |
19915 | |
19916 | /// Emit a diagnostic when statements are reachable. |
19917 | /// FIXME: check for reachability even in expressions for which we don't build a |
19918 | /// CFG (eg, in the initializer of a global or in a constant expression). |
19919 | /// For example, |
19920 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } |
19921 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, |
19922 | const PartialDiagnostic &PD) { |
19923 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { |
19924 | if (!FunctionScopes.empty()) |
19925 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( |
19926 | Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); |
19927 | return true; |
19928 | } |
19929 | |
19930 | // The initializer of a constexpr variable or of the first declaration of a |
19931 | // static data member is not syntactically a constant evaluated constant, |
19932 | // but nonetheless is always required to be a constant expression, so we |
19933 | // can skip diagnosing. |
19934 | // FIXME: Using the mangling context here is a hack. |
19935 | if (auto *VD = dyn_cast_or_null<VarDecl>( |
19936 | Val: ExprEvalContexts.back().ManglingContextDecl)) { |
19937 | if (VD->isConstexpr() || |
19938 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) |
19939 | return false; |
19940 | // FIXME: For any other kind of variable, we should build a CFG for its |
19941 | // initializer and check whether the context in question is reachable. |
19942 | } |
19943 | |
19944 | Diag(Loc, PD); |
19945 | return true; |
19946 | } |
19947 | |
19948 | /// Emit a diagnostic that describes an effect on the run-time behavior |
19949 | /// of the program being compiled. |
19950 | /// |
19951 | /// This routine emits the given diagnostic when the code currently being |
19952 | /// type-checked is "potentially evaluated", meaning that there is a |
19953 | /// possibility that the code will actually be executable. Code in sizeof() |
19954 | /// expressions, code used only during overload resolution, etc., are not |
19955 | /// potentially evaluated. This routine will suppress such diagnostics or, |
19956 | /// in the absolutely nutty case of potentially potentially evaluated |
19957 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it |
19958 | /// later. |
19959 | /// |
19960 | /// This routine should be used for all diagnostics that describe the run-time |
19961 | /// behavior of a program, such as passing a non-POD value through an ellipsis. |
19962 | /// Failure to do so will likely result in spurious diagnostics or failures |
19963 | /// during overload resolution or within sizeof/alignof/typeof/typeid. |
19964 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, |
19965 | const PartialDiagnostic &PD) { |
19966 | |
19967 | if (ExprEvalContexts.back().isDiscardedStatementContext()) |
19968 | return false; |
19969 | |
19970 | switch (ExprEvalContexts.back().Context) { |
19971 | case ExpressionEvaluationContext::Unevaluated: |
19972 | case ExpressionEvaluationContext::UnevaluatedList: |
19973 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
19974 | case ExpressionEvaluationContext::DiscardedStatement: |
19975 | // The argument will never be evaluated, so don't complain. |
19976 | break; |
19977 | |
19978 | case ExpressionEvaluationContext::ConstantEvaluated: |
19979 | case ExpressionEvaluationContext::ImmediateFunctionContext: |
19980 | // Relevant diagnostics should be produced by constant evaluation. |
19981 | break; |
19982 | |
19983 | case ExpressionEvaluationContext::PotentiallyEvaluated: |
19984 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
19985 | return DiagIfReachable(Loc, Stmts, PD); |
19986 | } |
19987 | |
19988 | return false; |
19989 | } |
19990 | |
19991 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
19992 | const PartialDiagnostic &PD) { |
19993 | return DiagRuntimeBehavior( |
19994 | Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD); |
19995 | } |
19996 | |
19997 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
19998 | CallExpr *CE, FunctionDecl *FD) { |
19999 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) |
20000 | return false; |
20001 | |
20002 | // If we're inside a decltype's expression, don't check for a valid return |
20003 | // type or construct temporaries until we know whether this is the last call. |
20004 | if (ExprEvalContexts.back().ExprContext == |
20005 | ExpressionEvaluationContextRecord::EK_Decltype) { |
20006 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE); |
20007 | return false; |
20008 | } |
20009 | |
20010 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { |
20011 | FunctionDecl *FD; |
20012 | CallExpr *CE; |
20013 | |
20014 | public: |
20015 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) |
20016 | : FD(FD), CE(CE) { } |
20017 | |
20018 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
20019 | if (!FD) { |
20020 | S.Diag(Loc, DiagID: diag::err_call_incomplete_return) |
20021 | << T << CE->getSourceRange(); |
20022 | return; |
20023 | } |
20024 | |
20025 | S.Diag(Loc, DiagID: diag::err_call_function_incomplete_return) |
20026 | << CE->getSourceRange() << FD << T; |
20027 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) |
20028 | << FD->getDeclName(); |
20029 | } |
20030 | } Diagnoser(FD, CE); |
20031 | |
20032 | if (RequireCompleteType(Loc, T: ReturnType, Diagnoser)) |
20033 | return true; |
20034 | |
20035 | return false; |
20036 | } |
20037 | |
20038 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses |
20039 | // will prevent this condition from triggering, which is what we want. |
20040 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { |
20041 | SourceLocation Loc; |
20042 | |
20043 | unsigned diagnostic = diag::warn_condition_is_assignment; |
20044 | bool IsOrAssign = false; |
20045 | |
20046 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) { |
20047 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) |
20048 | return; |
20049 | |
20050 | IsOrAssign = Op->getOpcode() == BO_OrAssign; |
20051 | |
20052 | // Greylist some idioms by putting them into a warning subcategory. |
20053 | if (ObjCMessageExpr *ME |
20054 | = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) { |
20055 | Selector Sel = ME->getSelector(); |
20056 | |
20057 | // self = [<foo> init...] |
20058 | if (ObjC().isSelfExpr(RExpr: Op->getLHS()) && ME->getMethodFamily() == OMF_init) |
20059 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
20060 | |
20061 | // <foo> = [<bar> nextObject] |
20062 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "nextObject" ) |
20063 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
20064 | } |
20065 | |
20066 | Loc = Op->getOperatorLoc(); |
20067 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
20068 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) |
20069 | return; |
20070 | |
20071 | IsOrAssign = Op->getOperator() == OO_PipeEqual; |
20072 | Loc = Op->getOperatorLoc(); |
20073 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) |
20074 | return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm()); |
20075 | else { |
20076 | // Not an assignment. |
20077 | return; |
20078 | } |
20079 | |
20080 | Diag(Loc, DiagID: diagnostic) << E->getSourceRange(); |
20081 | |
20082 | SourceLocation Open = E->getBeginLoc(); |
20083 | SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd()); |
20084 | Diag(Loc, DiagID: diag::note_condition_assign_silence) |
20085 | << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "(" ) |
20086 | << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")" ); |
20087 | |
20088 | if (IsOrAssign) |
20089 | Diag(Loc, DiagID: diag::note_condition_or_assign_to_comparison) |
20090 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "!=" ); |
20091 | else |
20092 | Diag(Loc, DiagID: diag::note_condition_assign_to_comparison) |
20093 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "==" ); |
20094 | } |
20095 | |
20096 | void Sema::(ParenExpr *ParenE) { |
20097 | // Don't warn if the parens came from a macro. |
20098 | SourceLocation parenLoc = ParenE->getBeginLoc(); |
20099 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) |
20100 | return; |
20101 | // Don't warn for dependent expressions. |
20102 | if (ParenE->isTypeDependent()) |
20103 | return; |
20104 | |
20105 | Expr *E = ParenE->IgnoreParens(); |
20106 | |
20107 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E)) |
20108 | if (opE->getOpcode() == BO_EQ && |
20109 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context) |
20110 | == Expr::MLV_Valid) { |
20111 | SourceLocation Loc = opE->getOperatorLoc(); |
20112 | |
20113 | Diag(Loc, DiagID: diag::warn_equality_with_extra_parens) << E->getSourceRange(); |
20114 | SourceRange ParenERange = ParenE->getSourceRange(); |
20115 | Diag(Loc, DiagID: diag::note_equality_comparison_silence) |
20116 | << FixItHint::CreateRemoval(RemoveRange: ParenERange.getBegin()) |
20117 | << FixItHint::CreateRemoval(RemoveRange: ParenERange.getEnd()); |
20118 | Diag(Loc, DiagID: diag::note_equality_comparison_to_assign) |
20119 | << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "=" ); |
20120 | } |
20121 | } |
20122 | |
20123 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, |
20124 | bool IsConstexpr) { |
20125 | DiagnoseAssignmentAsCondition(E); |
20126 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E)) |
20127 | DiagnoseEqualityWithExtraParens(ParenE: parenE); |
20128 | |
20129 | ExprResult result = CheckPlaceholderExpr(E); |
20130 | if (result.isInvalid()) return ExprError(); |
20131 | E = result.get(); |
20132 | |
20133 | if (!E->isTypeDependent()) { |
20134 | if (getLangOpts().CPlusPlus) |
20135 | return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4 |
20136 | |
20137 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); |
20138 | if (ERes.isInvalid()) |
20139 | return ExprError(); |
20140 | E = ERes.get(); |
20141 | |
20142 | QualType T = E->getType(); |
20143 | if (!T->isScalarType()) { // C99 6.8.4.1p1 |
20144 | Diag(Loc, DiagID: diag::err_typecheck_statement_requires_scalar) |
20145 | << T << E->getSourceRange(); |
20146 | return ExprError(); |
20147 | } |
20148 | CheckBoolLikeConversion(E, CC: Loc); |
20149 | } |
20150 | |
20151 | return E; |
20152 | } |
20153 | |
20154 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, |
20155 | Expr *SubExpr, ConditionKind CK, |
20156 | bool MissingOK) { |
20157 | // MissingOK indicates whether having no condition expression is valid |
20158 | // (for loop) or invalid (e.g. while loop). |
20159 | if (!SubExpr) |
20160 | return MissingOK ? ConditionResult() : ConditionError(); |
20161 | |
20162 | ExprResult Cond; |
20163 | switch (CK) { |
20164 | case ConditionKind::Boolean: |
20165 | Cond = CheckBooleanCondition(Loc, E: SubExpr); |
20166 | break; |
20167 | |
20168 | case ConditionKind::ConstexprIf: |
20169 | Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true); |
20170 | break; |
20171 | |
20172 | case ConditionKind::Switch: |
20173 | Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr); |
20174 | break; |
20175 | } |
20176 | if (Cond.isInvalid()) { |
20177 | Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(), |
20178 | SubExprs: {SubExpr}, T: PreferredConditionType(K: CK)); |
20179 | if (!Cond.get()) |
20180 | return ConditionError(); |
20181 | } |
20182 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. |
20183 | FullExprArg FullExpr = MakeFullExpr(Arg: Cond.get(), CC: Loc); |
20184 | if (!FullExpr.get()) |
20185 | return ConditionError(); |
20186 | |
20187 | return ConditionResult(*this, nullptr, FullExpr, |
20188 | CK == ConditionKind::ConstexprIf); |
20189 | } |
20190 | |
20191 | namespace { |
20192 | /// A visitor for rebuilding a call to an __unknown_any expression |
20193 | /// to have an appropriate type. |
20194 | struct RebuildUnknownAnyFunction |
20195 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { |
20196 | |
20197 | Sema &S; |
20198 | |
20199 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} |
20200 | |
20201 | ExprResult VisitStmt(Stmt *S) { |
20202 | llvm_unreachable("unexpected statement!" ); |
20203 | } |
20204 | |
20205 | ExprResult VisitExpr(Expr *E) { |
20206 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_call) |
20207 | << E->getSourceRange(); |
20208 | return ExprError(); |
20209 | } |
20210 | |
20211 | /// Rebuild an expression which simply semantically wraps another |
20212 | /// expression which it shares the type and value kind of. |
20213 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
20214 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
20215 | if (SubResult.isInvalid()) return ExprError(); |
20216 | |
20217 | Expr *SubExpr = SubResult.get(); |
20218 | E->setSubExpr(SubExpr); |
20219 | E->setType(SubExpr->getType()); |
20220 | E->setValueKind(SubExpr->getValueKind()); |
20221 | assert(E->getObjectKind() == OK_Ordinary); |
20222 | return E; |
20223 | } |
20224 | |
20225 | ExprResult VisitParenExpr(ParenExpr *E) { |
20226 | return rebuildSugarExpr(E); |
20227 | } |
20228 | |
20229 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
20230 | return rebuildSugarExpr(E); |
20231 | } |
20232 | |
20233 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
20234 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
20235 | if (SubResult.isInvalid()) return ExprError(); |
20236 | |
20237 | Expr *SubExpr = SubResult.get(); |
20238 | E->setSubExpr(SubExpr); |
20239 | E->setType(S.Context.getPointerType(T: SubExpr->getType())); |
20240 | assert(E->isPRValue()); |
20241 | assert(E->getObjectKind() == OK_Ordinary); |
20242 | return E; |
20243 | } |
20244 | |
20245 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { |
20246 | if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E); |
20247 | |
20248 | E->setType(VD->getType()); |
20249 | |
20250 | assert(E->isPRValue()); |
20251 | if (S.getLangOpts().CPlusPlus && |
20252 | !(isa<CXXMethodDecl>(Val: VD) && |
20253 | cast<CXXMethodDecl>(Val: VD)->isInstance())) |
20254 | E->setValueKind(VK_LValue); |
20255 | |
20256 | return E; |
20257 | } |
20258 | |
20259 | ExprResult VisitMemberExpr(MemberExpr *E) { |
20260 | return resolveDecl(E, VD: E->getMemberDecl()); |
20261 | } |
20262 | |
20263 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
20264 | return resolveDecl(E, VD: E->getDecl()); |
20265 | } |
20266 | }; |
20267 | } |
20268 | |
20269 | /// Given a function expression of unknown-any type, try to rebuild it |
20270 | /// to have a function type. |
20271 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { |
20272 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(S: FunctionExpr); |
20273 | if (Result.isInvalid()) return ExprError(); |
20274 | return S.DefaultFunctionArrayConversion(E: Result.get()); |
20275 | } |
20276 | |
20277 | namespace { |
20278 | /// A visitor for rebuilding an expression of type __unknown_anytype |
20279 | /// into one which resolves the type directly on the referring |
20280 | /// expression. Strict preservation of the original source |
20281 | /// structure is not a goal. |
20282 | struct RebuildUnknownAnyExpr |
20283 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { |
20284 | |
20285 | Sema &S; |
20286 | |
20287 | /// The current destination type. |
20288 | QualType DestType; |
20289 | |
20290 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) |
20291 | : S(S), DestType(CastType) {} |
20292 | |
20293 | ExprResult VisitStmt(Stmt *S) { |
20294 | llvm_unreachable("unexpected statement!" ); |
20295 | } |
20296 | |
20297 | ExprResult VisitExpr(Expr *E) { |
20298 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr) |
20299 | << E->getSourceRange(); |
20300 | return ExprError(); |
20301 | } |
20302 | |
20303 | ExprResult VisitCallExpr(CallExpr *E); |
20304 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); |
20305 | |
20306 | /// Rebuild an expression which simply semantically wraps another |
20307 | /// expression which it shares the type and value kind of. |
20308 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
20309 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
20310 | if (SubResult.isInvalid()) return ExprError(); |
20311 | Expr *SubExpr = SubResult.get(); |
20312 | E->setSubExpr(SubExpr); |
20313 | E->setType(SubExpr->getType()); |
20314 | E->setValueKind(SubExpr->getValueKind()); |
20315 | assert(E->getObjectKind() == OK_Ordinary); |
20316 | return E; |
20317 | } |
20318 | |
20319 | ExprResult VisitParenExpr(ParenExpr *E) { |
20320 | return rebuildSugarExpr(E); |
20321 | } |
20322 | |
20323 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
20324 | return rebuildSugarExpr(E); |
20325 | } |
20326 | |
20327 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
20328 | const PointerType *Ptr = DestType->getAs<PointerType>(); |
20329 | if (!Ptr) { |
20330 | S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof) |
20331 | << E->getSourceRange(); |
20332 | return ExprError(); |
20333 | } |
20334 | |
20335 | if (isa<CallExpr>(Val: E->getSubExpr())) { |
20336 | S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::err_unknown_any_addrof_call) |
20337 | << E->getSourceRange(); |
20338 | return ExprError(); |
20339 | } |
20340 | |
20341 | assert(E->isPRValue()); |
20342 | assert(E->getObjectKind() == OK_Ordinary); |
20343 | E->setType(DestType); |
20344 | |
20345 | // Build the sub-expression as if it were an object of the pointee type. |
20346 | DestType = Ptr->getPointeeType(); |
20347 | ExprResult SubResult = Visit(S: E->getSubExpr()); |
20348 | if (SubResult.isInvalid()) return ExprError(); |
20349 | E->setSubExpr(SubResult.get()); |
20350 | return E; |
20351 | } |
20352 | |
20353 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); |
20354 | |
20355 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); |
20356 | |
20357 | ExprResult VisitMemberExpr(MemberExpr *E) { |
20358 | return resolveDecl(E, VD: E->getMemberDecl()); |
20359 | } |
20360 | |
20361 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
20362 | return resolveDecl(E, VD: E->getDecl()); |
20363 | } |
20364 | }; |
20365 | } |
20366 | |
20367 | /// Rebuilds a call expression which yielded __unknown_anytype. |
20368 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { |
20369 | Expr *CalleeExpr = E->getCallee(); |
20370 | |
20371 | enum FnKind { |
20372 | FK_MemberFunction, |
20373 | FK_FunctionPointer, |
20374 | FK_BlockPointer |
20375 | }; |
20376 | |
20377 | FnKind Kind; |
20378 | QualType CalleeType = CalleeExpr->getType(); |
20379 | if (CalleeType == S.Context.BoundMemberTy) { |
20380 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); |
20381 | Kind = FK_MemberFunction; |
20382 | CalleeType = Expr::findBoundMemberType(expr: CalleeExpr); |
20383 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { |
20384 | CalleeType = Ptr->getPointeeType(); |
20385 | Kind = FK_FunctionPointer; |
20386 | } else { |
20387 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); |
20388 | Kind = FK_BlockPointer; |
20389 | } |
20390 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); |
20391 | |
20392 | // Verify that this is a legal result type of a function. |
20393 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
20394 | unsigned diagID = diag::err_func_returning_array_function; |
20395 | if (Kind == FK_BlockPointer) |
20396 | diagID = diag::err_block_returning_array_function; |
20397 | |
20398 | S.Diag(Loc: E->getExprLoc(), DiagID: diagID) |
20399 | << DestType->isFunctionType() << DestType; |
20400 | return ExprError(); |
20401 | } |
20402 | |
20403 | // Otherwise, go ahead and set DestType as the call's result. |
20404 | E->setType(DestType.getNonLValueExprType(Context: S.Context)); |
20405 | E->setValueKind(Expr::getValueKindForType(T: DestType)); |
20406 | assert(E->getObjectKind() == OK_Ordinary); |
20407 | |
20408 | // Rebuild the function type, replacing the result type with DestType. |
20409 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType); |
20410 | if (Proto) { |
20411 | // __unknown_anytype(...) is a special case used by the debugger when |
20412 | // it has no idea what a function's signature is. |
20413 | // |
20414 | // We want to build this call essentially under the K&R |
20415 | // unprototyped rules, but making a FunctionNoProtoType in C++ |
20416 | // would foul up all sorts of assumptions. However, we cannot |
20417 | // simply pass all arguments as variadic arguments, nor can we |
20418 | // portably just call the function under a non-variadic type; see |
20419 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. |
20420 | // However, it turns out that in practice it is generally safe to |
20421 | // call a function declared as "A foo(B,C,D);" under the prototype |
20422 | // "A foo(B,C,D,...);". The only known exception is with the |
20423 | // Windows ABI, where any variadic function is implicitly cdecl |
20424 | // regardless of its normal CC. Therefore we change the parameter |
20425 | // types to match the types of the arguments. |
20426 | // |
20427 | // This is a hack, but it is far superior to moving the |
20428 | // corresponding target-specific code from IR-gen to Sema/AST. |
20429 | |
20430 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); |
20431 | SmallVector<QualType, 8> ArgTypes; |
20432 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case |
20433 | ArgTypes.reserve(N: E->getNumArgs()); |
20434 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { |
20435 | ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i))); |
20436 | } |
20437 | ParamTypes = ArgTypes; |
20438 | } |
20439 | DestType = S.Context.getFunctionType(ResultTy: DestType, Args: ParamTypes, |
20440 | EPI: Proto->getExtProtoInfo()); |
20441 | } else { |
20442 | DestType = S.Context.getFunctionNoProtoType(ResultTy: DestType, |
20443 | Info: FnType->getExtInfo()); |
20444 | } |
20445 | |
20446 | // Rebuild the appropriate pointer-to-function type. |
20447 | switch (Kind) { |
20448 | case FK_MemberFunction: |
20449 | // Nothing to do. |
20450 | break; |
20451 | |
20452 | case FK_FunctionPointer: |
20453 | DestType = S.Context.getPointerType(T: DestType); |
20454 | break; |
20455 | |
20456 | case FK_BlockPointer: |
20457 | DestType = S.Context.getBlockPointerType(T: DestType); |
20458 | break; |
20459 | } |
20460 | |
20461 | // Finally, we can recurse. |
20462 | ExprResult CalleeResult = Visit(S: CalleeExpr); |
20463 | if (!CalleeResult.isUsable()) return ExprError(); |
20464 | E->setCallee(CalleeResult.get()); |
20465 | |
20466 | // Bind a temporary if necessary. |
20467 | return S.MaybeBindToTemporary(E); |
20468 | } |
20469 | |
20470 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { |
20471 | // Verify that this is a legal result type of a call. |
20472 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
20473 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_func_returning_array_function) |
20474 | << DestType->isFunctionType() << DestType; |
20475 | return ExprError(); |
20476 | } |
20477 | |
20478 | // Rewrite the method result type if available. |
20479 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { |
20480 | assert(Method->getReturnType() == S.Context.UnknownAnyTy); |
20481 | Method->setReturnType(DestType); |
20482 | } |
20483 | |
20484 | // Change the type of the message. |
20485 | E->setType(DestType.getNonReferenceType()); |
20486 | E->setValueKind(Expr::getValueKindForType(T: DestType)); |
20487 | |
20488 | return S.MaybeBindToTemporary(E); |
20489 | } |
20490 | |
20491 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { |
20492 | // The only case we should ever see here is a function-to-pointer decay. |
20493 | if (E->getCastKind() == CK_FunctionToPointerDecay) { |
20494 | assert(E->isPRValue()); |
20495 | assert(E->getObjectKind() == OK_Ordinary); |
20496 | |
20497 | E->setType(DestType); |
20498 | |
20499 | // Rebuild the sub-expression as the pointee (function) type. |
20500 | DestType = DestType->castAs<PointerType>()->getPointeeType(); |
20501 | |
20502 | ExprResult Result = Visit(S: E->getSubExpr()); |
20503 | if (!Result.isUsable()) return ExprError(); |
20504 | |
20505 | E->setSubExpr(Result.get()); |
20506 | return E; |
20507 | } else if (E->getCastKind() == CK_LValueToRValue) { |
20508 | assert(E->isPRValue()); |
20509 | assert(E->getObjectKind() == OK_Ordinary); |
20510 | |
20511 | assert(isa<BlockPointerType>(E->getType())); |
20512 | |
20513 | E->setType(DestType); |
20514 | |
20515 | // The sub-expression has to be a lvalue reference, so rebuild it as such. |
20516 | DestType = S.Context.getLValueReferenceType(T: DestType); |
20517 | |
20518 | ExprResult Result = Visit(S: E->getSubExpr()); |
20519 | if (!Result.isUsable()) return ExprError(); |
20520 | |
20521 | E->setSubExpr(Result.get()); |
20522 | return E; |
20523 | } else { |
20524 | llvm_unreachable("Unhandled cast type!" ); |
20525 | } |
20526 | } |
20527 | |
20528 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { |
20529 | ExprValueKind ValueKind = VK_LValue; |
20530 | QualType Type = DestType; |
20531 | |
20532 | // We know how to make this work for certain kinds of decls: |
20533 | |
20534 | // - functions |
20535 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) { |
20536 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { |
20537 | DestType = Ptr->getPointeeType(); |
20538 | ExprResult Result = resolveDecl(E, VD); |
20539 | if (Result.isInvalid()) return ExprError(); |
20540 | return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay, |
20541 | VK: VK_PRValue); |
20542 | } |
20543 | |
20544 | if (!Type->isFunctionType()) { |
20545 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_function) |
20546 | << VD << E->getSourceRange(); |
20547 | return ExprError(); |
20548 | } |
20549 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { |
20550 | // We must match the FunctionDecl's type to the hack introduced in |
20551 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown |
20552 | // type. See the lengthy commentary in that routine. |
20553 | QualType FDT = FD->getType(); |
20554 | const FunctionType *FnType = FDT->castAs<FunctionType>(); |
20555 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType); |
20556 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
20557 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { |
20558 | SourceLocation Loc = FD->getLocation(); |
20559 | FunctionDecl *NewFD = FunctionDecl::Create( |
20560 | C&: S.Context, DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc, |
20561 | N: FD->getNameInfo().getName(), T: DestType, TInfo: FD->getTypeSourceInfo(), |
20562 | SC: SC_None, UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(), |
20563 | isInlineSpecified: false /*isInlineSpecified*/, hasWrittenPrototype: FD->hasPrototype(), |
20564 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); |
20565 | |
20566 | if (FD->getQualifier()) |
20567 | NewFD->setQualifierInfo(FD->getQualifierLoc()); |
20568 | |
20569 | SmallVector<ParmVarDecl*, 16> Params; |
20570 | for (const auto &AI : FT->param_types()) { |
20571 | ParmVarDecl *Param = |
20572 | S.BuildParmVarDeclForTypedef(DC: FD, Loc, T: AI); |
20573 | Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
20574 | Params.push_back(Elt: Param); |
20575 | } |
20576 | NewFD->setParams(Params); |
20577 | DRE->setDecl(NewFD); |
20578 | VD = DRE->getDecl(); |
20579 | } |
20580 | } |
20581 | |
20582 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
20583 | if (MD->isInstance()) { |
20584 | ValueKind = VK_PRValue; |
20585 | Type = S.Context.BoundMemberTy; |
20586 | } |
20587 | |
20588 | // Function references aren't l-values in C. |
20589 | if (!S.getLangOpts().CPlusPlus) |
20590 | ValueKind = VK_PRValue; |
20591 | |
20592 | // - variables |
20593 | } else if (isa<VarDecl>(Val: VD)) { |
20594 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { |
20595 | Type = RefTy->getPointeeType(); |
20596 | } else if (Type->isFunctionType()) { |
20597 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unknown_any_var_function_type) |
20598 | << VD << E->getSourceRange(); |
20599 | return ExprError(); |
20600 | } |
20601 | |
20602 | // - nothing else |
20603 | } else { |
20604 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_decl) |
20605 | << VD << E->getSourceRange(); |
20606 | return ExprError(); |
20607 | } |
20608 | |
20609 | // Modifying the declaration like this is friendly to IR-gen but |
20610 | // also really dangerous. |
20611 | VD->setType(DestType); |
20612 | E->setType(Type); |
20613 | E->setValueKind(ValueKind); |
20614 | return E; |
20615 | } |
20616 | |
20617 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
20618 | Expr *CastExpr, CastKind &CastKind, |
20619 | ExprValueKind &VK, CXXCastPath &Path) { |
20620 | // The type we're casting to must be either void or complete. |
20621 | if (!CastType->isVoidType() && |
20622 | RequireCompleteType(Loc: TypeRange.getBegin(), T: CastType, |
20623 | DiagID: diag::err_typecheck_cast_to_incomplete)) |
20624 | return ExprError(); |
20625 | |
20626 | // Rewrite the casted expression from scratch. |
20627 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(S: CastExpr); |
20628 | if (!result.isUsable()) return ExprError(); |
20629 | |
20630 | CastExpr = result.get(); |
20631 | VK = CastExpr->getValueKind(); |
20632 | CastKind = CK_NoOp; |
20633 | |
20634 | return CastExpr; |
20635 | } |
20636 | |
20637 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { |
20638 | return RebuildUnknownAnyExpr(*this, ToType).Visit(S: E); |
20639 | } |
20640 | |
20641 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, |
20642 | Expr *arg, QualType ¶mType) { |
20643 | // If the syntactic form of the argument is not an explicit cast of |
20644 | // any sort, just do default argument promotion. |
20645 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens()); |
20646 | if (!castArg) { |
20647 | ExprResult result = DefaultArgumentPromotion(E: arg); |
20648 | if (result.isInvalid()) return ExprError(); |
20649 | paramType = result.get()->getType(); |
20650 | return result; |
20651 | } |
20652 | |
20653 | // Otherwise, use the type that was written in the explicit cast. |
20654 | assert(!arg->hasPlaceholderType()); |
20655 | paramType = castArg->getTypeAsWritten(); |
20656 | |
20657 | // Copy-initialize a parameter of that type. |
20658 | InitializedEntity entity = |
20659 | InitializedEntity::InitializeParameter(Context, Type: paramType, |
20660 | /*consumed*/ Consumed: false); |
20661 | return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg); |
20662 | } |
20663 | |
20664 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { |
20665 | Expr *orig = E; |
20666 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; |
20667 | while (true) { |
20668 | E = E->IgnoreParenImpCasts(); |
20669 | if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) { |
20670 | E = call->getCallee(); |
20671 | diagID = diag::err_uncasted_call_of_unknown_any; |
20672 | } else { |
20673 | break; |
20674 | } |
20675 | } |
20676 | |
20677 | SourceLocation loc; |
20678 | NamedDecl *d; |
20679 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) { |
20680 | loc = ref->getLocation(); |
20681 | d = ref->getDecl(); |
20682 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) { |
20683 | loc = mem->getMemberLoc(); |
20684 | d = mem->getMemberDecl(); |
20685 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) { |
20686 | diagID = diag::err_uncasted_call_of_unknown_any; |
20687 | loc = msg->getSelectorStartLoc(); |
20688 | d = msg->getMethodDecl(); |
20689 | if (!d) { |
20690 | S.Diag(Loc: loc, DiagID: diag::err_uncasted_send_to_unknown_any_method) |
20691 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() |
20692 | << orig->getSourceRange(); |
20693 | return ExprError(); |
20694 | } |
20695 | } else { |
20696 | S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_unknown_any_expr) |
20697 | << E->getSourceRange(); |
20698 | return ExprError(); |
20699 | } |
20700 | |
20701 | S.Diag(Loc: loc, DiagID: diagID) << d << orig->getSourceRange(); |
20702 | |
20703 | // Never recoverable. |
20704 | return ExprError(); |
20705 | } |
20706 | |
20707 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { |
20708 | if (!Context.isDependenceAllowed()) { |
20709 | // C cannot handle TypoExpr nodes on either side of a binop because it |
20710 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
20711 | // been dealt with before checking the operands. |
20712 | ExprResult Result = CorrectDelayedTyposInExpr(E); |
20713 | if (!Result.isUsable()) return ExprError(); |
20714 | E = Result.get(); |
20715 | } |
20716 | |
20717 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); |
20718 | if (!placeholderType) return E; |
20719 | |
20720 | switch (placeholderType->getKind()) { |
20721 | case BuiltinType::UnresolvedTemplate: { |
20722 | auto *ULE = cast<UnresolvedLookupExpr>(Val: E); |
20723 | const DeclarationNameInfo &NameInfo = ULE->getNameInfo(); |
20724 | // There's only one FoundDecl for UnresolvedTemplate type. See |
20725 | // BuildTemplateIdExpr. |
20726 | NamedDecl *Temp = *ULE->decls_begin(); |
20727 | const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp); |
20728 | |
20729 | if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier()) |
20730 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template) |
20731 | << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString() |
20732 | << Loc.getSourceRange() << IsTypeAliasTemplateDecl; |
20733 | else |
20734 | Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_template_kw_refers_to_type_template) |
20735 | << "" << NameInfo.getName().getAsString() << ULE->getSourceRange() |
20736 | << IsTypeAliasTemplateDecl; |
20737 | Diag(Loc: Temp->getLocation(), DiagID: diag::note_referenced_type_template) |
20738 | << IsTypeAliasTemplateDecl; |
20739 | |
20740 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}); |
20741 | } |
20742 | |
20743 | // Overloaded expressions. |
20744 | case BuiltinType::Overload: { |
20745 | // Try to resolve a single function template specialization. |
20746 | // This is obligatory. |
20747 | ExprResult Result = E; |
20748 | if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false)) |
20749 | return Result; |
20750 | |
20751 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization |
20752 | // leaves Result unchanged on failure. |
20753 | Result = E; |
20754 | if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result)) |
20755 | return Result; |
20756 | |
20757 | // If that failed, try to recover with a call. |
20758 | tryToRecoverWithCall(E&: Result, PD: PDiag(DiagID: diag::err_ovl_unresolvable), |
20759 | /*complain*/ ForceComplain: true); |
20760 | return Result; |
20761 | } |
20762 | |
20763 | // Bound member functions. |
20764 | case BuiltinType::BoundMember: { |
20765 | ExprResult result = E; |
20766 | const Expr *BME = E->IgnoreParens(); |
20767 | PartialDiagnostic PD = PDiag(DiagID: diag::err_bound_member_function); |
20768 | // Try to give a nicer diagnostic if it is a bound member that we recognize. |
20769 | if (isa<CXXPseudoDestructorExpr>(Val: BME)) { |
20770 | PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; |
20771 | } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) { |
20772 | if (ME->getMemberNameInfo().getName().getNameKind() == |
20773 | DeclarationName::CXXDestructorName) |
20774 | PD = PDiag(DiagID: diag::err_dtor_expr_without_call) << /*destructor*/ 0; |
20775 | } |
20776 | tryToRecoverWithCall(E&: result, PD, |
20777 | /*complain*/ ForceComplain: true); |
20778 | return result; |
20779 | } |
20780 | |
20781 | // ARC unbridged casts. |
20782 | case BuiltinType::ARCUnbridgedCast: { |
20783 | Expr *realCast = ObjC().stripARCUnbridgedCast(e: E); |
20784 | ObjC().diagnoseARCUnbridgedCast(e: realCast); |
20785 | return realCast; |
20786 | } |
20787 | |
20788 | // Expressions of unknown type. |
20789 | case BuiltinType::UnknownAny: |
20790 | return diagnoseUnknownAnyExpr(S&: *this, E); |
20791 | |
20792 | // Pseudo-objects. |
20793 | case BuiltinType::PseudoObject: |
20794 | return PseudoObject().checkRValue(E); |
20795 | |
20796 | case BuiltinType::BuiltinFn: { |
20797 | // Accept __noop without parens by implicitly converting it to a call expr. |
20798 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()); |
20799 | if (DRE) { |
20800 | auto *FD = cast<FunctionDecl>(Val: DRE->getDecl()); |
20801 | unsigned BuiltinID = FD->getBuiltinID(); |
20802 | if (BuiltinID == Builtin::BI__noop) { |
20803 | E = ImpCastExprToType(E, Type: Context.getPointerType(T: FD->getType()), |
20804 | CK: CK_BuiltinFnToFnPtr) |
20805 | .get(); |
20806 | return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy, |
20807 | VK: VK_PRValue, RParenLoc: SourceLocation(), |
20808 | FPFeatures: FPOptionsOverride()); |
20809 | } |
20810 | |
20811 | if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) { |
20812 | // Any use of these other than a direct call is ill-formed as of C++20, |
20813 | // because they are not addressable functions. In earlier language |
20814 | // modes, warn and force an instantiation of the real body. |
20815 | Diag(Loc: E->getBeginLoc(), |
20816 | DiagID: getLangOpts().CPlusPlus20 |
20817 | ? diag::err_use_of_unaddressable_function |
20818 | : diag::warn_cxx20_compat_use_of_unaddressable_function); |
20819 | if (FD->isImplicitlyInstantiable()) { |
20820 | // Require a definition here because a normal attempt at |
20821 | // instantiation for a builtin will be ignored, and we won't try |
20822 | // again later. We assume that the definition of the template |
20823 | // precedes this use. |
20824 | InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD, |
20825 | /*Recursive=*/false, |
20826 | /*DefinitionRequired=*/true, |
20827 | /*AtEndOfTU=*/false); |
20828 | } |
20829 | // Produce a properly-typed reference to the function. |
20830 | CXXScopeSpec SS; |
20831 | SS.Adopt(Other: DRE->getQualifierLoc()); |
20832 | TemplateArgumentListInfo TemplateArgs; |
20833 | DRE->copyTemplateArgumentsInto(List&: TemplateArgs); |
20834 | return BuildDeclRefExpr( |
20835 | D: FD, Ty: FD->getType(), VK: VK_LValue, NameInfo: DRE->getNameInfo(), |
20836 | SS: DRE->hasQualifier() ? &SS : nullptr, FoundD: DRE->getFoundDecl(), |
20837 | TemplateKWLoc: DRE->getTemplateKeywordLoc(), |
20838 | TemplateArgs: DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); |
20839 | } |
20840 | } |
20841 | |
20842 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_builtin_fn_use); |
20843 | return ExprError(); |
20844 | } |
20845 | |
20846 | case BuiltinType::IncompleteMatrixIdx: |
20847 | Diag(Loc: cast<MatrixSubscriptExpr>(Val: E->IgnoreParens()) |
20848 | ->getRowIdx() |
20849 | ->getBeginLoc(), |
20850 | DiagID: diag::err_matrix_incomplete_index); |
20851 | return ExprError(); |
20852 | |
20853 | // Expressions of unknown type. |
20854 | case BuiltinType::ArraySection: |
20855 | Diag(Loc: E->getBeginLoc(), DiagID: diag::err_array_section_use) |
20856 | << cast<ArraySectionExpr>(Val: E)->isOMPArraySection(); |
20857 | return ExprError(); |
20858 | |
20859 | // Expressions of unknown type. |
20860 | case BuiltinType::OMPArrayShaping: |
20861 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_array_shaping_use)); |
20862 | |
20863 | case BuiltinType::OMPIterator: |
20864 | return ExprError(Diag(Loc: E->getBeginLoc(), DiagID: diag::err_omp_iterator_use)); |
20865 | |
20866 | // Everything else should be impossible. |
20867 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
20868 | case BuiltinType::Id: |
20869 | #include "clang/Basic/OpenCLImageTypes.def" |
20870 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
20871 | case BuiltinType::Id: |
20872 | #include "clang/Basic/OpenCLExtensionTypes.def" |
20873 | #define SVE_TYPE(Name, Id, SingletonId) \ |
20874 | case BuiltinType::Id: |
20875 | #include "clang/Basic/AArch64SVEACLETypes.def" |
20876 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
20877 | case BuiltinType::Id: |
20878 | #include "clang/Basic/PPCTypes.def" |
20879 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
20880 | #include "clang/Basic/RISCVVTypes.def" |
20881 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
20882 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
20883 | #define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
20884 | #include "clang/Basic/AMDGPUTypes.def" |
20885 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: |
20886 | #define PLACEHOLDER_TYPE(Id, SingletonId) |
20887 | #include "clang/AST/BuiltinTypes.def" |
20888 | break; |
20889 | } |
20890 | |
20891 | llvm_unreachable("invalid placeholder type!" ); |
20892 | } |
20893 | |
20894 | bool Sema::CheckCaseExpression(Expr *E) { |
20895 | if (E->isTypeDependent()) |
20896 | return true; |
20897 | if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context)) |
20898 | return E->getType()->isIntegralOrEnumerationType(); |
20899 | return false; |
20900 | } |
20901 | |
20902 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, |
20903 | ArrayRef<Expr *> SubExprs, QualType T) { |
20904 | if (!Context.getLangOpts().RecoveryAST) |
20905 | return ExprError(); |
20906 | |
20907 | if (isSFINAEContext()) |
20908 | return ExprError(); |
20909 | |
20910 | if (T.isNull() || T->isUndeducedType() || |
20911 | !Context.getLangOpts().RecoveryASTType) |
20912 | // We don't know the concrete type, fallback to dependent type. |
20913 | T = Context.DependentTy; |
20914 | |
20915 | return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs); |
20916 | } |
20917 | |