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/ASTDiagnostic.h" |
19 | #include "clang/AST/ASTLambda.h" |
20 | #include "clang/AST/ASTMutationListener.h" |
21 | #include "clang/AST/CXXInheritance.h" |
22 | #include "clang/AST/Decl.h" |
23 | #include "clang/AST/DeclObjC.h" |
24 | #include "clang/AST/DeclTemplate.h" |
25 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
26 | #include "clang/AST/EvaluatedExprVisitor.h" |
27 | #include "clang/AST/Expr.h" |
28 | #include "clang/AST/ExprCXX.h" |
29 | #include "clang/AST/ExprObjC.h" |
30 | #include "clang/AST/MangleNumberingContext.h" |
31 | #include "clang/AST/OperationKinds.h" |
32 | #include "clang/AST/Type.h" |
33 | #include "clang/AST/TypeLoc.h" |
34 | #include "clang/Basic/Builtins.h" |
35 | #include "clang/Basic/DiagnosticSema.h" |
36 | #include "clang/Basic/PartialDiagnostic.h" |
37 | #include "clang/Basic/SourceManager.h" |
38 | #include "clang/Basic/Specifiers.h" |
39 | #include "clang/Basic/TargetInfo.h" |
40 | #include "clang/Basic/TypeTraits.h" |
41 | #include "clang/Lex/LiteralSupport.h" |
42 | #include "clang/Lex/Preprocessor.h" |
43 | #include "clang/Sema/AnalysisBasedWarnings.h" |
44 | #include "clang/Sema/DeclSpec.h" |
45 | #include "clang/Sema/DelayedDiagnostic.h" |
46 | #include "clang/Sema/Designator.h" |
47 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
48 | #include "clang/Sema/Initialization.h" |
49 | #include "clang/Sema/Lookup.h" |
50 | #include "clang/Sema/Overload.h" |
51 | #include "clang/Sema/ParsedTemplate.h" |
52 | #include "clang/Sema/Scope.h" |
53 | #include "clang/Sema/ScopeInfo.h" |
54 | #include "clang/Sema/SemaCUDA.h" |
55 | #include "clang/Sema/SemaFixItUtils.h" |
56 | #include "clang/Sema/SemaHLSL.h" |
57 | #include "clang/Sema/SemaInternal.h" |
58 | #include "clang/Sema/SemaObjC.h" |
59 | #include "clang/Sema/SemaOpenMP.h" |
60 | #include "clang/Sema/SemaPseudoObject.h" |
61 | #include "clang/Sema/Template.h" |
62 | #include "llvm/ADT/STLExtras.h" |
63 | #include "llvm/ADT/StringExtras.h" |
64 | #include "llvm/Support/ConvertUTF.h" |
65 | #include "llvm/Support/SaveAndRestore.h" |
66 | #include "llvm/Support/TimeProfiler.h" |
67 | #include "llvm/Support/TypeSize.h" |
68 | #include <optional> |
69 | |
70 | using namespace clang; |
71 | using namespace sema; |
72 | |
73 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { |
74 | // See if this is an auto-typed variable whose initializer we are parsing. |
75 | if (ParsingInitForAutoVars.count(D)) |
76 | return false; |
77 | |
78 | // See if this is a deleted function. |
79 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
80 | if (FD->isDeleted()) |
81 | return false; |
82 | |
83 | // If the function has a deduced return type, and we can't deduce it, |
84 | // then we can't use it either. |
85 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
86 | DeduceReturnType(FD, Loc: SourceLocation(), /*Diagnose*/ false)) |
87 | return false; |
88 | |
89 | // See if this is an aligned allocation/deallocation function that is |
90 | // unavailable. |
91 | if (TreatUnavailableAsInvalid && |
92 | isUnavailableAlignedAllocationFunction(FD: *FD)) |
93 | return false; |
94 | } |
95 | |
96 | // See if this function is unavailable. |
97 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && |
98 | cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable) |
99 | return false; |
100 | |
101 | if (isa<UnresolvedUsingIfExistsDecl>(Val: D)) |
102 | return false; |
103 | |
104 | return true; |
105 | } |
106 | |
107 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { |
108 | // Warn if this is used but marked unused. |
109 | if (const auto *A = D->getAttr<UnusedAttr>()) { |
110 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) |
111 | // should diagnose them. |
112 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && |
113 | A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) { |
114 | const Decl *DC = cast_or_null<Decl>(Val: S.ObjC().getCurObjCLexicalContext()); |
115 | if (DC && !DC->hasAttr<UnusedAttr>()) |
116 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; |
117 | } |
118 | } |
119 | } |
120 | |
121 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { |
122 | assert(Decl && Decl->isDeleted()); |
123 | |
124 | if (Decl->isDefaulted()) { |
125 | // If the method was explicitly defaulted, point at that declaration. |
126 | if (!Decl->isImplicit()) |
127 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); |
128 | |
129 | // Try to diagnose why this special member function was implicitly |
130 | // deleted. This might fail, if that reason no longer applies. |
131 | DiagnoseDeletedDefaultedFunction(FD: Decl); |
132 | return; |
133 | } |
134 | |
135 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl); |
136 | if (Ctor && Ctor->isInheritingConstructor()) |
137 | return NoteDeletedInheritingConstructor(CD: Ctor); |
138 | |
139 | Diag(Decl->getLocation(), diag::note_availability_specified_here) |
140 | << Decl << 1; |
141 | } |
142 | |
143 | /// Determine whether a FunctionDecl was ever declared with an |
144 | /// explicit storage class. |
145 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { |
146 | for (auto *I : D->redecls()) { |
147 | if (I->getStorageClass() != SC_None) |
148 | return true; |
149 | } |
150 | return false; |
151 | } |
152 | |
153 | /// Check whether we're in an extern inline function and referring to a |
154 | /// variable or function with internal linkage (C11 6.7.4p3). |
155 | /// |
156 | /// This is only a warning because we used to silently accept this code, but |
157 | /// in many cases it will not behave correctly. This is not enabled in C++ mode |
158 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) |
159 | /// and so while there may still be user mistakes, most of the time we can't |
160 | /// prove that there are errors. |
161 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, |
162 | const NamedDecl *D, |
163 | SourceLocation Loc) { |
164 | // This is disabled under C++; there are too many ways for this to fire in |
165 | // contexts where the warning is a false positive, or where it is technically |
166 | // correct but benign. |
167 | if (S.getLangOpts().CPlusPlus) |
168 | return; |
169 | |
170 | // Check if this is an inlined function or method. |
171 | FunctionDecl *Current = S.getCurFunctionDecl(); |
172 | if (!Current) |
173 | return; |
174 | if (!Current->isInlined()) |
175 | return; |
176 | if (!Current->isExternallyVisible()) |
177 | return; |
178 | |
179 | // Check if the decl has internal linkage. |
180 | if (D->getFormalLinkage() != Linkage::Internal) |
181 | return; |
182 | |
183 | // Downgrade from ExtWarn to Extension if |
184 | // (1) the supposedly external inline function is in the main file, |
185 | // and probably won't be included anywhere else. |
186 | // (2) the thing we're referencing is a pure function. |
187 | // (3) the thing we're referencing is another inline function. |
188 | // This last can give us false negatives, but it's better than warning on |
189 | // wrappers for simple C library functions. |
190 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(Val: D); |
191 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); |
192 | if (!DowngradeWarning && UsedFn) |
193 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); |
194 | |
195 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet |
196 | : diag::ext_internal_in_extern_inline) |
197 | << /*IsVar=*/!UsedFn << D; |
198 | |
199 | S.MaybeSuggestAddingStaticToDecl(D: Current); |
200 | |
201 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) |
202 | << D; |
203 | } |
204 | |
205 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { |
206 | const FunctionDecl *First = Cur->getFirstDecl(); |
207 | |
208 | // Suggest "static" on the function, if possible. |
209 | if (!hasAnyExplicitStorageClass(D: First)) { |
210 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); |
211 | Diag(DeclBegin, diag::note_convert_inline_to_static) |
212 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); |
213 | } |
214 | } |
215 | |
216 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
217 | const ObjCInterfaceDecl *UnknownObjCClass, |
218 | bool ObjCPropertyAccess, |
219 | bool AvoidPartialAvailabilityChecks, |
220 | ObjCInterfaceDecl *ClassReceiver, |
221 | bool SkipTrailingRequiresClause) { |
222 | SourceLocation Loc = Locs.front(); |
223 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(Val: D)) { |
224 | // If there were any diagnostics suppressed by template argument deduction, |
225 | // emit them now. |
226 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); |
227 | if (Pos != SuppressedDiagnostics.end()) { |
228 | for (const auto &[DiagLoc, PD] : Pos->second) { |
229 | DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID())); |
230 | PD.Emit(Builder); |
231 | } |
232 | // Clear out the list of suppressed diagnostics, so that we don't emit |
233 | // them again for this specialization. However, we don't obsolete this |
234 | // entry from the table, because we want to avoid ever emitting these |
235 | // diagnostics again. |
236 | Pos->second.clear(); |
237 | } |
238 | |
239 | // C++ [basic.start.main]p3: |
240 | // The function 'main' shall not be used within a program. |
241 | if (cast<FunctionDecl>(D)->isMain()) |
242 | Diag(Loc, diag::ext_main_used); |
243 | |
244 | diagnoseUnavailableAlignedAllocation(FD: *cast<FunctionDecl>(Val: D), Loc); |
245 | } |
246 | |
247 | // See if this is an auto-typed variable whose initializer we are parsing. |
248 | if (ParsingInitForAutoVars.count(D)) { |
249 | if (isa<BindingDecl>(Val: D)) { |
250 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) |
251 | << D->getDeclName(); |
252 | } else { |
253 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) |
254 | << diag::ParsingInitFor::Var << D->getDeclName() |
255 | << cast<VarDecl>(D)->getType(); |
256 | } |
257 | return true; |
258 | } |
259 | |
260 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
261 | // See if this is a deleted function. |
262 | if (FD->isDeleted()) { |
263 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD); |
264 | if (Ctor && Ctor->isInheritingConstructor()) |
265 | Diag(Loc, diag::err_deleted_inherited_ctor_use) |
266 | << Ctor->getParent() |
267 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); |
268 | else { |
269 | StringLiteral *Msg = FD->getDeletedMessage(); |
270 | Diag(Loc, diag::err_deleted_function_use) |
271 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
272 | } |
273 | NoteDeletedFunction(Decl: FD); |
274 | return true; |
275 | } |
276 | |
277 | // [expr.prim.id]p4 |
278 | // A program that refers explicitly or implicitly to a function with a |
279 | // trailing requires-clause whose constraint-expression is not satisfied, |
280 | // other than to declare it, is ill-formed. [...] |
281 | // |
282 | // See if this is a function with constraints that need to be satisfied. |
283 | // Check this before deducing the return type, as it might instantiate the |
284 | // definition. |
285 | if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { |
286 | ConstraintSatisfaction Satisfaction; |
287 | if (CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc, |
288 | /*ForOverloadResolution*/ true)) |
289 | // A diagnostic will have already been generated (non-constant |
290 | // constraint expression, for example) |
291 | return true; |
292 | if (!Satisfaction.IsSatisfied) { |
293 | Diag(Loc, |
294 | diag::err_reference_to_function_with_unsatisfied_constraints) |
295 | << D; |
296 | DiagnoseUnsatisfiedConstraint(Satisfaction); |
297 | return true; |
298 | } |
299 | } |
300 | |
301 | // If the function has a deduced return type, and we can't deduce it, |
302 | // then we can't use it either. |
303 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
304 | DeduceReturnType(FD, Loc)) |
305 | return true; |
306 | |
307 | if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, Callee: FD)) |
308 | return true; |
309 | |
310 | } |
311 | |
312 | if (auto *Concept = dyn_cast<ConceptDecl>(Val: D); |
313 | Concept && CheckConceptUseInDefinition(Concept, Loc)) |
314 | return true; |
315 | |
316 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) { |
317 | // Lambdas are only default-constructible or assignable in C++2a onwards. |
318 | if (MD->getParent()->isLambda() && |
319 | ((isa<CXXConstructorDecl>(Val: MD) && |
320 | cast<CXXConstructorDecl>(Val: MD)->isDefaultConstructor()) || |
321 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { |
322 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) |
323 | << !isa<CXXConstructorDecl>(MD); |
324 | } |
325 | } |
326 | |
327 | auto getReferencedObjCProp = [](const NamedDecl *D) -> |
328 | const ObjCPropertyDecl * { |
329 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) |
330 | return MD->findPropertyDecl(); |
331 | return nullptr; |
332 | }; |
333 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { |
334 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) |
335 | return true; |
336 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(ND: D, Loc)) { |
337 | return true; |
338 | } |
339 | |
340 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions |
341 | // Only the variables omp_in and omp_out are allowed in the combiner. |
342 | // Only the variables omp_priv and omp_orig are allowed in the |
343 | // initializer-clause. |
344 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: CurContext); |
345 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && |
346 | isa<VarDecl>(Val: D)) { |
347 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) |
348 | << getCurFunction()->HasOMPDeclareReductionCombiner; |
349 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; |
350 | return true; |
351 | } |
352 | |
353 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions |
354 | // List-items in map clauses on this construct may only refer to the declared |
355 | // variable var and entities that could be referenced by a procedure defined |
356 | // at the same location. |
357 | // [OpenMP 5.2] Also allow iterator declared variables. |
358 | if (LangOpts.OpenMP && isa<VarDecl>(Val: D) && |
359 | !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) { |
360 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) |
361 | << OpenMP().getOpenMPDeclareMapperVarName(); |
362 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; |
363 | return true; |
364 | } |
365 | |
366 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: D)) { |
367 | Diag(Loc, diag::err_use_of_empty_using_if_exists); |
368 | Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); |
369 | return true; |
370 | } |
371 | |
372 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, |
373 | AvoidPartialAvailabilityChecks, ClassReceiver); |
374 | |
375 | DiagnoseUnusedOfDecl(S&: *this, D, Loc); |
376 | |
377 | diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc); |
378 | |
379 | if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) { |
380 | if (getLangOpts().getFPEvalMethod() != |
381 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine && |
382 | PP.getLastFPEvalPragmaLocation().isValid() && |
383 | PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod()) |
384 | Diag(D->getLocation(), |
385 | diag::err_type_available_only_in_default_eval_method) |
386 | << D->getName(); |
387 | } |
388 | |
389 | if (auto *VD = dyn_cast<ValueDecl>(Val: D)) |
390 | checkTypeSupport(Ty: VD->getType(), Loc, D: VD); |
391 | |
392 | if (LangOpts.SYCLIsDevice || |
393 | (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) { |
394 | if (!Context.getTargetInfo().isTLSSupported()) |
395 | if (const auto *VD = dyn_cast<VarDecl>(D)) |
396 | if (VD->getTLSKind() != VarDecl::TLS_None) |
397 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); |
398 | } |
399 | |
400 | return false; |
401 | } |
402 | |
403 | void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, |
404 | ArrayRef<Expr *> Args) { |
405 | const SentinelAttr *Attr = D->getAttr<SentinelAttr>(); |
406 | if (!Attr) |
407 | return; |
408 | |
409 | // The number of formal parameters of the declaration. |
410 | unsigned NumFormalParams; |
411 | |
412 | // The kind of declaration. This is also an index into a %select in |
413 | // the diagnostic. |
414 | enum { CK_Function, CK_Method, CK_Block } CalleeKind; |
415 | |
416 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
417 | NumFormalParams = MD->param_size(); |
418 | CalleeKind = CK_Method; |
419 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
420 | NumFormalParams = FD->param_size(); |
421 | CalleeKind = CK_Function; |
422 | } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
423 | QualType Ty = VD->getType(); |
424 | const FunctionType *Fn = nullptr; |
425 | if (const auto *PtrTy = Ty->getAs<PointerType>()) { |
426 | Fn = PtrTy->getPointeeType()->getAs<FunctionType>(); |
427 | if (!Fn) |
428 | return; |
429 | CalleeKind = CK_Function; |
430 | } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) { |
431 | Fn = PtrTy->getPointeeType()->castAs<FunctionType>(); |
432 | CalleeKind = CK_Block; |
433 | } else { |
434 | return; |
435 | } |
436 | |
437 | if (const auto *proto = dyn_cast<FunctionProtoType>(Val: Fn)) |
438 | NumFormalParams = proto->getNumParams(); |
439 | else |
440 | NumFormalParams = 0; |
441 | } else { |
442 | return; |
443 | } |
444 | |
445 | // "NullPos" is the number of formal parameters at the end which |
446 | // effectively count as part of the variadic arguments. This is |
447 | // useful if you would prefer to not have *any* formal parameters, |
448 | // but the language forces you to have at least one. |
449 | unsigned NullPos = Attr->getNullPos(); |
450 | assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel"); |
451 | NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos); |
452 | |
453 | // The number of arguments which should follow the sentinel. |
454 | unsigned NumArgsAfterSentinel = Attr->getSentinel(); |
455 | |
456 | // If there aren't enough arguments for all the formal parameters, |
457 | // the sentinel, and the args after the sentinel, complain. |
458 | if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) { |
459 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); |
460 | Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind); |
461 | return; |
462 | } |
463 | |
464 | // Otherwise, find the sentinel expression. |
465 | const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1]; |
466 | if (!SentinelExpr) |
467 | return; |
468 | if (SentinelExpr->isValueDependent()) |
469 | return; |
470 | if (Context.isSentinelNullExpr(E: SentinelExpr)) |
471 | return; |
472 | |
473 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', |
474 | // or 'NULL' if those are actually defined in the context. Only use |
475 | // 'nil' for ObjC methods, where it's much more likely that the |
476 | // variadic arguments form a list of object pointers. |
477 | SourceLocation MissingNilLoc = getLocForEndOfToken(Loc: SentinelExpr->getEndLoc()); |
478 | std::string NullValue; |
479 | if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil")) |
480 | NullValue = "nil"; |
481 | else if (getLangOpts().CPlusPlus11) |
482 | NullValue = "nullptr"; |
483 | else if (PP.isMacroDefined(Id: "NULL")) |
484 | NullValue = "NULL"; |
485 | else |
486 | NullValue = "(void*) 0"; |
487 | |
488 | if (MissingNilLoc.isInvalid()) |
489 | Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind); |
490 | else |
491 | Diag(MissingNilLoc, diag::warn_missing_sentinel) |
492 | << int(CalleeKind) |
493 | << FixItHint::CreateInsertion(MissingNilLoc, ", "+ NullValue); |
494 | Diag(D->getLocation(), diag::note_sentinel_here) |
495 | << int(CalleeKind) << Attr->getRange(); |
496 | } |
497 | |
498 | SourceRange Sema::getExprRange(Expr *E) const { |
499 | return E ? E->getSourceRange() : SourceRange(); |
500 | } |
501 | |
502 | //===----------------------------------------------------------------------===// |
503 | // Standard Promotions and Conversions |
504 | //===----------------------------------------------------------------------===// |
505 | |
506 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). |
507 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { |
508 | // Handle any placeholder expressions which made it here. |
509 | if (E->hasPlaceholderType()) { |
510 | ExprResult result = CheckPlaceholderExpr(E); |
511 | if (result.isInvalid()) return ExprError(); |
512 | E = result.get(); |
513 | } |
514 | |
515 | QualType Ty = E->getType(); |
516 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); |
517 | |
518 | if (Ty->isFunctionType()) { |
519 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts())) |
520 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) |
521 | if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc())) |
522 | return ExprError(); |
523 | |
524 | E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
525 | CK: CK_FunctionToPointerDecay).get(); |
526 | } else if (Ty->isArrayType()) { |
527 | // In C90 mode, arrays only promote to pointers if the array expression is |
528 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has |
529 | // type 'array of type' is converted to an expression that has type 'pointer |
530 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression |
531 | // that has type 'array of type' ...". The relevant change is "an lvalue" |
532 | // (C90) to "an expression" (C99). |
533 | // |
534 | // C++ 4.2p1: |
535 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of |
536 | // T" can be converted to an rvalue of type "pointer to T". |
537 | // |
538 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { |
539 | ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty), |
540 | CK: CK_ArrayToPointerDecay); |
541 | if (Res.isInvalid()) |
542 | return ExprError(); |
543 | E = Res.get(); |
544 | } |
545 | } |
546 | return E; |
547 | } |
548 | |
549 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { |
550 | // Check to see if we are dereferencing a null pointer. If so, |
551 | // and if not volatile-qualified, this is undefined behavior that the |
552 | // optimizer will delete, so warn about it. People sometimes try to use this |
553 | // to get a deterministic trap and are surprised by clang's behavior. This |
554 | // only handles the pattern "*null", which is a very syntactic check. |
555 | const auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()); |
556 | if (UO && UO->getOpcode() == UO_Deref && |
557 | UO->getSubExpr()->getType()->isPointerType()) { |
558 | const LangAS AS = |
559 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); |
560 | if ((!isTargetAddressSpace(AS) || |
561 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && |
562 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( |
563 | Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) && |
564 | !UO->getType().isVolatileQualified()) { |
565 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, |
566 | S.PDiag(diag::warn_indirection_through_null) |
567 | << UO->getSubExpr()->getSourceRange()); |
568 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, |
569 | S.PDiag(diag::note_indirection_through_null)); |
570 | } |
571 | } |
572 | } |
573 | |
574 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, |
575 | SourceLocation AssignLoc, |
576 | const Expr* RHS) { |
577 | const ObjCIvarDecl *IV = OIRE->getDecl(); |
578 | if (!IV) |
579 | return; |
580 | |
581 | DeclarationName MemberName = IV->getDeclName(); |
582 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); |
583 | if (!Member || !Member->isStr(Str: "isa")) |
584 | return; |
585 | |
586 | const Expr *Base = OIRE->getBase(); |
587 | QualType BaseType = Base->getType(); |
588 | if (OIRE->isArrow()) |
589 | BaseType = BaseType->getPointeeType(); |
590 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) |
591 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { |
592 | ObjCInterfaceDecl *ClassDeclared = nullptr; |
593 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared); |
594 | if (!ClassDeclared->getSuperClass() |
595 | && (*ClassDeclared->ivar_begin()) == IV) { |
596 | if (RHS) { |
597 | NamedDecl *ObjectSetClass = |
598 | S.LookupSingleName(S: S.TUScope, |
599 | Name: &S.Context.Idents.get(Name: "object_setClass"), |
600 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
601 | if (ObjectSetClass) { |
602 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc()); |
603 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) |
604 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), |
605 | "object_setClass(") |
606 | << FixItHint::CreateReplacement( |
607 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") |
608 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); |
609 | } |
610 | else |
611 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); |
612 | } else { |
613 | NamedDecl *ObjectGetClass = |
614 | S.LookupSingleName(S: S.TUScope, |
615 | Name: &S.Context.Idents.get(Name: "object_getClass"), |
616 | Loc: SourceLocation(), NameKind: S.LookupOrdinaryName); |
617 | if (ObjectGetClass) |
618 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) |
619 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), |
620 | "object_getClass(") |
621 | << FixItHint::CreateReplacement( |
622 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); |
623 | else |
624 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); |
625 | } |
626 | S.Diag(IV->getLocation(), diag::note_ivar_decl); |
627 | } |
628 | } |
629 | } |
630 | |
631 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { |
632 | // Handle any placeholder expressions which made it here. |
633 | if (E->hasPlaceholderType()) { |
634 | ExprResult result = CheckPlaceholderExpr(E); |
635 | if (result.isInvalid()) return ExprError(); |
636 | E = result.get(); |
637 | } |
638 | |
639 | // C++ [conv.lval]p1: |
640 | // A glvalue of a non-function, non-array type T can be |
641 | // converted to a prvalue. |
642 | if (!E->isGLValue()) return E; |
643 | |
644 | QualType T = E->getType(); |
645 | assert(!T.isNull() && "r-value conversion on typeless expression?"); |
646 | |
647 | // lvalue-to-rvalue conversion cannot be applied to types that decay to |
648 | // pointers (i.e. function or array types). |
649 | if (T->canDecayToPointerType()) |
650 | return E; |
651 | |
652 | // We don't want to throw lvalue-to-rvalue casts on top of |
653 | // expressions of certain types in C++. |
654 | if (getLangOpts().CPlusPlus) { |
655 | if (T == Context.OverloadTy || T->isRecordType() || |
656 | (T->isDependentType() && !T->isAnyPointerType() && |
657 | !T->isMemberPointerType())) |
658 | return E; |
659 | } |
660 | |
661 | // The C standard is actually really unclear on this point, and |
662 | // DR106 tells us what the result should be but not why. It's |
663 | // generally best to say that void types just doesn't undergo |
664 | // lvalue-to-rvalue at all. Note that expressions of unqualified |
665 | // 'void' type are never l-values, but qualified void can be. |
666 | if (T->isVoidType()) |
667 | return E; |
668 | |
669 | // OpenCL usually rejects direct accesses to values of 'half' type. |
670 | if (getLangOpts().OpenCL && |
671 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) && |
672 | T->isHalfType()) { |
673 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) |
674 | << 0 << T; |
675 | return ExprError(); |
676 | } |
677 | |
678 | CheckForNullPointerDereference(S&: *this, E); |
679 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) { |
680 | NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope, |
681 | Name: &Context.Idents.get(Name: "object_getClass"), |
682 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
683 | if (ObjectGetClass) |
684 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) |
685 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") |
686 | << FixItHint::CreateReplacement( |
687 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); |
688 | else |
689 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); |
690 | } |
691 | else if (const ObjCIvarRefExpr *OIRE = |
692 | dyn_cast<ObjCIvarRefExpr>(Val: E->IgnoreParenCasts())) |
693 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: nullptr); |
694 | |
695 | // C++ [conv.lval]p1: |
696 | // [...] If T is a non-class type, the type of the prvalue is the |
697 | // cv-unqualified version of T. Otherwise, the type of the |
698 | // rvalue is T. |
699 | // |
700 | // C99 6.3.2.1p2: |
701 | // If the lvalue has qualified type, the value has the unqualified |
702 | // version of the type of the lvalue; otherwise, the value has the |
703 | // type of the lvalue. |
704 | if (T.hasQualifiers()) |
705 | T = T.getUnqualifiedType(); |
706 | |
707 | // Under the MS ABI, lock down the inheritance model now. |
708 | if (T->isMemberPointerType() && |
709 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
710 | (void)isCompleteType(Loc: E->getExprLoc(), T); |
711 | |
712 | ExprResult Res = CheckLValueToRValueConversionOperand(E); |
713 | if (Res.isInvalid()) |
714 | return Res; |
715 | E = Res.get(); |
716 | |
717 | // Loading a __weak object implicitly retains the value, so we need a cleanup to |
718 | // balance that. |
719 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
720 | Cleanup.setExprNeedsCleanups(true); |
721 | |
722 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
723 | Cleanup.setExprNeedsCleanups(true); |
724 | |
725 | if (!BoundsSafetyCheckUseOfCountAttrPtr(E: Res.get())) |
726 | return ExprError(); |
727 | |
728 | // C++ [conv.lval]p3: |
729 | // If T is cv std::nullptr_t, the result is a null pointer constant. |
730 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; |
731 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue, |
732 | FPO: CurFPFeatureOverrides()); |
733 | |
734 | // C11 6.3.2.1p2: |
735 | // ... if the lvalue has atomic type, the value has the non-atomic version |
736 | // of the type of the lvalue ... |
737 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { |
738 | T = Atomic->getValueType().getUnqualifiedType(); |
739 | Res = ImplicitCastExpr::Create(Context, T, Kind: CK_AtomicToNonAtomic, Operand: Res.get(), |
740 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
741 | } |
742 | |
743 | return Res; |
744 | } |
745 | |
746 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { |
747 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); |
748 | if (Res.isInvalid()) |
749 | return ExprError(); |
750 | Res = DefaultLvalueConversion(E: Res.get()); |
751 | if (Res.isInvalid()) |
752 | return ExprError(); |
753 | return Res; |
754 | } |
755 | |
756 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { |
757 | QualType Ty = E->getType(); |
758 | ExprResult Res = E; |
759 | // Only do implicit cast for a function type, but not for a pointer |
760 | // to function type. |
761 | if (Ty->isFunctionType()) { |
762 | Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty), |
763 | CK: CK_FunctionToPointerDecay); |
764 | if (Res.isInvalid()) |
765 | return ExprError(); |
766 | } |
767 | Res = DefaultLvalueConversion(E: Res.get()); |
768 | if (Res.isInvalid()) |
769 | return ExprError(); |
770 | return Res.get(); |
771 | } |
772 | |
773 | /// UsualUnaryFPConversions - Promotes floating-point types according to the |
774 | /// current language semantics. |
775 | ExprResult Sema::UsualUnaryFPConversions(Expr *E) { |
776 | QualType Ty = E->getType(); |
777 | assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type"); |
778 | |
779 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); |
780 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && |
781 | (getLangOpts().getFPEvalMethod() != |
782 | LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || |
783 | PP.getLastFPEvalPragmaLocation().isValid())) { |
784 | switch (EvalMethod) { |
785 | default: |
786 | llvm_unreachable("Unrecognized float evaluation method"); |
787 | break; |
788 | case LangOptions::FEM_UnsetOnCommandLine: |
789 | llvm_unreachable("Float evaluation method should be set by now"); |
790 | break; |
791 | case LangOptions::FEM_Double: |
792 | if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0) |
793 | // Widen the expression to double. |
794 | return Ty->isComplexType() |
795 | ? ImpCastExprToType(E, |
796 | Type: Context.getComplexType(Context.DoubleTy), |
797 | CK: CK_FloatingComplexCast) |
798 | : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast); |
799 | break; |
800 | case LangOptions::FEM_Extended: |
801 | if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0) |
802 | // Widen the expression to long double. |
803 | return Ty->isComplexType() |
804 | ? ImpCastExprToType( |
805 | E, Type: Context.getComplexType(Context.LongDoubleTy), |
806 | CK: CK_FloatingComplexCast) |
807 | : ImpCastExprToType(E, Type: Context.LongDoubleTy, |
808 | CK: CK_FloatingCast); |
809 | break; |
810 | } |
811 | } |
812 | |
813 | // Half FP have to be promoted to float unless it is natively supported |
814 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) |
815 | return ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast); |
816 | |
817 | return E; |
818 | } |
819 | |
820 | /// UsualUnaryConversions - Performs various conversions that are common to most |
821 | /// operators (C99 6.3). The conversions of array and function types are |
822 | /// sometimes suppressed. For example, the array->pointer conversion doesn't |
823 | /// apply if the array is an argument to the sizeof or address (&) operators. |
824 | /// In these instances, this routine should *not* be called. |
825 | ExprResult Sema::UsualUnaryConversions(Expr *E) { |
826 | // First, convert to an r-value. |
827 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
828 | if (Res.isInvalid()) |
829 | return ExprError(); |
830 | |
831 | // Promote floating-point types. |
832 | Res = UsualUnaryFPConversions(E: Res.get()); |
833 | if (Res.isInvalid()) |
834 | return ExprError(); |
835 | E = Res.get(); |
836 | |
837 | QualType Ty = E->getType(); |
838 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); |
839 | |
840 | // Try to perform integral promotions if the object has a theoretically |
841 | // promotable type. |
842 | if (Ty->isIntegralOrUnscopedEnumerationType()) { |
843 | // C99 6.3.1.1p2: |
844 | // |
845 | // The following may be used in an expression wherever an int or |
846 | // unsigned int may be used: |
847 | // - an object or expression with an integer type whose integer |
848 | // conversion rank is less than or equal to the rank of int |
849 | // and unsigned int. |
850 | // - A bit-field of type _Bool, int, signed int, or unsigned int. |
851 | // |
852 | // If an int can represent all values of the original type, the |
853 | // value is converted to an int; otherwise, it is converted to an |
854 | // unsigned int. These are called the integer promotions. All |
855 | // other types are unchanged by the integer promotions. |
856 | |
857 | QualType PTy = Context.isPromotableBitField(E); |
858 | if (!PTy.isNull()) { |
859 | E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get(); |
860 | return E; |
861 | } |
862 | if (Context.isPromotableIntegerType(T: Ty)) { |
863 | QualType PT = Context.getPromotedIntegerType(PromotableType: Ty); |
864 | E = ImpCastExprToType(E, Type: PT, CK: CK_IntegralCast).get(); |
865 | return E; |
866 | } |
867 | } |
868 | return E; |
869 | } |
870 | |
871 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
872 | /// do not have a prototype. Arguments that have type float or __fp16 |
873 | /// are promoted to double. All other argument types are converted by |
874 | /// UsualUnaryConversions(). |
875 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { |
876 | QualType Ty = E->getType(); |
877 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); |
878 | |
879 | ExprResult Res = UsualUnaryConversions(E); |
880 | if (Res.isInvalid()) |
881 | return ExprError(); |
882 | E = Res.get(); |
883 | |
884 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) |
885 | // promote to double. |
886 | // Note that default argument promotion applies only to float (and |
887 | // half/fp16); it does not apply to _Float16. |
888 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
889 | if (BTy && (BTy->getKind() == BuiltinType::Half || |
890 | BTy->getKind() == BuiltinType::Float)) { |
891 | if (getLangOpts().OpenCL && |
892 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: getLangOpts())) { |
893 | if (BTy->getKind() == BuiltinType::Half) { |
894 | E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
895 | } |
896 | } else { |
897 | E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get(); |
898 | } |
899 | } |
900 | if (BTy && |
901 | getLangOpts().getExtendIntArgs() == |
902 | LangOptions::ExtendArgsKind::ExtendTo64 && |
903 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && |
904 | Context.getTypeSizeInChars(BTy) < |
905 | Context.getTypeSizeInChars(Context.LongLongTy)) { |
906 | E = (Ty->isUnsignedIntegerType()) |
907 | ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast) |
908 | .get() |
909 | : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get(); |
910 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && |
911 | "Unexpected typesize for LongLongTy"); |
912 | } |
913 | |
914 | // C++ performs lvalue-to-rvalue conversion as a default argument |
915 | // promotion, even on class types, but note: |
916 | // C++11 [conv.lval]p2: |
917 | // When an lvalue-to-rvalue conversion occurs in an unevaluated |
918 | // operand or a subexpression thereof the value contained in the |
919 | // referenced object is not accessed. Otherwise, if the glvalue |
920 | // has a class type, the conversion copy-initializes a temporary |
921 | // of type T from the glvalue and the result of the conversion |
922 | // is a prvalue for the temporary. |
923 | // FIXME: add some way to gate this entire thing for correctness in |
924 | // potentially potentially evaluated contexts. |
925 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { |
926 | ExprResult Temp = PerformCopyInitialization( |
927 | Entity: InitializedEntity::InitializeTemporary(Type: E->getType()), |
928 | EqualLoc: E->getExprLoc(), Init: E); |
929 | if (Temp.isInvalid()) |
930 | return ExprError(); |
931 | E = Temp.get(); |
932 | } |
933 | |
934 | // C++ [expr.call]p7, per CWG722: |
935 | // An argument that has (possibly cv-qualified) type std::nullptr_t is |
936 | // converted to void* ([conv.ptr]). |
937 | // (This does not apply to C23 nullptr) |
938 | if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType()) |
939 | E = ImpCastExprToType(E, Type: Context.VoidPtrTy, CK: CK_NullToPointer).get(); |
940 | |
941 | return E; |
942 | } |
943 | |
944 | VarArgKind Sema::isValidVarArgType(const QualType &Ty) { |
945 | if (Ty->isIncompleteType()) { |
946 | // C++11 [expr.call]p7: |
947 | // After these conversions, if the argument does not have arithmetic, |
948 | // enumeration, pointer, pointer to member, or class type, the program |
949 | // is ill-formed. |
950 | // |
951 | // Since we've already performed null pointer conversion, array-to-pointer |
952 | // decay and function-to-pointer decay, the only such type in C++ is cv |
953 | // void. This also handles initializer lists as variadic arguments. |
954 | if (Ty->isVoidType()) |
955 | return VarArgKind::Invalid; |
956 | |
957 | if (Ty->isObjCObjectType()) |
958 | return VarArgKind::Invalid; |
959 | return VarArgKind::Valid; |
960 | } |
961 | |
962 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
963 | return VarArgKind::Invalid; |
964 | |
965 | if (Context.getTargetInfo().getTriple().isWasm() && |
966 | Ty.isWebAssemblyReferenceType()) { |
967 | return VarArgKind::Invalid; |
968 | } |
969 | |
970 | if (Ty.isCXX98PODType(Context)) |
971 | return VarArgKind::Valid; |
972 | |
973 | // C++11 [expr.call]p7: |
974 | // Passing a potentially-evaluated argument of class type (Clause 9) |
975 | // having a non-trivial copy constructor, a non-trivial move constructor, |
976 | // or a non-trivial destructor, with no corresponding parameter, |
977 | // is conditionally-supported with implementation-defined semantics. |
978 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) |
979 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) |
980 | if (!Record->hasNonTrivialCopyConstructor() && |
981 | !Record->hasNonTrivialMoveConstructor() && |
982 | !Record->hasNonTrivialDestructor()) |
983 | return VarArgKind::ValidInCXX11; |
984 | |
985 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) |
986 | return VarArgKind::Valid; |
987 | |
988 | if (Ty->isObjCObjectType()) |
989 | return VarArgKind::Invalid; |
990 | |
991 | if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>()) |
992 | return VarArgKind::Valid; |
993 | |
994 | if (getLangOpts().MSVCCompat) |
995 | return VarArgKind::MSVCUndefined; |
996 | |
997 | if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>()) |
998 | return VarArgKind::Valid; |
999 | |
1000 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're |
1001 | // permitted to reject them. We should consider doing so. |
1002 | return VarArgKind::Undefined; |
1003 | } |
1004 | |
1005 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { |
1006 | // Don't allow one to pass an Objective-C interface to a vararg. |
1007 | const QualType &Ty = E->getType(); |
1008 | VarArgKind VAK = isValidVarArgType(Ty); |
1009 | |
1010 | // Complain about passing non-POD types through varargs. |
1011 | switch (VAK) { |
1012 | case VarArgKind::ValidInCXX11: |
1013 | DiagRuntimeBehavior( |
1014 | E->getBeginLoc(), nullptr, |
1015 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); |
1016 | [[fallthrough]]; |
1017 | case VarArgKind::Valid: |
1018 | if (Ty->isRecordType()) { |
1019 | // This is unlikely to be what the user intended. If the class has a |
1020 | // 'c_str' member function, the user probably meant to call that. |
1021 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
1022 | PDiag(diag::warn_pass_class_arg_to_vararg) |
1023 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); |
1024 | } |
1025 | break; |
1026 | |
1027 | case VarArgKind::Undefined: |
1028 | case VarArgKind::MSVCUndefined: |
1029 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
1030 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) |
1031 | << getLangOpts().CPlusPlus11 << Ty << CT); |
1032 | break; |
1033 | |
1034 | case VarArgKind::Invalid: |
1035 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
1036 | Diag(E->getBeginLoc(), |
1037 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) |
1038 | << Ty << CT; |
1039 | else if (Ty->isObjCObjectType()) |
1040 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
1041 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) |
1042 | << Ty << CT); |
1043 | else |
1044 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) |
1045 | << isa<InitListExpr>(E) << Ty << CT; |
1046 | break; |
1047 | } |
1048 | } |
1049 | |
1050 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
1051 | FunctionDecl *FDecl) { |
1052 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { |
1053 | // Strip the unbridged-cast placeholder expression off, if applicable. |
1054 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && |
1055 | (CT == VariadicCallType::Method || |
1056 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { |
1057 | E = ObjC().stripARCUnbridgedCast(e: E); |
1058 | |
1059 | // Otherwise, do normal placeholder checking. |
1060 | } else { |
1061 | ExprResult ExprRes = CheckPlaceholderExpr(E); |
1062 | if (ExprRes.isInvalid()) |
1063 | return ExprError(); |
1064 | E = ExprRes.get(); |
1065 | } |
1066 | } |
1067 | |
1068 | ExprResult ExprRes = DefaultArgumentPromotion(E); |
1069 | if (ExprRes.isInvalid()) |
1070 | return ExprError(); |
1071 | |
1072 | // Copy blocks to the heap. |
1073 | if (ExprRes.get()->getType()->isBlockPointerType()) |
1074 | maybeExtendBlockObject(E&: ExprRes); |
1075 | |
1076 | E = ExprRes.get(); |
1077 | |
1078 | // Diagnostics regarding non-POD argument types are |
1079 | // emitted along with format string checking in Sema::CheckFunctionCall(). |
1080 | if (isValidVarArgType(Ty: E->getType()) == VarArgKind::Undefined) { |
1081 | // Turn this into a trap. |
1082 | CXXScopeSpec SS; |
1083 | SourceLocation TemplateKWLoc; |
1084 | UnqualifiedId Name; |
1085 | Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"), |
1086 | IdLoc: E->getBeginLoc()); |
1087 | ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name, |
1088 | /*HasTrailingLParen=*/true, |
1089 | /*IsAddressOfOperand=*/false); |
1090 | if (TrapFn.isInvalid()) |
1091 | return ExprError(); |
1092 | |
1093 | ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(), ArgExprs: {}, |
1094 | RParenLoc: E->getEndLoc()); |
1095 | if (Call.isInvalid()) |
1096 | return ExprError(); |
1097 | |
1098 | ExprResult Comma = |
1099 | ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E); |
1100 | if (Comma.isInvalid()) |
1101 | return ExprError(); |
1102 | return Comma.get(); |
1103 | } |
1104 | |
1105 | if (!getLangOpts().CPlusPlus && |
1106 | RequireCompleteType(E->getExprLoc(), E->getType(), |
1107 | diag::err_call_incomplete_argument)) |
1108 | return ExprError(); |
1109 | |
1110 | return E; |
1111 | } |
1112 | |
1113 | /// Convert complex integers to complex floats and real integers to |
1114 | /// real floats as required for complex arithmetic. Helper function of |
1115 | /// UsualArithmeticConversions() |
1116 | /// |
1117 | /// \return false if the integer expression is an integer type and is |
1118 | /// successfully converted to the (complex) float type. |
1119 | static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, |
1120 | ExprResult &ComplexExpr, |
1121 | QualType IntTy, |
1122 | QualType ComplexTy, |
1123 | bool SkipCast) { |
1124 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; |
1125 | if (SkipCast) return false; |
1126 | if (IntTy->isIntegerType()) { |
1127 | QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); |
1128 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating); |
1129 | } else { |
1130 | assert(IntTy->isComplexIntegerType()); |
1131 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy, |
1132 | CK: CK_IntegralComplexToFloatingComplex); |
1133 | } |
1134 | return false; |
1135 | } |
1136 | |
1137 | // This handles complex/complex, complex/float, or float/complex. |
1138 | // When both operands are complex, the shorter operand is converted to the |
1139 | // type of the longer, and that is the type of the result. This corresponds |
1140 | // to what is done when combining two real floating-point operands. |
1141 | // The fun begins when size promotion occur across type domains. |
1142 | // From H&S 6.3.4: When one operand is complex and the other is a real |
1143 | // floating-point type, the less precise type is converted, within it's |
1144 | // real or complex domain, to the precision of the other type. For example, |
1145 | // when combining a "long double" with a "double _Complex", the |
1146 | // "double _Complex" is promoted to "long double _Complex". |
1147 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, |
1148 | QualType ShorterType, |
1149 | QualType LongerType, |
1150 | bool PromotePrecision) { |
1151 | bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType()); |
1152 | QualType Result = |
1153 | LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType); |
1154 | |
1155 | if (PromotePrecision) { |
1156 | if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) { |
1157 | Shorter = |
1158 | S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast); |
1159 | } else { |
1160 | if (LongerIsComplex) |
1161 | LongerType = LongerType->castAs<ComplexType>()->getElementType(); |
1162 | Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast); |
1163 | } |
1164 | } |
1165 | return Result; |
1166 | } |
1167 | |
1168 | /// Handle arithmetic conversion with complex types. Helper function of |
1169 | /// UsualArithmeticConversions() |
1170 | static QualType handleComplexConversion(Sema &S, ExprResult &LHS, |
1171 | ExprResult &RHS, QualType LHSType, |
1172 | QualType RHSType, bool IsCompAssign) { |
1173 | // Handle (complex) integer types. |
1174 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType, |
1175 | /*SkipCast=*/false)) |
1176 | return LHSType; |
1177 | if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: RHSType, |
1178 | /*SkipCast=*/IsCompAssign)) |
1179 | return RHSType; |
1180 | |
1181 | // Compute the rank of the two types, regardless of whether they are complex. |
1182 | int Order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
1183 | if (Order < 0) |
1184 | // Promote the precision of the LHS if not an assignment. |
1185 | return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType, |
1186 | /*PromotePrecision=*/!IsCompAssign); |
1187 | // Promote the precision of the RHS unless it is already the same as the LHS. |
1188 | return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType, |
1189 | /*PromotePrecision=*/Order > 0); |
1190 | } |
1191 | |
1192 | /// Handle arithmetic conversion from integer to float. Helper function |
1193 | /// of UsualArithmeticConversions() |
1194 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, |
1195 | ExprResult &IntExpr, |
1196 | QualType FloatTy, QualType IntTy, |
1197 | bool ConvertFloat, bool ConvertInt) { |
1198 | if (IntTy->isIntegerType()) { |
1199 | if (ConvertInt) |
1200 | // Convert intExpr to the lhs floating point type. |
1201 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: FloatTy, |
1202 | CK: CK_IntegralToFloating); |
1203 | return FloatTy; |
1204 | } |
1205 | |
1206 | // Convert both sides to the appropriate complex float. |
1207 | assert(IntTy->isComplexIntegerType()); |
1208 | QualType result = S.Context.getComplexType(T: FloatTy); |
1209 | |
1210 | // _Complex int -> _Complex float |
1211 | if (ConvertInt) |
1212 | IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result, |
1213 | CK: CK_IntegralComplexToFloatingComplex); |
1214 | |
1215 | // float -> _Complex float |
1216 | if (ConvertFloat) |
1217 | FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result, |
1218 | CK: CK_FloatingRealToComplex); |
1219 | |
1220 | return result; |
1221 | } |
1222 | |
1223 | /// Handle arithmethic conversion with floating point types. Helper |
1224 | /// function of UsualArithmeticConversions() |
1225 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, |
1226 | ExprResult &RHS, QualType LHSType, |
1227 | QualType RHSType, bool IsCompAssign) { |
1228 | bool LHSFloat = LHSType->isRealFloatingType(); |
1229 | bool RHSFloat = RHSType->isRealFloatingType(); |
1230 | |
1231 | // N1169 4.1.4: If one of the operands has a floating type and the other |
1232 | // operand has a fixed-point type, the fixed-point operand |
1233 | // is converted to the floating type [...] |
1234 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { |
1235 | if (LHSFloat) |
1236 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating); |
1237 | else if (!IsCompAssign) |
1238 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FixedPointToFloating); |
1239 | return LHSFloat ? LHSType : RHSType; |
1240 | } |
1241 | |
1242 | // If we have two real floating types, convert the smaller operand |
1243 | // to the bigger result. |
1244 | if (LHSFloat && RHSFloat) { |
1245 | int order = S.Context.getFloatingTypeOrder(LHS: LHSType, RHS: RHSType); |
1246 | if (order > 0) { |
1247 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast); |
1248 | return LHSType; |
1249 | } |
1250 | |
1251 | assert(order < 0 && "illegal float comparison"); |
1252 | if (!IsCompAssign) |
1253 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_FloatingCast); |
1254 | return RHSType; |
1255 | } |
1256 | |
1257 | if (LHSFloat) { |
1258 | // Half FP has to be promoted to float unless it is natively supported |
1259 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) |
1260 | LHSType = S.Context.FloatTy; |
1261 | |
1262 | return handleIntToFloatConversion(S, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType, |
1263 | /*ConvertFloat=*/!IsCompAssign, |
1264 | /*ConvertInt=*/ true); |
1265 | } |
1266 | assert(RHSFloat); |
1267 | return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: LHSType, |
1268 | /*ConvertFloat=*/ true, |
1269 | /*ConvertInt=*/!IsCompAssign); |
1270 | } |
1271 | |
1272 | /// Diagnose attempts to convert between __float128, __ibm128 and |
1273 | /// long double if there is no support for such conversion. |
1274 | /// Helper function of UsualArithmeticConversions(). |
1275 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, |
1276 | QualType RHSType) { |
1277 | // No issue if either is not a floating point type. |
1278 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) |
1279 | return false; |
1280 | |
1281 | // No issue if both have the same 128-bit float semantics. |
1282 | auto *LHSComplex = LHSType->getAs<ComplexType>(); |
1283 | auto *RHSComplex = RHSType->getAs<ComplexType>(); |
1284 | |
1285 | QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; |
1286 | QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; |
1287 | |
1288 | const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(T: LHSElem); |
1289 | const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: RHSElem); |
1290 | |
1291 | if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || |
1292 | &RHSSem != &llvm::APFloat::IEEEquad()) && |
1293 | (&LHSSem != &llvm::APFloat::IEEEquad() || |
1294 | &RHSSem != &llvm::APFloat::PPCDoubleDouble())) |
1295 | return false; |
1296 | |
1297 | return true; |
1298 | } |
1299 | |
1300 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); |
1301 | |
1302 | namespace { |
1303 | /// These helper callbacks are placed in an anonymous namespace to |
1304 | /// permit their use as function template parameters. |
1305 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { |
1306 | return S.ImpCastExprToType(E: op, Type: toType, CK: CK_IntegralCast); |
1307 | } |
1308 | |
1309 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { |
1310 | return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType), |
1311 | CK: CK_IntegralComplexCast); |
1312 | } |
1313 | } |
1314 | |
1315 | /// Handle integer arithmetic conversions. Helper function of |
1316 | /// UsualArithmeticConversions() |
1317 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> |
1318 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, |
1319 | ExprResult &RHS, QualType LHSType, |
1320 | QualType RHSType, bool IsCompAssign) { |
1321 | // The rules for this case are in C99 6.3.1.8 |
1322 | int order = S.Context.getIntegerTypeOrder(LHS: LHSType, RHS: RHSType); |
1323 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); |
1324 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); |
1325 | if (LHSSigned == RHSSigned) { |
1326 | // Same signedness; use the higher-ranked type |
1327 | if (order >= 0) { |
1328 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1329 | return LHSType; |
1330 | } else if (!IsCompAssign) |
1331 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1332 | return RHSType; |
1333 | } else if (order != (LHSSigned ? 1 : -1)) { |
1334 | // The unsigned type has greater than or equal rank to the |
1335 | // signed type, so use the unsigned type |
1336 | if (RHSSigned) { |
1337 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1338 | return LHSType; |
1339 | } else if (!IsCompAssign) |
1340 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1341 | return RHSType; |
1342 | } else if (S.Context.getIntWidth(T: LHSType) != S.Context.getIntWidth(T: RHSType)) { |
1343 | // The two types are different widths; if we are here, that |
1344 | // means the signed type is larger than the unsigned type, so |
1345 | // use the signed type. |
1346 | if (LHSSigned) { |
1347 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
1348 | return LHSType; |
1349 | } else if (!IsCompAssign) |
1350 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
1351 | return RHSType; |
1352 | } else { |
1353 | // The signed type is higher-ranked than the unsigned type, |
1354 | // but isn't actually any bigger (like unsigned int and long |
1355 | // on most 32-bit systems). Use the unsigned type corresponding |
1356 | // to the signed type. |
1357 | QualType result = |
1358 | S.Context.getCorrespondingUnsignedType(T: LHSSigned ? LHSType : RHSType); |
1359 | RHS = (*doRHSCast)(S, RHS.get(), result); |
1360 | if (!IsCompAssign) |
1361 | LHS = (*doLHSCast)(S, LHS.get(), result); |
1362 | return result; |
1363 | } |
1364 | } |
1365 | |
1366 | /// Handle conversions with GCC complex int extension. Helper function |
1367 | /// of UsualArithmeticConversions() |
1368 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, |
1369 | ExprResult &RHS, QualType LHSType, |
1370 | QualType RHSType, |
1371 | bool IsCompAssign) { |
1372 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); |
1373 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); |
1374 | |
1375 | if (LHSComplexInt && RHSComplexInt) { |
1376 | QualType LHSEltType = LHSComplexInt->getElementType(); |
1377 | QualType RHSEltType = RHSComplexInt->getElementType(); |
1378 | QualType ScalarType = |
1379 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> |
1380 | (S, LHS, RHS, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign); |
1381 | |
1382 | return S.Context.getComplexType(T: ScalarType); |
1383 | } |
1384 | |
1385 | if (LHSComplexInt) { |
1386 | QualType LHSEltType = LHSComplexInt->getElementType(); |
1387 | QualType ScalarType = |
1388 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> |
1389 | (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign); |
1390 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
1391 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType, |
1392 | CK: CK_IntegralRealToComplex); |
1393 | |
1394 | return ComplexType; |
1395 | } |
1396 | |
1397 | assert(RHSComplexInt); |
1398 | |
1399 | QualType RHSEltType = RHSComplexInt->getElementType(); |
1400 | QualType ScalarType = |
1401 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> |
1402 | (S, LHS, RHS, LHSType, RHSType: RHSEltType, IsCompAssign); |
1403 | QualType ComplexType = S.Context.getComplexType(T: ScalarType); |
1404 | |
1405 | if (!IsCompAssign) |
1406 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType, |
1407 | CK: CK_IntegralRealToComplex); |
1408 | return ComplexType; |
1409 | } |
1410 | |
1411 | /// Return the rank of a given fixed point or integer type. The value itself |
1412 | /// doesn't matter, but the values must be increasing with proper increasing |
1413 | /// rank as described in N1169 4.1.1. |
1414 | static unsigned GetFixedPointRank(QualType Ty) { |
1415 | const auto *BTy = Ty->getAs<BuiltinType>(); |
1416 | assert(BTy && "Expected a builtin type."); |
1417 | |
1418 | switch (BTy->getKind()) { |
1419 | case BuiltinType::ShortFract: |
1420 | case BuiltinType::UShortFract: |
1421 | case BuiltinType::SatShortFract: |
1422 | case BuiltinType::SatUShortFract: |
1423 | return 1; |
1424 | case BuiltinType::Fract: |
1425 | case BuiltinType::UFract: |
1426 | case BuiltinType::SatFract: |
1427 | case BuiltinType::SatUFract: |
1428 | return 2; |
1429 | case BuiltinType::LongFract: |
1430 | case BuiltinType::ULongFract: |
1431 | case BuiltinType::SatLongFract: |
1432 | case BuiltinType::SatULongFract: |
1433 | return 3; |
1434 | case BuiltinType::ShortAccum: |
1435 | case BuiltinType::UShortAccum: |
1436 | case BuiltinType::SatShortAccum: |
1437 | case BuiltinType::SatUShortAccum: |
1438 | return 4; |
1439 | case BuiltinType::Accum: |
1440 | case BuiltinType::UAccum: |
1441 | case BuiltinType::SatAccum: |
1442 | case BuiltinType::SatUAccum: |
1443 | return 5; |
1444 | case BuiltinType::LongAccum: |
1445 | case BuiltinType::ULongAccum: |
1446 | case BuiltinType::SatLongAccum: |
1447 | case BuiltinType::SatULongAccum: |
1448 | return 6; |
1449 | default: |
1450 | if (BTy->isInteger()) |
1451 | return 0; |
1452 | llvm_unreachable("Unexpected fixed point or integer type"); |
1453 | } |
1454 | } |
1455 | |
1456 | /// handleFixedPointConversion - Fixed point operations between fixed |
1457 | /// point types and integers or other fixed point types do not fall under |
1458 | /// usual arithmetic conversion since these conversions could result in loss |
1459 | /// of precsision (N1169 4.1.4). These operations should be calculated with |
1460 | /// the full precision of their result type (N1169 4.1.6.2.1). |
1461 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, |
1462 | QualType RHSTy) { |
1463 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && |
1464 | "Expected at least one of the operands to be a fixed point type"); |
1465 | assert((LHSTy->isFixedPointOrIntegerType() || |
1466 | RHSTy->isFixedPointOrIntegerType()) && |
1467 | "Special fixed point arithmetic operation conversions are only " |
1468 | "applied to ints or other fixed point types"); |
1469 | |
1470 | // If one operand has signed fixed-point type and the other operand has |
1471 | // unsigned fixed-point type, then the unsigned fixed-point operand is |
1472 | // converted to its corresponding signed fixed-point type and the resulting |
1473 | // type is the type of the converted operand. |
1474 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) |
1475 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy); |
1476 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) |
1477 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy); |
1478 | |
1479 | // The result type is the type with the highest rank, whereby a fixed-point |
1480 | // conversion rank is always greater than an integer conversion rank; if the |
1481 | // type of either of the operands is a saturating fixedpoint type, the result |
1482 | // type shall be the saturating fixed-point type corresponding to the type |
1483 | // with the highest rank; the resulting value is converted (taking into |
1484 | // account rounding and overflow) to the precision of the resulting type. |
1485 | // Same ranks between signed and unsigned types are resolved earlier, so both |
1486 | // types are either signed or both unsigned at this point. |
1487 | unsigned LHSTyRank = GetFixedPointRank(Ty: LHSTy); |
1488 | unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy); |
1489 | |
1490 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; |
1491 | |
1492 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) |
1493 | ResultTy = S.Context.getCorrespondingSaturatedType(Ty: ResultTy); |
1494 | |
1495 | return ResultTy; |
1496 | } |
1497 | |
1498 | /// Check that the usual arithmetic conversions can be performed on this pair of |
1499 | /// expressions that might be of enumeration type. |
1500 | void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, |
1501 | SourceLocation Loc, |
1502 | ArithConvKind ACK) { |
1503 | // C++2a [expr.arith.conv]p1: |
1504 | // If one operand is of enumeration type and the other operand is of a |
1505 | // different enumeration type or a floating-point type, this behavior is |
1506 | // deprecated ([depr.arith.conv.enum]). |
1507 | // |
1508 | // Warn on this in all language modes. Produce a deprecation warning in C++20. |
1509 | // Eventually we will presumably reject these cases (in C++23 onwards?). |
1510 | QualType L = LHS->getEnumCoercedType(Ctx: Context), |
1511 | R = RHS->getEnumCoercedType(Ctx: Context); |
1512 | bool LEnum = L->isUnscopedEnumerationType(), |
1513 | REnum = R->isUnscopedEnumerationType(); |
1514 | bool IsCompAssign = ACK == ArithConvKind::CompAssign; |
1515 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || |
1516 | (REnum && L->isFloatingType())) { |
1517 | Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26 |
1518 | : getLangOpts().CPlusPlus20 |
1519 | ? diag::warn_arith_conv_enum_float_cxx20 |
1520 | : diag::warn_arith_conv_enum_float) |
1521 | << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum |
1522 | << L << R; |
1523 | } else if (!IsCompAssign && LEnum && REnum && |
1524 | !Context.hasSameUnqualifiedType(T1: L, T2: R)) { |
1525 | unsigned DiagID; |
1526 | // In C++ 26, usual arithmetic conversions between 2 different enum types |
1527 | // are ill-formed. |
1528 | if (getLangOpts().CPlusPlus26) |
1529 | DiagID = diag::warn_conv_mixed_enum_types_cxx26; |
1530 | else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || |
1531 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { |
1532 | // If either enumeration type is unnamed, it's less likely that the |
1533 | // user cares about this, but this situation is still deprecated in |
1534 | // C++2a. Use a different warning group. |
1535 | DiagID = getLangOpts().CPlusPlus20 |
1536 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 |
1537 | : diag::warn_arith_conv_mixed_anon_enum_types; |
1538 | } else if (ACK == ArithConvKind::Conditional) { |
1539 | // Conditional expressions are separated out because they have |
1540 | // historically had a different warning flag. |
1541 | DiagID = getLangOpts().CPlusPlus20 |
1542 | ? diag::warn_conditional_mixed_enum_types_cxx20 |
1543 | : diag::warn_conditional_mixed_enum_types; |
1544 | } else if (ACK == ArithConvKind::Comparison) { |
1545 | // Comparison expressions are separated out because they have |
1546 | // historically had a different warning flag. |
1547 | DiagID = getLangOpts().CPlusPlus20 |
1548 | ? diag::warn_comparison_mixed_enum_types_cxx20 |
1549 | : diag::warn_comparison_mixed_enum_types; |
1550 | } else { |
1551 | DiagID = getLangOpts().CPlusPlus20 |
1552 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 |
1553 | : diag::warn_arith_conv_mixed_enum_types; |
1554 | } |
1555 | Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() |
1556 | << (int)ACK << L << R; |
1557 | } |
1558 | } |
1559 | |
1560 | static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, |
1561 | Expr *RHS, SourceLocation Loc, |
1562 | ArithConvKind ACK) { |
1563 | QualType LHSType = LHS->getType().getUnqualifiedType(); |
1564 | QualType RHSType = RHS->getType().getUnqualifiedType(); |
1565 | |
1566 | if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() || |
1567 | !RHSType->isUnicodeCharacterType()) |
1568 | return; |
1569 | |
1570 | if (ACK == ArithConvKind::Comparison) { |
1571 | if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType)) |
1572 | return; |
1573 | |
1574 | auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) { |
1575 | if (T->isChar8Type()) |
1576 | return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue()); |
1577 | if (T->isChar16Type()) |
1578 | return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue()); |
1579 | assert(T->isChar32Type()); |
1580 | return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue()); |
1581 | }; |
1582 | |
1583 | Expr::EvalResult LHSRes, RHSRes; |
1584 | bool LHSSuccess = LHS->EvaluateAsInt(Result&: LHSRes, Ctx: SemaRef.getASTContext(), |
1585 | AllowSideEffects: Expr::SE_AllowSideEffects, |
1586 | InConstantContext: SemaRef.isConstantEvaluatedContext()); |
1587 | bool RHSuccess = RHS->EvaluateAsInt(Result&: RHSRes, Ctx: SemaRef.getASTContext(), |
1588 | AllowSideEffects: Expr::SE_AllowSideEffects, |
1589 | InConstantContext: SemaRef.isConstantEvaluatedContext()); |
1590 | |
1591 | // Don't warn if the one known value is a representable |
1592 | // in the type of both expressions. |
1593 | if (LHSSuccess != RHSuccess) { |
1594 | Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes; |
1595 | if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) && |
1596 | IsSingleCodeUnitCP(RHSType, Res.Val.getInt())) |
1597 | return; |
1598 | } |
1599 | |
1600 | if (!LHSSuccess || !RHSuccess) { |
1601 | SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types) |
1602 | << LHS->getSourceRange() << RHS->getSourceRange() << LHSType |
1603 | << RHSType; |
1604 | return; |
1605 | } |
1606 | |
1607 | llvm::APSInt LHSValue(32); |
1608 | LHSValue = LHSRes.Val.getInt(); |
1609 | llvm::APSInt RHSValue(32); |
1610 | RHSValue = RHSRes.Val.getInt(); |
1611 | |
1612 | bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue); |
1613 | bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue); |
1614 | if (LHSSafe && RHSSafe) |
1615 | return; |
1616 | |
1617 | SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant) |
1618 | << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType |
1619 | << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType) |
1620 | << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType); |
1621 | return; |
1622 | } |
1623 | |
1624 | if (SemaRef.getASTContext().hasSameType(T1: LHSType, T2: RHSType)) |
1625 | return; |
1626 | |
1627 | SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types) |
1628 | << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType |
1629 | << RHSType; |
1630 | } |
1631 | |
1632 | /// UsualArithmeticConversions - Performs various conversions that are common to |
1633 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
1634 | /// routine returns the first non-arithmetic type found. The client is |
1635 | /// responsible for emitting appropriate error diagnostics. |
1636 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
1637 | SourceLocation Loc, |
1638 | ArithConvKind ACK) { |
1639 | |
1640 | checkEnumArithmeticConversions(LHS: LHS.get(), RHS: RHS.get(), Loc, ACK); |
1641 | |
1642 | CheckUnicodeArithmeticConversions(SemaRef&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK); |
1643 | |
1644 | if (ACK != ArithConvKind::CompAssign) { |
1645 | LHS = UsualUnaryConversions(E: LHS.get()); |
1646 | if (LHS.isInvalid()) |
1647 | return QualType(); |
1648 | } |
1649 | |
1650 | RHS = UsualUnaryConversions(E: RHS.get()); |
1651 | if (RHS.isInvalid()) |
1652 | return QualType(); |
1653 | |
1654 | // For conversion purposes, we ignore any qualifiers. |
1655 | // For example, "const float" and "float" are equivalent. |
1656 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
1657 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
1658 | |
1659 | // For conversion purposes, we ignore any atomic qualifier on the LHS. |
1660 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) |
1661 | LHSType = AtomicLHS->getValueType(); |
1662 | |
1663 | // If both types are identical, no conversion is needed. |
1664 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
1665 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
1666 | |
1667 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. |
1668 | // The caller can deal with this (e.g. pointer + int). |
1669 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) |
1670 | return QualType(); |
1671 | |
1672 | // Apply unary and bitfield promotions to the LHS's type. |
1673 | QualType LHSUnpromotedType = LHSType; |
1674 | if (Context.isPromotableIntegerType(T: LHSType)) |
1675 | LHSType = Context.getPromotedIntegerType(PromotableType: LHSType); |
1676 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get()); |
1677 | if (!LHSBitfieldPromoteTy.isNull()) |
1678 | LHSType = LHSBitfieldPromoteTy; |
1679 | if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign) |
1680 | LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast); |
1681 | |
1682 | // If both types are identical, no conversion is needed. |
1683 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
1684 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
1685 | |
1686 | // At this point, we have two different arithmetic types. |
1687 | |
1688 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
1689 | // where such conversions currently can't be handled. |
1690 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
1691 | return QualType(); |
1692 | |
1693 | // Handle complex types first (C99 6.3.1.8p1). |
1694 | if (LHSType->isComplexType() || RHSType->isComplexType()) |
1695 | return handleComplexConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1696 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
1697 | |
1698 | // Now handle "real" floating types (i.e. float, double, long double). |
1699 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
1700 | return handleFloatConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1701 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
1702 | |
1703 | // Handle GCC complex int extension. |
1704 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) |
1705 | return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType, |
1706 | IsCompAssign: ACK == ArithConvKind::CompAssign); |
1707 | |
1708 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) |
1709 | return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType); |
1710 | |
1711 | // Finally, we have two differing integer types. |
1712 | return handleIntegerConversion<doIntegralCast, doIntegralCast>( |
1713 | S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ArithConvKind::CompAssign); |
1714 | } |
1715 | |
1716 | //===----------------------------------------------------------------------===// |
1717 | // Semantic Analysis for various Expression Types |
1718 | //===----------------------------------------------------------------------===// |
1719 | |
1720 | |
1721 | ExprResult Sema::ActOnGenericSelectionExpr( |
1722 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
1723 | bool PredicateIsExpr, void *ControllingExprOrType, |
1724 | ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) { |
1725 | unsigned NumAssocs = ArgTypes.size(); |
1726 | assert(NumAssocs == ArgExprs.size()); |
1727 | |
1728 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; |
1729 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1730 | if (ArgTypes[i]) |
1731 | (void) GetTypeFromParser(Ty: ArgTypes[i], TInfo: &Types[i]); |
1732 | else |
1733 | Types[i] = nullptr; |
1734 | } |
1735 | |
1736 | // If we have a controlling type, we need to convert it from a parsed type |
1737 | // into a semantic type and then pass that along. |
1738 | if (!PredicateIsExpr) { |
1739 | TypeSourceInfo *ControllingType; |
1740 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType), |
1741 | TInfo: &ControllingType); |
1742 | assert(ControllingType && "couldn't get the type out of the parser"); |
1743 | ControllingExprOrType = ControllingType; |
1744 | } |
1745 | |
1746 | ExprResult ER = CreateGenericSelectionExpr( |
1747 | KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType, |
1748 | Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs); |
1749 | delete [] Types; |
1750 | return ER; |
1751 | } |
1752 | |
1753 | ExprResult Sema::CreateGenericSelectionExpr( |
1754 | SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, |
1755 | bool PredicateIsExpr, void *ControllingExprOrType, |
1756 | ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) { |
1757 | unsigned NumAssocs = Types.size(); |
1758 | assert(NumAssocs == Exprs.size()); |
1759 | assert(ControllingExprOrType && |
1760 | "Must have either a controlling expression or a controlling type"); |
1761 | |
1762 | Expr *ControllingExpr = nullptr; |
1763 | TypeSourceInfo *ControllingType = nullptr; |
1764 | if (PredicateIsExpr) { |
1765 | // Decay and strip qualifiers for the controlling expression type, and |
1766 | // handle placeholder type replacement. See committee discussion from WG14 |
1767 | // DR423. |
1768 | EnterExpressionEvaluationContext Unevaluated( |
1769 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
1770 | ExprResult R = DefaultFunctionArrayLvalueConversion( |
1771 | E: reinterpret_cast<Expr *>(ControllingExprOrType)); |
1772 | if (R.isInvalid()) |
1773 | return ExprError(); |
1774 | ControllingExpr = R.get(); |
1775 | } else { |
1776 | // The extension form uses the type directly rather than converting it. |
1777 | ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType); |
1778 | if (!ControllingType) |
1779 | return ExprError(); |
1780 | } |
1781 | |
1782 | bool TypeErrorFound = false, |
1783 | IsResultDependent = ControllingExpr |
1784 | ? ControllingExpr->isTypeDependent() |
1785 | : ControllingType->getType()->isDependentType(), |
1786 | ContainsUnexpandedParameterPack = |
1787 | ControllingExpr |
1788 | ? ControllingExpr->containsUnexpandedParameterPack() |
1789 | : ControllingType->getType()->containsUnexpandedParameterPack(); |
1790 | |
1791 | // The controlling expression is an unevaluated operand, so side effects are |
1792 | // likely unintended. |
1793 | if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr && |
1794 | ControllingExpr->HasSideEffects(Context, false)) |
1795 | Diag(ControllingExpr->getExprLoc(), |
1796 | diag::warn_side_effects_unevaluated_context); |
1797 | |
1798 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1799 | if (Exprs[i]->containsUnexpandedParameterPack()) |
1800 | ContainsUnexpandedParameterPack = true; |
1801 | |
1802 | if (Types[i]) { |
1803 | if (Types[i]->getType()->containsUnexpandedParameterPack()) |
1804 | ContainsUnexpandedParameterPack = true; |
1805 | |
1806 | if (Types[i]->getType()->isDependentType()) { |
1807 | IsResultDependent = true; |
1808 | } else { |
1809 | // We relax the restriction on use of incomplete types and non-object |
1810 | // types with the type-based extension of _Generic. Allowing incomplete |
1811 | // objects means those can be used as "tags" for a type-safe way to map |
1812 | // to a value. Similarly, matching on function types rather than |
1813 | // function pointer types can be useful. However, the restriction on VM |
1814 | // types makes sense to retain as there are open questions about how |
1815 | // the selection can be made at compile time. |
1816 | // |
1817 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a |
1818 | // complete object type other than a variably modified type." |
1819 | // C2y removed the requirement that an expression form must |
1820 | // use a complete type, though it's still as-if the type has undergone |
1821 | // lvalue conversion. We support this as an extension in C23 and |
1822 | // earlier because GCC does so. |
1823 | unsigned D = 0; |
1824 | if (ControllingExpr && Types[i]->getType()->isIncompleteType()) |
1825 | D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete |
1826 | : diag::ext_assoc_type_incomplete; |
1827 | else if (ControllingExpr && !Types[i]->getType()->isObjectType()) |
1828 | D = diag::err_assoc_type_nonobject; |
1829 | else if (Types[i]->getType()->isVariablyModifiedType()) |
1830 | D = diag::err_assoc_type_variably_modified; |
1831 | else if (ControllingExpr) { |
1832 | // Because the controlling expression undergoes lvalue conversion, |
1833 | // array conversion, and function conversion, an association which is |
1834 | // of array type, function type, or is qualified can never be |
1835 | // reached. We will warn about this so users are less surprised by |
1836 | // the unreachable association. However, we don't have to handle |
1837 | // function types; that's not an object type, so it's handled above. |
1838 | // |
1839 | // The logic is somewhat different for C++ because C++ has different |
1840 | // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, |
1841 | // If T is a non-class type, the type of the prvalue is the cv- |
1842 | // unqualified version of T. Otherwise, the type of the prvalue is T. |
1843 | // The result of these rules is that all qualified types in an |
1844 | // association in C are unreachable, and in C++, only qualified non- |
1845 | // class types are unreachable. |
1846 | // |
1847 | // NB: this does not apply when the first operand is a type rather |
1848 | // than an expression, because the type form does not undergo |
1849 | // conversion. |
1850 | unsigned Reason = 0; |
1851 | QualType QT = Types[i]->getType(); |
1852 | if (QT->isArrayType()) |
1853 | Reason = 1; |
1854 | else if (QT.hasQualifiers() && |
1855 | (!LangOpts.CPlusPlus || !QT->isRecordType())) |
1856 | Reason = 2; |
1857 | |
1858 | if (Reason) |
1859 | Diag(Types[i]->getTypeLoc().getBeginLoc(), |
1860 | diag::warn_unreachable_association) |
1861 | << QT << (Reason - 1); |
1862 | } |
1863 | |
1864 | if (D != 0) { |
1865 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) |
1866 | << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType(); |
1867 | if (getDiagnostics().getDiagnosticLevel( |
1868 | DiagID: D, Loc: Types[i]->getTypeLoc().getBeginLoc()) >= |
1869 | DiagnosticsEngine::Error) |
1870 | TypeErrorFound = true; |
1871 | } |
1872 | |
1873 | // C11 6.5.1.1p2 "No two generic associations in the same generic |
1874 | // selection shall specify compatible types." |
1875 | for (unsigned j = i+1; j < NumAssocs; ++j) |
1876 | if (Types[j] && !Types[j]->getType()->isDependentType() && |
1877 | Context.typesAreCompatible(T1: Types[i]->getType(), |
1878 | T2: Types[j]->getType())) { |
1879 | Diag(Types[j]->getTypeLoc().getBeginLoc(), |
1880 | diag::err_assoc_compatible_types) |
1881 | << Types[j]->getTypeLoc().getSourceRange() |
1882 | << Types[j]->getType() |
1883 | << Types[i]->getType(); |
1884 | Diag(Types[i]->getTypeLoc().getBeginLoc(), |
1885 | diag::note_compat_assoc) |
1886 | << Types[i]->getTypeLoc().getSourceRange() |
1887 | << Types[i]->getType(); |
1888 | TypeErrorFound = true; |
1889 | } |
1890 | } |
1891 | } |
1892 | } |
1893 | if (TypeErrorFound) |
1894 | return ExprError(); |
1895 | |
1896 | // If we determined that the generic selection is result-dependent, don't |
1897 | // try to compute the result expression. |
1898 | if (IsResultDependent) { |
1899 | if (ControllingExpr) |
1900 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingExpr, |
1901 | AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1902 | ContainsUnexpandedParameterPack); |
1903 | return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, |
1904 | AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1905 | ContainsUnexpandedParameterPack); |
1906 | } |
1907 | |
1908 | SmallVector<unsigned, 1> CompatIndices; |
1909 | unsigned DefaultIndex = -1U; |
1910 | // Look at the canonical type of the controlling expression in case it was a |
1911 | // deduced type like __auto_type. However, when issuing diagnostics, use the |
1912 | // type the user wrote in source rather than the canonical one. |
1913 | for (unsigned i = 0; i < NumAssocs; ++i) { |
1914 | if (!Types[i]) |
1915 | DefaultIndex = i; |
1916 | else if (ControllingExpr && |
1917 | Context.typesAreCompatible( |
1918 | T1: ControllingExpr->getType().getCanonicalType(), |
1919 | T2: Types[i]->getType())) |
1920 | CompatIndices.push_back(Elt: i); |
1921 | else if (ControllingType && |
1922 | Context.typesAreCompatible( |
1923 | T1: ControllingType->getType().getCanonicalType(), |
1924 | T2: Types[i]->getType())) |
1925 | CompatIndices.push_back(Elt: i); |
1926 | } |
1927 | |
1928 | auto GetControllingRangeAndType = [](Expr *ControllingExpr, |
1929 | TypeSourceInfo *ControllingType) { |
1930 | // We strip parens here because the controlling expression is typically |
1931 | // parenthesized in macro definitions. |
1932 | if (ControllingExpr) |
1933 | ControllingExpr = ControllingExpr->IgnoreParens(); |
1934 | |
1935 | SourceRange SR = ControllingExpr |
1936 | ? ControllingExpr->getSourceRange() |
1937 | : ControllingType->getTypeLoc().getSourceRange(); |
1938 | QualType QT = ControllingExpr ? ControllingExpr->getType() |
1939 | : ControllingType->getType(); |
1940 | |
1941 | return std::make_pair(SR, QT); |
1942 | }; |
1943 | |
1944 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have |
1945 | // type compatible with at most one of the types named in its generic |
1946 | // association list." |
1947 | if (CompatIndices.size() > 1) { |
1948 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
1949 | SourceRange SR = P.first; |
1950 | Diag(SR.getBegin(), diag::err_generic_sel_multi_match) |
1951 | << SR << P.second << (unsigned)CompatIndices.size(); |
1952 | for (unsigned I : CompatIndices) { |
1953 | Diag(Types[I]->getTypeLoc().getBeginLoc(), |
1954 | diag::note_compat_assoc) |
1955 | << Types[I]->getTypeLoc().getSourceRange() |
1956 | << Types[I]->getType(); |
1957 | } |
1958 | return ExprError(); |
1959 | } |
1960 | |
1961 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, |
1962 | // its controlling expression shall have type compatible with exactly one of |
1963 | // the types named in its generic association list." |
1964 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { |
1965 | auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); |
1966 | SourceRange SR = P.first; |
1967 | Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second; |
1968 | return ExprError(); |
1969 | } |
1970 | |
1971 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a |
1972 | // type name that is compatible with the type of the controlling expression, |
1973 | // then the result expression of the generic selection is the expression |
1974 | // in that generic association. Otherwise, the result expression of the |
1975 | // generic selection is the expression in the default generic association." |
1976 | unsigned ResultIndex = |
1977 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; |
1978 | |
1979 | if (ControllingExpr) { |
1980 | return GenericSelectionExpr::Create( |
1981 | Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1982 | ContainsUnexpandedParameterPack, ResultIndex); |
1983 | } |
1984 | return GenericSelectionExpr::Create( |
1985 | Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc, |
1986 | ContainsUnexpandedParameterPack, ResultIndex); |
1987 | } |
1988 | |
1989 | static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) { |
1990 | switch (Kind) { |
1991 | default: |
1992 | llvm_unreachable("unexpected TokenKind"); |
1993 | case tok::kw___func__: |
1994 | return PredefinedIdentKind::Func; // [C99 6.4.2.2] |
1995 | case tok::kw___FUNCTION__: |
1996 | return PredefinedIdentKind::Function; |
1997 | case tok::kw___FUNCDNAME__: |
1998 | return PredefinedIdentKind::FuncDName; // [MS] |
1999 | case tok::kw___FUNCSIG__: |
2000 | return PredefinedIdentKind::FuncSig; // [MS] |
2001 | case tok::kw_L__FUNCTION__: |
2002 | return PredefinedIdentKind::LFunction; // [MS] |
2003 | case tok::kw_L__FUNCSIG__: |
2004 | return PredefinedIdentKind::LFuncSig; // [MS] |
2005 | case tok::kw___PRETTY_FUNCTION__: |
2006 | return PredefinedIdentKind::PrettyFunction; // [GNU] |
2007 | } |
2008 | } |
2009 | |
2010 | /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used |
2011 | /// to determine the value of a PredefinedExpr. This can be either a |
2012 | /// block, lambda, captured statement, function, otherwise a nullptr. |
2013 | static Decl *getPredefinedExprDecl(DeclContext *DC) { |
2014 | while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC)) |
2015 | DC = DC->getParent(); |
2016 | return cast_or_null<Decl>(Val: DC); |
2017 | } |
2018 | |
2019 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the |
2020 | /// location of the token and the offset of the ud-suffix within it. |
2021 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, |
2022 | unsigned Offset) { |
2023 | return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(), |
2024 | LangOpts: S.getLangOpts()); |
2025 | } |
2026 | |
2027 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up |
2028 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. |
2029 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, |
2030 | IdentifierInfo *UDSuffix, |
2031 | SourceLocation UDSuffixLoc, |
2032 | ArrayRef<Expr*> Args, |
2033 | SourceLocation LitEndLoc) { |
2034 | assert(Args.size() <= 2 && "too many arguments for literal operator"); |
2035 | |
2036 | QualType ArgTy[2]; |
2037 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { |
2038 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); |
2039 | if (ArgTy[ArgIdx]->isArrayType()) |
2040 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(T: ArgTy[ArgIdx]); |
2041 | } |
2042 | |
2043 | DeclarationName OpName = |
2044 | S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
2045 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
2046 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
2047 | |
2048 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); |
2049 | if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()), |
2050 | /*AllowRaw*/ false, /*AllowTemplate*/ false, |
2051 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
2052 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) |
2053 | return ExprError(); |
2054 | |
2055 | return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc); |
2056 | } |
2057 | |
2058 | ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) { |
2059 | // StringToks needs backing storage as it doesn't hold array elements itself |
2060 | std::vector<Token> ExpandedToks; |
2061 | if (getLangOpts().MicrosoftExt) |
2062 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
2063 | |
2064 | StringLiteralParser Literal(StringToks, PP, |
2065 | StringLiteralEvalMethod::Unevaluated); |
2066 | if (Literal.hadError) |
2067 | return ExprError(); |
2068 | |
2069 | SmallVector<SourceLocation, 4> StringTokLocs; |
2070 | for (const Token &Tok : StringToks) |
2071 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
2072 | |
2073 | StringLiteral *Lit = StringLiteral::Create( |
2074 | Ctx: Context, Str: Literal.GetString(), Kind: StringLiteralKind::Unevaluated, Pascal: false, Ty: {}, |
2075 | Loc: &StringTokLocs[0], NumConcatenated: StringTokLocs.size()); |
2076 | |
2077 | if (!Literal.getUDSuffix().empty()) { |
2078 | SourceLocation UDSuffixLoc = |
2079 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
2080 | Offset: Literal.getUDSuffixOffset()); |
2081 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); |
2082 | } |
2083 | |
2084 | return Lit; |
2085 | } |
2086 | |
2087 | std::vector<Token> |
2088 | Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) { |
2089 | // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function |
2090 | // local macros that expand to string literals that may be concatenated. |
2091 | // These macros are expanded here (in Sema), because StringLiteralParser |
2092 | // (in Lex) doesn't know the enclosing function (because it hasn't been |
2093 | // parsed yet). |
2094 | assert(getLangOpts().MicrosoftExt); |
2095 | |
2096 | // Note: Although function local macros are defined only inside functions, |
2097 | // we ensure a valid `CurrentDecl` even outside of a function. This allows |
2098 | // expansion of macros into empty string literals without additional checks. |
2099 | Decl *CurrentDecl = getPredefinedExprDecl(DC: CurContext); |
2100 | if (!CurrentDecl) |
2101 | CurrentDecl = Context.getTranslationUnitDecl(); |
2102 | |
2103 | std::vector<Token> ExpandedToks; |
2104 | ExpandedToks.reserve(n: Toks.size()); |
2105 | for (const Token &Tok : Toks) { |
2106 | if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) { |
2107 | assert(tok::isStringLiteral(Tok.getKind())); |
2108 | ExpandedToks.emplace_back(args: Tok); |
2109 | continue; |
2110 | } |
2111 | if (isa<TranslationUnitDecl>(CurrentDecl)) |
2112 | Diag(Tok.getLocation(), diag::ext_predef_outside_function); |
2113 | // Stringify predefined expression |
2114 | Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined) |
2115 | << Tok.getKind(); |
2116 | SmallString<64> Str; |
2117 | llvm::raw_svector_ostream OS(Str); |
2118 | Token &Exp = ExpandedToks.emplace_back(); |
2119 | Exp.startToken(); |
2120 | if (Tok.getKind() == tok::kw_L__FUNCTION__ || |
2121 | Tok.getKind() == tok::kw_L__FUNCSIG__) { |
2122 | OS << 'L'; |
2123 | Exp.setKind(tok::wide_string_literal); |
2124 | } else { |
2125 | Exp.setKind(tok::string_literal); |
2126 | } |
2127 | OS << '"' |
2128 | << Lexer::Stringify(Str: PredefinedExpr::ComputeName( |
2129 | IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl)) |
2130 | << '"'; |
2131 | PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: Tok.getEndLoc()); |
2132 | } |
2133 | return ExpandedToks; |
2134 | } |
2135 | |
2136 | ExprResult |
2137 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { |
2138 | assert(!StringToks.empty() && "Must have at least one string!"); |
2139 | |
2140 | // StringToks needs backing storage as it doesn't hold array elements itself |
2141 | std::vector<Token> ExpandedToks; |
2142 | if (getLangOpts().MicrosoftExt) |
2143 | StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(Toks: StringToks); |
2144 | |
2145 | StringLiteralParser Literal(StringToks, PP); |
2146 | if (Literal.hadError) |
2147 | return ExprError(); |
2148 | |
2149 | SmallVector<SourceLocation, 4> StringTokLocs; |
2150 | for (const Token &Tok : StringToks) |
2151 | StringTokLocs.push_back(Elt: Tok.getLocation()); |
2152 | |
2153 | QualType CharTy = Context.CharTy; |
2154 | StringLiteralKind Kind = StringLiteralKind::Ordinary; |
2155 | if (Literal.isWide()) { |
2156 | CharTy = Context.getWideCharType(); |
2157 | Kind = StringLiteralKind::Wide; |
2158 | } else if (Literal.isUTF8()) { |
2159 | if (getLangOpts().Char8) |
2160 | CharTy = Context.Char8Ty; |
2161 | else if (getLangOpts().C23) |
2162 | CharTy = Context.UnsignedCharTy; |
2163 | Kind = StringLiteralKind::UTF8; |
2164 | } else if (Literal.isUTF16()) { |
2165 | CharTy = Context.Char16Ty; |
2166 | Kind = StringLiteralKind::UTF16; |
2167 | } else if (Literal.isUTF32()) { |
2168 | CharTy = Context.Char32Ty; |
2169 | Kind = StringLiteralKind::UTF32; |
2170 | } else if (Literal.isPascal()) { |
2171 | CharTy = Context.UnsignedCharTy; |
2172 | } |
2173 | |
2174 | // Warn on u8 string literals before C++20 and C23, whose type |
2175 | // was an array of char before but becomes an array of char8_t. |
2176 | // In C++20, it cannot be used where a pointer to char is expected. |
2177 | // In C23, it might have an unexpected value if char was signed. |
2178 | if (Kind == StringLiteralKind::UTF8 && |
2179 | (getLangOpts().CPlusPlus |
2180 | ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8 |
2181 | : !getLangOpts().C23)) { |
2182 | Diag(StringTokLocs.front(), getLangOpts().CPlusPlus |
2183 | ? diag::warn_cxx20_compat_utf8_string |
2184 | : diag::warn_c23_compat_utf8_string); |
2185 | |
2186 | // Create removals for all 'u8' prefixes in the string literal(s). This |
2187 | // ensures C++20/C23 compatibility (but may change the program behavior when |
2188 | // built by non-Clang compilers for which the execution character set is |
2189 | // not always UTF-8). |
2190 | auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8); |
2191 | SourceLocation RemovalDiagLoc; |
2192 | for (const Token &Tok : StringToks) { |
2193 | if (Tok.getKind() == tok::utf8_string_literal) { |
2194 | if (RemovalDiagLoc.isInvalid()) |
2195 | RemovalDiagLoc = Tok.getLocation(); |
2196 | RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange( |
2197 | B: Tok.getLocation(), |
2198 | E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2, |
2199 | SM: getSourceManager(), LangOpts: getLangOpts()))); |
2200 | } |
2201 | } |
2202 | Diag(RemovalDiagLoc, RemovalDiag); |
2203 | } |
2204 | |
2205 | QualType StrTy = |
2206 | Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars()); |
2207 | |
2208 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! |
2209 | StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(), |
2210 | Kind, Pascal: Literal.Pascal, Ty: StrTy, |
2211 | Loc: &StringTokLocs[0], |
2212 | NumConcatenated: StringTokLocs.size()); |
2213 | if (Literal.getUDSuffix().empty()) |
2214 | return Lit; |
2215 | |
2216 | // We're building a user-defined literal. |
2217 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
2218 | SourceLocation UDSuffixLoc = |
2219 | getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()], |
2220 | Offset: Literal.getUDSuffixOffset()); |
2221 | |
2222 | // Make sure we're allowed user-defined literals here. |
2223 | if (!UDLScope) |
2224 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); |
2225 | |
2226 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form |
2227 | // operator "" X (str, len) |
2228 | QualType SizeType = Context.getSizeType(); |
2229 | |
2230 | DeclarationName OpName = |
2231 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
2232 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
2233 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
2234 | |
2235 | QualType ArgTy[] = { |
2236 | Context.getArrayDecayedType(T: StrTy), SizeType |
2237 | }; |
2238 | |
2239 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
2240 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy, |
2241 | /*AllowRaw*/ false, /*AllowTemplate*/ true, |
2242 | /*AllowStringTemplatePack*/ AllowStringTemplate: true, |
2243 | /*DiagnoseMissing*/ true, StringLit: Lit)) { |
2244 | |
2245 | case LOLR_Cooked: { |
2246 | llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars()); |
2247 | IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType, |
2248 | l: StringTokLocs[0]); |
2249 | Expr *Args[] = { Lit, LenArg }; |
2250 | |
2251 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); |
2252 | } |
2253 | |
2254 | case LOLR_Template: { |
2255 | TemplateArgumentListInfo ExplicitArgs; |
2256 | TemplateArgument Arg(Lit, /*IsCanonical=*/false); |
2257 | TemplateArgumentLocInfo ArgInfo(Lit); |
2258 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
2259 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(), |
2260 | ExplicitTemplateArgs: &ExplicitArgs); |
2261 | } |
2262 | |
2263 | case LOLR_StringTemplatePack: { |
2264 | TemplateArgumentListInfo ExplicitArgs; |
2265 | |
2266 | unsigned CharBits = Context.getIntWidth(T: CharTy); |
2267 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); |
2268 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
2269 | |
2270 | TemplateArgument TypeArg(CharTy); |
2271 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy)); |
2272 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo)); |
2273 | |
2274 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { |
2275 | Value = Lit->getCodeUnit(i: I); |
2276 | TemplateArgument Arg(Context, Value, CharTy); |
2277 | TemplateArgumentLocInfo ArgInfo; |
2278 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
2279 | } |
2280 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: StringTokLocs.back(), |
2281 | ExplicitTemplateArgs: &ExplicitArgs); |
2282 | } |
2283 | case LOLR_Raw: |
2284 | case LOLR_ErrorNoDiagnostic: |
2285 | llvm_unreachable("unexpected literal operator lookup result"); |
2286 | case LOLR_Error: |
2287 | return ExprError(); |
2288 | } |
2289 | llvm_unreachable("unexpected literal operator lookup result"); |
2290 | } |
2291 | |
2292 | DeclRefExpr * |
2293 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2294 | SourceLocation Loc, |
2295 | const CXXScopeSpec *SS) { |
2296 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); |
2297 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); |
2298 | } |
2299 | |
2300 | DeclRefExpr * |
2301 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2302 | const DeclarationNameInfo &NameInfo, |
2303 | const CXXScopeSpec *SS, NamedDecl *FoundD, |
2304 | SourceLocation TemplateKWLoc, |
2305 | const TemplateArgumentListInfo *TemplateArgs) { |
2306 | NestedNameSpecifierLoc NNS = |
2307 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); |
2308 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, |
2309 | TemplateArgs); |
2310 | } |
2311 | |
2312 | // CUDA/HIP: Check whether a captured reference variable is referencing a |
2313 | // host variable in a device or host device lambda. |
2314 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, |
2315 | VarDecl *VD) { |
2316 | if (!S.getLangOpts().CUDA || !VD->hasInit()) |
2317 | return false; |
2318 | assert(VD->getType()->isReferenceType()); |
2319 | |
2320 | // Check whether the reference variable is referencing a host variable. |
2321 | auto *DRE = dyn_cast<DeclRefExpr>(Val: VD->getInit()); |
2322 | if (!DRE) |
2323 | return false; |
2324 | auto *Referee = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
2325 | if (!Referee || !Referee->hasGlobalStorage() || |
2326 | Referee->hasAttr<CUDADeviceAttr>()) |
2327 | return false; |
2328 | |
2329 | // Check whether the current function is a device or host device lambda. |
2330 | // Check whether the reference variable is a capture by getDeclContext() |
2331 | // since refersToEnclosingVariableOrCapture() is not ready at this point. |
2332 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: S.CurContext); |
2333 | if (MD && MD->getParent()->isLambda() && |
2334 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && |
2335 | VD->getDeclContext() != MD) |
2336 | return true; |
2337 | |
2338 | return false; |
2339 | } |
2340 | |
2341 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { |
2342 | // A declaration named in an unevaluated operand never constitutes an odr-use. |
2343 | if (isUnevaluatedContext()) |
2344 | return NOUR_Unevaluated; |
2345 | |
2346 | // C++2a [basic.def.odr]p4: |
2347 | // A variable x whose name appears as a potentially-evaluated expression e |
2348 | // is odr-used by e unless [...] x is a reference that is usable in |
2349 | // constant expressions. |
2350 | // CUDA/HIP: |
2351 | // If a reference variable referencing a host variable is captured in a |
2352 | // device or host device lambda, the value of the referee must be copied |
2353 | // to the capture and the reference variable must be treated as odr-use |
2354 | // since the value of the referee is not known at compile time and must |
2355 | // be loaded from the captured. |
2356 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
2357 | if (VD->getType()->isReferenceType() && |
2358 | !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) && |
2359 | !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) && |
2360 | VD->isUsableInConstantExpressions(C: Context)) |
2361 | return NOUR_Constant; |
2362 | } |
2363 | |
2364 | // All remaining non-variable cases constitute an odr-use. For variables, we |
2365 | // need to wait and see how the expression is used. |
2366 | return NOUR_None; |
2367 | } |
2368 | |
2369 | DeclRefExpr * |
2370 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
2371 | const DeclarationNameInfo &NameInfo, |
2372 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, |
2373 | SourceLocation TemplateKWLoc, |
2374 | const TemplateArgumentListInfo *TemplateArgs) { |
2375 | bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) && |
2376 | NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc()); |
2377 | |
2378 | DeclRefExpr *E = DeclRefExpr::Create( |
2379 | Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty, |
2380 | VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D)); |
2381 | MarkDeclRefReferenced(E); |
2382 | |
2383 | // C++ [except.spec]p17: |
2384 | // An exception-specification is considered to be needed when: |
2385 | // - in an expression, the function is the unique lookup result or |
2386 | // the selected member of a set of overloaded functions. |
2387 | // |
2388 | // We delay doing this until after we've built the function reference and |
2389 | // marked it as used so that: |
2390 | // a) if the function is defaulted, we get errors from defining it before / |
2391 | // instead of errors from computing its exception specification, and |
2392 | // b) if the function is a defaulted comparison, we can use the body we |
2393 | // build when defining it as input to the exception specification |
2394 | // computation rather than computing a new body. |
2395 | if (const auto *FPT = Ty->getAs<FunctionProtoType>()) { |
2396 | if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) { |
2397 | if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT)) |
2398 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); |
2399 | } |
2400 | } |
2401 | |
2402 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && |
2403 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && |
2404 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) |
2405 | getCurFunction()->recordUseOfWeak(E); |
2406 | |
2407 | const auto *FD = dyn_cast<FieldDecl>(Val: D); |
2408 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D)) |
2409 | FD = IFD->getAnonField(); |
2410 | if (FD) { |
2411 | UnusedPrivateFields.remove(FD); |
2412 | // Just in case we're building an illegal pointer-to-member. |
2413 | if (FD->isBitField()) |
2414 | E->setObjectKind(OK_BitField); |
2415 | } |
2416 | |
2417 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier |
2418 | // designates a bit-field. |
2419 | if (const auto *BD = dyn_cast<BindingDecl>(Val: D)) |
2420 | if (const auto *BE = BD->getBinding()) |
2421 | E->setObjectKind(BE->getObjectKind()); |
2422 | |
2423 | return E; |
2424 | } |
2425 | |
2426 | void |
2427 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, |
2428 | TemplateArgumentListInfo &Buffer, |
2429 | DeclarationNameInfo &NameInfo, |
2430 | const TemplateArgumentListInfo *&TemplateArgs) { |
2431 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { |
2432 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); |
2433 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); |
2434 | |
2435 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), |
2436 | Id.TemplateId->NumArgs); |
2437 | translateTemplateArguments(In: TemplateArgsPtr, Out&: Buffer); |
2438 | |
2439 | TemplateName TName = Id.TemplateId->Template.get(); |
2440 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; |
2441 | NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc); |
2442 | TemplateArgs = &Buffer; |
2443 | } else { |
2444 | NameInfo = GetNameFromUnqualifiedId(Name: Id); |
2445 | TemplateArgs = nullptr; |
2446 | } |
2447 | } |
2448 | |
2449 | static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, |
2450 | Sema &SemaRef, const CXXScopeSpec &SS, |
2451 | DeclarationName Typo, |
2452 | SourceRange TypoRange, |
2453 | unsigned DiagnosticID, |
2454 | unsigned DiagnosticSuggestID) { |
2455 | DeclContext *Ctx = |
2456 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, EnteringContext: false); |
2457 | if (!TC) { |
2458 | // Emit a special diagnostic for failed member lookups. |
2459 | // FIXME: computing the declaration context might fail here (?) |
2460 | if (Ctx) |
2461 | SemaRef.Diag(TypoRange.getBegin(), diag::err_no_member) |
2462 | << Typo << Ctx << TypoRange; |
2463 | else |
2464 | SemaRef.Diag(TypoRange.getBegin(), DiagnosticID) << Typo << TypoRange; |
2465 | return; |
2466 | } |
2467 | |
2468 | std::string CorrectedStr = TC.getAsString(LO: SemaRef.getLangOpts()); |
2469 | bool DroppedSpecifier = |
2470 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; |
2471 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() |
2472 | ? diag::note_implicit_param_decl |
2473 | : diag::note_previous_decl; |
2474 | if (!Ctx) |
2475 | SemaRef.diagnoseTypo( |
2476 | TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo << TypoRange, |
2477 | SemaRef.PDiag(NoteID)); |
2478 | else |
2479 | SemaRef.diagnoseTypo(TC, |
2480 | SemaRef.PDiag(diag::err_no_member_suggest) |
2481 | << Typo << Ctx << DroppedSpecifier << TypoRange, |
2482 | SemaRef.PDiag(NoteID)); |
2483 | } |
2484 | |
2485 | bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) { |
2486 | // During a default argument instantiation the CurContext points |
2487 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a |
2488 | // function parameter list, hence add an explicit check. |
2489 | bool isDefaultArgument = |
2490 | !CodeSynthesisContexts.empty() && |
2491 | CodeSynthesisContexts.back().Kind == |
2492 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; |
2493 | const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: CurContext); |
2494 | bool isInstance = CurMethod && CurMethod->isInstance() && |
2495 | R.getNamingClass() == CurMethod->getParent() && |
2496 | !isDefaultArgument; |
2497 | |
2498 | // There are two ways we can find a class-scope declaration during template |
2499 | // instantiation that we did not find in the template definition: if it is a |
2500 | // member of a dependent base class, or if it is declared after the point of |
2501 | // use in the same class. Distinguish these by comparing the class in which |
2502 | // the member was found to the naming class of the lookup. |
2503 | unsigned DiagID = diag::err_found_in_dependent_base; |
2504 | unsigned NoteID = diag::note_member_declared_at; |
2505 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { |
2506 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class |
2507 | : diag::err_found_later_in_class; |
2508 | } else if (getLangOpts().MSVCCompat) { |
2509 | DiagID = diag::ext_found_in_dependent_base; |
2510 | NoteID = diag::note_dependent_member_use; |
2511 | } |
2512 | |
2513 | if (isInstance) { |
2514 | // Give a code modification hint to insert 'this->'. |
2515 | Diag(R.getNameLoc(), DiagID) |
2516 | << R.getLookupName() |
2517 | << FixItHint::CreateInsertion(InsertionLoc: R.getNameLoc(), Code: "this->"); |
2518 | CheckCXXThisCapture(Loc: R.getNameLoc()); |
2519 | } else { |
2520 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming |
2521 | // they're not shadowed). |
2522 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); |
2523 | } |
2524 | |
2525 | for (const NamedDecl *D : R) |
2526 | Diag(D->getLocation(), NoteID); |
2527 | |
2528 | // Return true if we are inside a default argument instantiation |
2529 | // and the found name refers to an instance member function, otherwise |
2530 | // the caller will try to create an implicit member call and this is wrong |
2531 | // for default arguments. |
2532 | // |
2533 | // FIXME: Is this special case necessary? We could allow the caller to |
2534 | // diagnose this. |
2535 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { |
2536 | Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0; |
2537 | return true; |
2538 | } |
2539 | |
2540 | // Tell the callee to try to recover. |
2541 | return false; |
2542 | } |
2543 | |
2544 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
2545 | CorrectionCandidateCallback &CCC, |
2546 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2547 | ArrayRef<Expr *> Args, DeclContext *LookupCtx, |
2548 | TypoExpr **Out) { |
2549 | DeclarationName Name = R.getLookupName(); |
2550 | SourceRange NameRange = R.getLookupNameInfo().getSourceRange(); |
2551 | |
2552 | unsigned diagnostic = diag::err_undeclared_var_use; |
2553 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; |
2554 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || |
2555 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || |
2556 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
2557 | diagnostic = diag::err_undeclared_use; |
2558 | diagnostic_suggest = diag::err_undeclared_use_suggest; |
2559 | } |
2560 | |
2561 | // If the original lookup was an unqualified lookup, fake an |
2562 | // unqualified lookup. This is useful when (for example) the |
2563 | // original lookup would not have found something because it was a |
2564 | // dependent name. |
2565 | DeclContext *DC = |
2566 | LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr); |
2567 | while (DC) { |
2568 | if (isa<CXXRecordDecl>(Val: DC)) { |
2569 | if (ExplicitTemplateArgs) { |
2570 | if (LookupTemplateName( |
2571 | R, S, SS, ObjectType: Context.getRecordType(cast<CXXRecordDecl>(Val: DC)), |
2572 | /*EnteringContext*/ false, RequiredTemplate: TemplateNameIsRequired, |
2573 | /*RequiredTemplateKind*/ ATK: nullptr, /*AllowTypoCorrection*/ true)) |
2574 | return true; |
2575 | } else { |
2576 | LookupQualifiedName(R, LookupCtx: DC); |
2577 | } |
2578 | |
2579 | if (!R.empty()) { |
2580 | // Don't give errors about ambiguities in this lookup. |
2581 | R.suppressDiagnostics(); |
2582 | |
2583 | // If there's a best viable function among the results, only mention |
2584 | // that one in the notes. |
2585 | OverloadCandidateSet Candidates(R.getNameLoc(), |
2586 | OverloadCandidateSet::CSK_Normal); |
2587 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates); |
2588 | OverloadCandidateSet::iterator Best; |
2589 | if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) == |
2590 | OR_Success) { |
2591 | R.clear(); |
2592 | R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess()); |
2593 | R.resolveKind(); |
2594 | } |
2595 | |
2596 | return DiagnoseDependentMemberLookup(R); |
2597 | } |
2598 | |
2599 | R.clear(); |
2600 | } |
2601 | |
2602 | DC = DC->getLookupParent(); |
2603 | } |
2604 | |
2605 | // We didn't find anything, so try to correct for a typo. |
2606 | TypoCorrection Corrected; |
2607 | if (S && Out) { |
2608 | assert(!ExplicitTemplateArgs && |
2609 | "Diagnosing an empty lookup with explicit template args!"); |
2610 | *Out = CorrectTypoDelayed( |
2611 | Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC, |
2612 | TDG: [=](const TypoCorrection &TC) { |
2613 | emitEmptyLookupTypoDiagnostic(TC, SemaRef&: *this, SS, Typo: Name, TypoRange: NameRange, |
2614 | DiagnosticID: diagnostic, DiagnosticSuggestID: diagnostic_suggest); |
2615 | }, |
2616 | TRC: nullptr, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx); |
2617 | if (*Out) |
2618 | return true; |
2619 | } else if (S && (Corrected = CorrectTypo( |
2620 | Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC, |
2621 | Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx))) { |
2622 | std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts())); |
2623 | bool DroppedSpecifier = |
2624 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; |
2625 | R.setLookupName(Corrected.getCorrection()); |
2626 | |
2627 | bool AcceptableWithRecovery = false; |
2628 | bool AcceptableWithoutRecovery = false; |
2629 | NamedDecl *ND = Corrected.getFoundDecl(); |
2630 | if (ND) { |
2631 | if (Corrected.isOverloaded()) { |
2632 | OverloadCandidateSet OCS(R.getNameLoc(), |
2633 | OverloadCandidateSet::CSK_Normal); |
2634 | OverloadCandidateSet::iterator Best; |
2635 | for (NamedDecl *CD : Corrected) { |
2636 | if (FunctionTemplateDecl *FTD = |
2637 | dyn_cast<FunctionTemplateDecl>(Val: CD)) |
2638 | AddTemplateOverloadCandidate( |
2639 | FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, |
2640 | Args, CandidateSet&: OCS); |
2641 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD)) |
2642 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) |
2643 | AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(FD, AS_none), |
2644 | Args, CandidateSet&: OCS); |
2645 | } |
2646 | switch (OCS.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best)) { |
2647 | case OR_Success: |
2648 | ND = Best->FoundDecl; |
2649 | Corrected.setCorrectionDecl(ND); |
2650 | break; |
2651 | default: |
2652 | // FIXME: Arbitrarily pick the first declaration for the note. |
2653 | Corrected.setCorrectionDecl(ND); |
2654 | break; |
2655 | } |
2656 | } |
2657 | R.addDecl(D: ND); |
2658 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { |
2659 | CXXRecordDecl *Record = nullptr; |
2660 | if (Corrected.getCorrectionSpecifier()) { |
2661 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); |
2662 | Record = Ty->getAsCXXRecordDecl(); |
2663 | } |
2664 | if (!Record) |
2665 | Record = cast<CXXRecordDecl>( |
2666 | ND->getDeclContext()->getRedeclContext()); |
2667 | R.setNamingClass(Record); |
2668 | } |
2669 | |
2670 | auto *UnderlyingND = ND->getUnderlyingDecl(); |
2671 | AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) || |
2672 | isa<FunctionTemplateDecl>(Val: UnderlyingND); |
2673 | // FIXME: If we ended up with a typo for a type name or |
2674 | // Objective-C class name, we're in trouble because the parser |
2675 | // is in the wrong place to recover. Suggest the typo |
2676 | // correction, but don't make it a fix-it since we're not going |
2677 | // to recover well anyway. |
2678 | AcceptableWithoutRecovery = isa<TypeDecl>(Val: UnderlyingND) || |
2679 | getAsTypeTemplateDecl(UnderlyingND) || |
2680 | isa<ObjCInterfaceDecl>(Val: UnderlyingND); |
2681 | } else { |
2682 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it |
2683 | // because we aren't able to recover. |
2684 | AcceptableWithoutRecovery = true; |
2685 | } |
2686 | |
2687 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { |
2688 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() |
2689 | ? diag::note_implicit_param_decl |
2690 | : diag::note_previous_decl; |
2691 | if (SS.isEmpty()) |
2692 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange, |
2693 | PDiag(NoteID), AcceptableWithRecovery); |
2694 | else |
2695 | diagnoseTypo(Corrected, |
2696 | PDiag(diag::err_no_member_suggest) |
2697 | << Name << computeDeclContext(SS, false) |
2698 | << DroppedSpecifier << NameRange, |
2699 | PDiag(NoteID), AcceptableWithRecovery); |
2700 | |
2701 | // Tell the callee whether to try to recover. |
2702 | return !AcceptableWithRecovery; |
2703 | } |
2704 | } |
2705 | R.clear(); |
2706 | |
2707 | // Emit a special diagnostic for failed member lookups. |
2708 | // FIXME: computing the declaration context might fail here (?) |
2709 | if (!SS.isEmpty()) { |
2710 | Diag(R.getNameLoc(), diag::err_no_member) |
2711 | << Name << computeDeclContext(SS, false) << NameRange; |
2712 | return true; |
2713 | } |
2714 | |
2715 | // Give up, we can't recover. |
2716 | Diag(R.getNameLoc(), diagnostic) << Name << NameRange; |
2717 | return true; |
2718 | } |
2719 | |
2720 | /// In Microsoft mode, if we are inside a template class whose parent class has |
2721 | /// dependent base classes, and we can't resolve an unqualified identifier, then |
2722 | /// assume the identifier is a member of a dependent base class. We can only |
2723 | /// recover successfully in static methods, instance methods, and other contexts |
2724 | /// where 'this' is available. This doesn't precisely match MSVC's |
2725 | /// instantiation model, but it's close enough. |
2726 | static Expr * |
2727 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, |
2728 | DeclarationNameInfo &NameInfo, |
2729 | SourceLocation TemplateKWLoc, |
2730 | const TemplateArgumentListInfo *TemplateArgs) { |
2731 | // Only try to recover from lookup into dependent bases in static methods or |
2732 | // contexts where 'this' is available. |
2733 | QualType ThisType = S.getCurrentThisType(); |
2734 | const CXXRecordDecl *RD = nullptr; |
2735 | if (!ThisType.isNull()) |
2736 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); |
2737 | else if (auto *MD = dyn_cast<CXXMethodDecl>(Val: S.CurContext)) |
2738 | RD = MD->getParent(); |
2739 | if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases()) |
2740 | return nullptr; |
2741 | |
2742 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' |
2743 | // is available, suggest inserting 'this->' as a fixit. |
2744 | SourceLocation Loc = NameInfo.getLoc(); |
2745 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); |
2746 | DB << NameInfo.getName() << RD; |
2747 | |
2748 | if (!ThisType.isNull()) { |
2749 | DB << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "this->"); |
2750 | return CXXDependentScopeMemberExpr::Create( |
2751 | Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true, |
2752 | /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc, |
2753 | /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs); |
2754 | } |
2755 | |
2756 | // Synthesize a fake NNS that points to the derived class. This will |
2757 | // perform name lookup during template instantiation. |
2758 | CXXScopeSpec SS; |
2759 | auto *NNS = |
2760 | NestedNameSpecifier::Create(Context, nullptr, RD->getTypeForDecl()); |
2761 | SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(Loc, Loc)); |
2762 | return DependentScopeDeclRefExpr::Create( |
2763 | Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
2764 | TemplateArgs); |
2765 | } |
2766 | |
2767 | ExprResult |
2768 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, |
2769 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, |
2770 | bool HasTrailingLParen, bool IsAddressOfOperand, |
2771 | CorrectionCandidateCallback *CCC, |
2772 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { |
2773 | assert(!(IsAddressOfOperand && HasTrailingLParen) && |
2774 | "cannot be direct & operand and have a trailing lparen"); |
2775 | if (SS.isInvalid()) |
2776 | return ExprError(); |
2777 | |
2778 | TemplateArgumentListInfo TemplateArgsBuffer; |
2779 | |
2780 | // Decompose the UnqualifiedId into the following data. |
2781 | DeclarationNameInfo NameInfo; |
2782 | const TemplateArgumentListInfo *TemplateArgs; |
2783 | DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer, NameInfo, TemplateArgs); |
2784 | |
2785 | DeclarationName Name = NameInfo.getName(); |
2786 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
2787 | SourceLocation NameLoc = NameInfo.getLoc(); |
2788 | |
2789 | if (II && II->isEditorPlaceholder()) { |
2790 | // FIXME: When typed placeholders are supported we can create a typed |
2791 | // placeholder expression node. |
2792 | return ExprError(); |
2793 | } |
2794 | |
2795 | // This specially handles arguments of attributes appertains to a type of C |
2796 | // struct field such that the name lookup within a struct finds the member |
2797 | // name, which is not the case for other contexts in C. |
2798 | if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) { |
2799 | // See if this is reference to a field of struct. |
2800 | LookupResult R(*this, NameInfo, LookupMemberName); |
2801 | // LookupName handles a name lookup from within anonymous struct. |
2802 | if (LookupName(R, S)) { |
2803 | if (auto *VD = dyn_cast<ValueDecl>(Val: R.getFoundDecl())) { |
2804 | QualType type = VD->getType().getNonReferenceType(); |
2805 | // This will eventually be translated into MemberExpr upon |
2806 | // the use of instantiated struct fields. |
2807 | return BuildDeclRefExpr(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc); |
2808 | } |
2809 | } |
2810 | } |
2811 | |
2812 | // Perform the required lookup. |
2813 | LookupResult R(*this, NameInfo, |
2814 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) |
2815 | ? LookupObjCImplicitSelfParam |
2816 | : LookupOrdinaryName); |
2817 | if (TemplateKWLoc.isValid() || TemplateArgs) { |
2818 | // Lookup the template name again to correctly establish the context in |
2819 | // which it was found. This is really unfortunate as we already did the |
2820 | // lookup to determine that it was a template name in the first place. If |
2821 | // this becomes a performance hit, we can work harder to preserve those |
2822 | // results until we get here but it's likely not worth it. |
2823 | AssumedTemplateKind AssumedTemplate; |
2824 | if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(), |
2825 | /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc, |
2826 | ATK: &AssumedTemplate)) |
2827 | return ExprError(); |
2828 | |
2829 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2830 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
2831 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
2832 | } else { |
2833 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); |
2834 | LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType(), |
2835 | /*AllowBuiltinCreation=*/!IvarLookupFollowUp); |
2836 | |
2837 | // If the result might be in a dependent base class, this is a dependent |
2838 | // id-expression. |
2839 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2840 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
2841 | isAddressOfOperand: IsAddressOfOperand, TemplateArgs); |
2842 | |
2843 | // If this reference is in an Objective-C method, then we need to do |
2844 | // some special Objective-C lookup, too. |
2845 | if (IvarLookupFollowUp) { |
2846 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II, AllowBuiltinCreation: true)); |
2847 | if (E.isInvalid()) |
2848 | return ExprError(); |
2849 | |
2850 | if (Expr *Ex = E.getAs<Expr>()) |
2851 | return Ex; |
2852 | } |
2853 | } |
2854 | |
2855 | if (R.isAmbiguous()) |
2856 | return ExprError(); |
2857 | |
2858 | // This could be an implicitly declared function reference if the language |
2859 | // mode allows it as a feature. |
2860 | if (R.empty() && HasTrailingLParen && II && |
2861 | getLangOpts().implicitFunctionsAllowed()) { |
2862 | NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *II, S); |
2863 | if (D) R.addDecl(D); |
2864 | } |
2865 | |
2866 | // Determine whether this name might be a candidate for |
2867 | // argument-dependent lookup. |
2868 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); |
2869 | |
2870 | if (R.empty() && !ADL) { |
2871 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { |
2872 | if (Expr *E = recoverFromMSUnqualifiedLookup(S&: *this, Context, NameInfo, |
2873 | TemplateKWLoc, TemplateArgs)) |
2874 | return E; |
2875 | } |
2876 | |
2877 | // Don't diagnose an empty lookup for inline assembly. |
2878 | if (IsInlineAsmIdentifier) |
2879 | return ExprError(); |
2880 | |
2881 | // If this name wasn't predeclared and if this is not a function |
2882 | // call, diagnose the problem. |
2883 | TypoExpr *TE = nullptr; |
2884 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() |
2885 | : nullptr); |
2886 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; |
2887 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && |
2888 | "Typo correction callback misconfigured"); |
2889 | if (CCC) { |
2890 | // Make sure the callback knows what the typo being diagnosed is. |
2891 | CCC->setTypoName(II); |
2892 | if (SS.isValid()) |
2893 | CCC->setTypoNNS(SS.getScopeRep()); |
2894 | } |
2895 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for |
2896 | // a template name, but we happen to have always already looked up the name |
2897 | // before we get here if it must be a template name. |
2898 | if (DiagnoseEmptyLookup(S, SS, R, CCC&: CCC ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr, |
2899 | Args: {}, LookupCtx: nullptr, Out: &TE)) { |
2900 | if (TE && KeywordReplacement) { |
2901 | auto &State = getTypoExprState(TE); |
2902 | auto BestTC = State.Consumer->getNextCorrection(); |
2903 | if (BestTC.isKeyword()) { |
2904 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); |
2905 | if (State.DiagHandler) |
2906 | State.DiagHandler(BestTC); |
2907 | KeywordReplacement->startToken(); |
2908 | KeywordReplacement->setKind(II->getTokenID()); |
2909 | KeywordReplacement->setIdentifierInfo(II); |
2910 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); |
2911 | // Clean up the state associated with the TypoExpr, since it has |
2912 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). |
2913 | clearDelayedTypo(TE); |
2914 | // Signal that a correction to a keyword was performed by returning a |
2915 | // valid-but-null ExprResult. |
2916 | return (Expr*)nullptr; |
2917 | } |
2918 | State.Consumer->resetCorrectionStream(); |
2919 | } |
2920 | return TE ? TE : ExprError(); |
2921 | } |
2922 | |
2923 | assert(!R.empty() && |
2924 | "DiagnoseEmptyLookup returned false but added no results"); |
2925 | |
2926 | // If we found an Objective-C instance variable, let |
2927 | // LookupInObjCMethod build the appropriate expression to |
2928 | // reference the ivar. |
2929 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { |
2930 | R.clear(); |
2931 | ExprResult E(ObjC().LookupInObjCMethod(LookUp&: R, S, II: Ivar->getIdentifier())); |
2932 | // In a hopelessly buggy code, Objective-C instance variable |
2933 | // lookup fails and no expression will be built to reference it. |
2934 | if (!E.isInvalid() && !E.get()) |
2935 | return ExprError(); |
2936 | return E; |
2937 | } |
2938 | } |
2939 | |
2940 | // This is guaranteed from this point on. |
2941 | assert(!R.empty() || ADL); |
2942 | |
2943 | // Check whether this might be a C++ implicit instance member access. |
2944 | // C++ [class.mfct.non-static]p3: |
2945 | // When an id-expression that is not part of a class member access |
2946 | // syntax and not used to form a pointer to member is used in the |
2947 | // body of a non-static member function of class X, if name lookup |
2948 | // resolves the name in the id-expression to a non-static non-type |
2949 | // member of some class C, the id-expression is transformed into a |
2950 | // class member access expression using (*this) as the |
2951 | // postfix-expression to the left of the . operator. |
2952 | // |
2953 | // But we don't actually need to do this for '&' operands if R |
2954 | // resolved to a function or overloaded function set, because the |
2955 | // expression is ill-formed if it actually works out to be a |
2956 | // non-static member function: |
2957 | // |
2958 | // C++ [expr.ref]p4: |
2959 | // Otherwise, if E1.E2 refers to a non-static member function. . . |
2960 | // [t]he expression can be used only as the left-hand operand of a |
2961 | // member function call. |
2962 | // |
2963 | // There are other safeguards against such uses, but it's important |
2964 | // to get this right here so that we don't end up making a |
2965 | // spuriously dependent expression if we're inside a dependent |
2966 | // instance method. |
2967 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
2968 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, |
2969 | S); |
2970 | |
2971 | if (TemplateArgs || TemplateKWLoc.isValid()) { |
2972 | |
2973 | // In C++1y, if this is a variable template id, then check it |
2974 | // in BuildTemplateIdExpr(). |
2975 | // The single lookup result must be a variable template declaration. |
2976 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && |
2977 | Id.TemplateId->Kind == TNK_Var_template) { |
2978 | assert(R.getAsSingle<VarTemplateDecl>() && |
2979 | "There should only be one declaration found."); |
2980 | } |
2981 | |
2982 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: ADL, TemplateArgs); |
2983 | } |
2984 | |
2985 | return BuildDeclarationNameExpr(SS, R, NeedsADL: ADL); |
2986 | } |
2987 | |
2988 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( |
2989 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, |
2990 | bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) { |
2991 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
2992 | LookupParsedName(R, /*S=*/nullptr, SS: &SS, /*ObjectType=*/QualType()); |
2993 | |
2994 | if (R.isAmbiguous()) |
2995 | return ExprError(); |
2996 | |
2997 | if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid()) |
2998 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), |
2999 | NameInfo, /*TemplateArgs=*/nullptr); |
3000 | |
3001 | if (R.empty()) { |
3002 | // Don't diagnose problems with invalid record decl, the secondary no_member |
3003 | // diagnostic during template instantiation is likely bogus, e.g. if a class |
3004 | // is invalid because it's derived from an invalid base class, then missing |
3005 | // members were likely supposed to be inherited. |
3006 | DeclContext *DC = computeDeclContext(SS); |
3007 | if (const auto *CD = dyn_cast<CXXRecordDecl>(Val: DC)) |
3008 | if (CD->isInvalidDecl()) |
3009 | return ExprError(); |
3010 | Diag(NameInfo.getLoc(), diag::err_no_member) |
3011 | << NameInfo.getName() << DC << SS.getRange(); |
3012 | return ExprError(); |
3013 | } |
3014 | |
3015 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { |
3016 | QualType Ty = Context.getTypeDeclType(Decl: TD); |
3017 | QualType ET = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, T: Ty); |
3018 | |
3019 | // Diagnose a missing typename if this resolved unambiguously to a type in |
3020 | // a dependent context. If we can recover with a type, downgrade this to |
3021 | // a warning in Microsoft compatibility mode. |
3022 | unsigned DiagID = diag::err_typename_missing; |
3023 | if (RecoveryTSI && getLangOpts().MSVCCompat) |
3024 | DiagID = diag::ext_typename_missing; |
3025 | SourceLocation Loc = SS.getBeginLoc(); |
3026 | auto D = Diag(Loc, DiagID); |
3027 | D << ET << SourceRange(Loc, NameInfo.getEndLoc()); |
3028 | |
3029 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE |
3030 | // context. |
3031 | if (!RecoveryTSI) |
3032 | return ExprError(); |
3033 | |
3034 | // Only issue the fixit if we're prepared to recover. |
3035 | D << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename "); |
3036 | |
3037 | // Recover by pretending this was an elaborated type. |
3038 | TypeLocBuilder TLB; |
3039 | TLB.pushTypeSpec(T: Ty).setNameLoc(NameInfo.getLoc()); |
3040 | |
3041 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(T: ET); |
3042 | QTL.setElaboratedKeywordLoc(SourceLocation()); |
3043 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
3044 | |
3045 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: ET); |
3046 | |
3047 | return ExprEmpty(); |
3048 | } |
3049 | |
3050 | // If necessary, build an implicit class member access. |
3051 | if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand)) |
3052 | return BuildPossibleImplicitMemberExpr(SS, |
3053 | /*TemplateKWLoc=*/SourceLocation(), |
3054 | R, /*TemplateArgs=*/nullptr, |
3055 | /*S=*/nullptr); |
3056 | |
3057 | return BuildDeclarationNameExpr(SS, R, /*ADL=*/NeedsADL: false); |
3058 | } |
3059 | |
3060 | ExprResult |
3061 | Sema::PerformObjectMemberConversion(Expr *From, |
3062 | NestedNameSpecifier *Qualifier, |
3063 | NamedDecl *FoundDecl, |
3064 | NamedDecl *Member) { |
3065 | const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); |
3066 | if (!RD) |
3067 | return From; |
3068 | |
3069 | QualType DestRecordType; |
3070 | QualType DestType; |
3071 | QualType FromRecordType; |
3072 | QualType FromType = From->getType(); |
3073 | bool PointerConversions = false; |
3074 | if (isa<FieldDecl>(Val: Member)) { |
3075 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(Decl: RD)); |
3076 | auto FromPtrType = FromType->getAs<PointerType>(); |
3077 | DestRecordType = Context.getAddrSpaceQualType( |
3078 | T: DestRecordType, AddressSpace: FromPtrType |
3079 | ? FromType->getPointeeType().getAddressSpace() |
3080 | : FromType.getAddressSpace()); |
3081 | |
3082 | if (FromPtrType) { |
3083 | DestType = Context.getPointerType(T: DestRecordType); |
3084 | FromRecordType = FromPtrType->getPointeeType(); |
3085 | PointerConversions = true; |
3086 | } else { |
3087 | DestType = DestRecordType; |
3088 | FromRecordType = FromType; |
3089 | } |
3090 | } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: Member)) { |
3091 | if (!Method->isImplicitObjectMemberFunction()) |
3092 | return From; |
3093 | |
3094 | DestType = Method->getThisType().getNonReferenceType(); |
3095 | DestRecordType = Method->getFunctionObjectParameterType(); |
3096 | |
3097 | if (FromType->getAs<PointerType>()) { |
3098 | FromRecordType = FromType->getPointeeType(); |
3099 | PointerConversions = true; |
3100 | } else { |
3101 | FromRecordType = FromType; |
3102 | DestType = DestRecordType; |
3103 | } |
3104 | |
3105 | LangAS FromAS = FromRecordType.getAddressSpace(); |
3106 | LangAS DestAS = DestRecordType.getAddressSpace(); |
3107 | if (FromAS != DestAS) { |
3108 | QualType FromRecordTypeWithoutAS = |
3109 | Context.removeAddrSpaceQualType(T: FromRecordType); |
3110 | QualType FromTypeWithDestAS = |
3111 | Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS); |
3112 | if (PointerConversions) |
3113 | FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS); |
3114 | From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS, |
3115 | CK: CK_AddressSpaceConversion, VK: From->getValueKind()) |
3116 | .get(); |
3117 | } |
3118 | } else { |
3119 | // No conversion necessary. |
3120 | return From; |
3121 | } |
3122 | |
3123 | if (DestType->isDependentType() || FromType->isDependentType()) |
3124 | return From; |
3125 | |
3126 | // If the unqualified types are the same, no conversion is necessary. |
3127 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
3128 | return From; |
3129 | |
3130 | SourceRange FromRange = From->getSourceRange(); |
3131 | SourceLocation FromLoc = FromRange.getBegin(); |
3132 | |
3133 | ExprValueKind VK = From->getValueKind(); |
3134 | |
3135 | // C++ [class.member.lookup]p8: |
3136 | // [...] Ambiguities can often be resolved by qualifying a name with its |
3137 | // class name. |
3138 | // |
3139 | // If the member was a qualified name and the qualified referred to a |
3140 | // specific base subobject type, we'll cast to that intermediate type |
3141 | // first and then to the object in which the member is declared. That allows |
3142 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: |
3143 | // |
3144 | // class Base { public: int x; }; |
3145 | // class Derived1 : public Base { }; |
3146 | // class Derived2 : public Base { }; |
3147 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; |
3148 | // |
3149 | // void VeryDerived::f() { |
3150 | // x = 17; // error: ambiguous base subobjects |
3151 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 |
3152 | // } |
3153 | if (Qualifier && Qualifier->getAsType()) { |
3154 | QualType QType = QualType(Qualifier->getAsType(), 0); |
3155 | assert(QType->isRecordType() && "lookup done with non-record type"); |
3156 | |
3157 | QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); |
3158 | |
3159 | // In C++98, the qualifier type doesn't actually have to be a base |
3160 | // type of the object type, in which case we just ignore it. |
3161 | // Otherwise build the appropriate casts. |
3162 | if (IsDerivedFrom(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) { |
3163 | CXXCastPath BasePath; |
3164 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType, |
3165 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath)) |
3166 | return ExprError(); |
3167 | |
3168 | if (PointerConversions) |
3169 | QType = Context.getPointerType(T: QType); |
3170 | From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase, |
3171 | VK, BasePath: &BasePath).get(); |
3172 | |
3173 | FromType = QType; |
3174 | FromRecordType = QRecordType; |
3175 | |
3176 | // If the qualifier type was the same as the destination type, |
3177 | // we're done. |
3178 | if (Context.hasSameUnqualifiedType(T1: FromRecordType, T2: DestRecordType)) |
3179 | return From; |
3180 | } |
3181 | } |
3182 | |
3183 | CXXCastPath BasePath; |
3184 | if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType, |
3185 | Loc: FromLoc, Range: FromRange, BasePath: &BasePath, |
3186 | /*IgnoreAccess=*/true)) |
3187 | return ExprError(); |
3188 | |
3189 | // Propagate qualifiers to base subobjects as per: |
3190 | // C++ [basic.type.qualifier]p1.2: |
3191 | // A volatile object is [...] a subobject of a volatile object. |
3192 | Qualifiers FromTypeQuals = FromType.getQualifiers(); |
3193 | FromTypeQuals.setAddressSpace(DestType.getAddressSpace()); |
3194 | DestType = Context.getQualifiedType(T: DestType, Qs: FromTypeQuals); |
3195 | |
3196 | return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase, VK, |
3197 | BasePath: &BasePath); |
3198 | } |
3199 | |
3200 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, |
3201 | const LookupResult &R, |
3202 | bool HasTrailingLParen) { |
3203 | // Only when used directly as the postfix-expression of a call. |
3204 | if (!HasTrailingLParen) |
3205 | return false; |
3206 | |
3207 | // Never if a scope specifier was provided. |
3208 | if (SS.isNotEmpty()) |
3209 | return false; |
3210 | |
3211 | // Only in C++ or ObjC++. |
3212 | if (!getLangOpts().CPlusPlus) |
3213 | return false; |
3214 | |
3215 | // Turn off ADL when we find certain kinds of declarations during |
3216 | // normal lookup: |
3217 | for (const NamedDecl *D : R) { |
3218 | // C++0x [basic.lookup.argdep]p3: |
3219 | // -- a declaration of a class member |
3220 | // Since using decls preserve this property, we check this on the |
3221 | // original decl. |
3222 | if (D->isCXXClassMember()) |
3223 | return false; |
3224 | |
3225 | // C++0x [basic.lookup.argdep]p3: |
3226 | // -- a block-scope function declaration that is not a |
3227 | // using-declaration |
3228 | // NOTE: we also trigger this for function templates (in fact, we |
3229 | // don't check the decl type at all, since all other decl types |
3230 | // turn off ADL anyway). |
3231 | if (isa<UsingShadowDecl>(Val: D)) |
3232 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
3233 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) |
3234 | return false; |
3235 | |
3236 | // C++0x [basic.lookup.argdep]p3: |
3237 | // -- a declaration that is neither a function or a function |
3238 | // template |
3239 | // And also for builtin functions. |
3240 | if (const auto *FDecl = dyn_cast<FunctionDecl>(Val: D)) { |
3241 | // But also builtin functions. |
3242 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) |
3243 | return false; |
3244 | } else if (!isa<FunctionTemplateDecl>(Val: D)) |
3245 | return false; |
3246 | } |
3247 | |
3248 | return true; |
3249 | } |
3250 | |
3251 | |
3252 | /// Diagnoses obvious problems with the use of the given declaration |
3253 | /// as an expression. This is only actually called for lookups that |
3254 | /// were not overloaded, and it doesn't promise that the declaration |
3255 | /// will in fact be used. |
3256 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, |
3257 | bool AcceptInvalid) { |
3258 | if (D->isInvalidDecl() && !AcceptInvalid) |
3259 | return true; |
3260 | |
3261 | if (isa<TypedefNameDecl>(Val: D)) { |
3262 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); |
3263 | return true; |
3264 | } |
3265 | |
3266 | if (isa<ObjCInterfaceDecl>(Val: D)) { |
3267 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); |
3268 | return true; |
3269 | } |
3270 | |
3271 | if (isa<NamespaceDecl>(Val: D)) { |
3272 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); |
3273 | return true; |
3274 | } |
3275 | |
3276 | return false; |
3277 | } |
3278 | |
3279 | // Certain multiversion types should be treated as overloaded even when there is |
3280 | // only one result. |
3281 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { |
3282 | assert(R.isSingleResult() && "Expected only a single result"); |
3283 | const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl()); |
3284 | return FD && |
3285 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); |
3286 | } |
3287 | |
3288 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
3289 | LookupResult &R, bool NeedsADL, |
3290 | bool AcceptInvalidDecl) { |
3291 | // If this is a single, fully-resolved result and we don't need ADL, |
3292 | // just build an ordinary singleton decl ref. |
3293 | if (!NeedsADL && R.isSingleResult() && |
3294 | !R.getAsSingle<FunctionTemplateDecl>() && |
3295 | !ShouldLookupResultBeMultiVersionOverload(R)) |
3296 | return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(), |
3297 | FoundD: R.getRepresentativeDecl(), TemplateArgs: nullptr, |
3298 | AcceptInvalidDecl); |
3299 | |
3300 | // We only need to check the declaration if there's exactly one |
3301 | // result, because in the overloaded case the results can only be |
3302 | // functions and function templates. |
3303 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && |
3304 | CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(), |
3305 | AcceptInvalid: AcceptInvalidDecl)) |
3306 | return ExprError(); |
3307 | |
3308 | // Otherwise, just build an unresolved lookup expression. Suppress |
3309 | // any lookup-related diagnostics; we'll hash these out later, when |
3310 | // we've picked a target. |
3311 | R.suppressDiagnostics(); |
3312 | |
3313 | UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( |
3314 | Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context), |
3315 | NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(), |
3316 | /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false); |
3317 | |
3318 | return ULE; |
3319 | } |
3320 | |
3321 | static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, |
3322 | SourceLocation loc, |
3323 | ValueDecl *var); |
3324 | |
3325 | ExprResult Sema::BuildDeclarationNameExpr( |
3326 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
3327 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, |
3328 | bool AcceptInvalidDecl) { |
3329 | assert(D && "Cannot refer to a NULL declaration"); |
3330 | assert(!isa<FunctionTemplateDecl>(D) && |
3331 | "Cannot refer unambiguously to a function template"); |
3332 | |
3333 | SourceLocation Loc = NameInfo.getLoc(); |
3334 | if (CheckDeclInExpr(S&: *this, Loc, D, AcceptInvalid: AcceptInvalidDecl)) { |
3335 | // Recovery from invalid cases (e.g. D is an invalid Decl). |
3336 | // We use the dependent type for the RecoveryExpr to prevent bogus follow-up |
3337 | // diagnostics, as invalid decls use int as a fallback type. |
3338 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}); |
3339 | } |
3340 | |
3341 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D)) { |
3342 | // Specifically diagnose references to class templates that are missing |
3343 | // a template argument list. |
3344 | diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc); |
3345 | return ExprError(); |
3346 | } |
3347 | |
3348 | // Make sure that we're referring to a value. |
3349 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: D)) { |
3350 | Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); |
3351 | Diag(D->getLocation(), diag::note_declared_at); |
3352 | return ExprError(); |
3353 | } |
3354 | |
3355 | // Check whether this declaration can be used. Note that we suppress |
3356 | // this check when we're going to perform argument-dependent lookup |
3357 | // on this function name, because this might not be the function |
3358 | // that overload resolution actually selects. |
3359 | if (DiagnoseUseOfDecl(D, Locs: Loc)) |
3360 | return ExprError(); |
3361 | |
3362 | auto *VD = cast<ValueDecl>(Val: D); |
3363 | |
3364 | // Only create DeclRefExpr's for valid Decl's. |
3365 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) |
3366 | return ExprError(); |
3367 | |
3368 | // Handle members of anonymous structs and unions. If we got here, |
3369 | // and the reference is to a class member indirect field, then this |
3370 | // must be the subject of a pointer-to-member expression. |
3371 | if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(Val: VD); |
3372 | IndirectField && !IndirectField->isCXXClassMember()) |
3373 | return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(), |
3374 | indirectField: IndirectField); |
3375 | |
3376 | QualType type = VD->getType(); |
3377 | if (type.isNull()) |
3378 | return ExprError(); |
3379 | ExprValueKind valueKind = VK_PRValue; |
3380 | |
3381 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of |
3382 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, |
3383 | // is expanded by some outer '...' in the context of the use. |
3384 | type = type.getNonPackExpansionType(); |
3385 | |
3386 | switch (D->getKind()) { |
3387 | // Ignore all the non-ValueDecl kinds. |
3388 | #define ABSTRACT_DECL(kind) |
3389 | #define VALUE(type, base) |
3390 | #define DECL(type, base) case Decl::type: |
3391 | #include "clang/AST/DeclNodes.inc" |
3392 | llvm_unreachable("invalid value decl kind"); |
3393 | |
3394 | // These shouldn't make it here. |
3395 | case Decl::ObjCAtDefsField: |
3396 | llvm_unreachable("forming non-member reference to ivar?"); |
3397 | |
3398 | // Enum constants are always r-values and never references. |
3399 | // Unresolved using declarations are dependent. |
3400 | case Decl::EnumConstant: |
3401 | case Decl::UnresolvedUsingValue: |
3402 | case Decl::OMPDeclareReduction: |
3403 | case Decl::OMPDeclareMapper: |
3404 | valueKind = VK_PRValue; |
3405 | break; |
3406 | |
3407 | // Fields and indirect fields that got here must be for |
3408 | // pointer-to-member expressions; we just call them l-values for |
3409 | // internal consistency, because this subexpression doesn't really |
3410 | // exist in the high-level semantics. |
3411 | case Decl::Field: |
3412 | case Decl::IndirectField: |
3413 | case Decl::ObjCIvar: |
3414 | assert((getLangOpts().CPlusPlus || isAttrContext()) && |
3415 | "building reference to field in C?"); |
3416 | |
3417 | // These can't have reference type in well-formed programs, but |
3418 | // for internal consistency we do this anyway. |
3419 | type = type.getNonReferenceType(); |
3420 | valueKind = VK_LValue; |
3421 | break; |
3422 | |
3423 | // Non-type template parameters are either l-values or r-values |
3424 | // depending on the type. |
3425 | case Decl::NonTypeTemplateParm: { |
3426 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { |
3427 | type = reftype->getPointeeType(); |
3428 | valueKind = VK_LValue; // even if the parameter is an r-value reference |
3429 | break; |
3430 | } |
3431 | |
3432 | // [expr.prim.id.unqual]p2: |
3433 | // If the entity is a template parameter object for a template |
3434 | // parameter of type T, the type of the expression is const T. |
3435 | // [...] The expression is an lvalue if the entity is a [...] template |
3436 | // parameter object. |
3437 | if (type->isRecordType()) { |
3438 | type = type.getUnqualifiedType().withConst(); |
3439 | valueKind = VK_LValue; |
3440 | break; |
3441 | } |
3442 | |
3443 | // For non-references, we need to strip qualifiers just in case |
3444 | // the template parameter was declared as 'const int' or whatever. |
3445 | valueKind = VK_PRValue; |
3446 | type = type.getUnqualifiedType(); |
3447 | break; |
3448 | } |
3449 | |
3450 | case Decl::Var: |
3451 | case Decl::VarTemplateSpecialization: |
3452 | case Decl::VarTemplatePartialSpecialization: |
3453 | case Decl::Decomposition: |
3454 | case Decl::Binding: |
3455 | case Decl::OMPCapturedExpr: |
3456 | // In C, "extern void blah;" is valid and is an r-value. |
3457 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && |
3458 | type->isVoidType()) { |
3459 | valueKind = VK_PRValue; |
3460 | break; |
3461 | } |
3462 | [[fallthrough]]; |
3463 | |
3464 | case Decl::ImplicitParam: |
3465 | case Decl::ParmVar: { |
3466 | // These are always l-values. |
3467 | valueKind = VK_LValue; |
3468 | type = type.getNonReferenceType(); |
3469 | |
3470 | // FIXME: Does the addition of const really only apply in |
3471 | // potentially-evaluated contexts? Since the variable isn't actually |
3472 | // captured in an unevaluated context, it seems that the answer is no. |
3473 | if (!isUnevaluatedContext()) { |
3474 | QualType CapturedType = getCapturedDeclRefType(Var: cast<ValueDecl>(VD), Loc); |
3475 | if (!CapturedType.isNull()) |
3476 | type = CapturedType; |
3477 | } |
3478 | break; |
3479 | } |
3480 | |
3481 | case Decl::Function: { |
3482 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { |
3483 | if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) { |
3484 | type = Context.BuiltinFnTy; |
3485 | valueKind = VK_PRValue; |
3486 | break; |
3487 | } |
3488 | } |
3489 | |
3490 | const FunctionType *fty = type->castAs<FunctionType>(); |
3491 | |
3492 | // If we're referring to a function with an __unknown_anytype |
3493 | // result type, make the entire expression __unknown_anytype. |
3494 | if (fty->getReturnType() == Context.UnknownAnyTy) { |
3495 | type = Context.UnknownAnyTy; |
3496 | valueKind = VK_PRValue; |
3497 | break; |
3498 | } |
3499 | |
3500 | // Functions are l-values in C++. |
3501 | if (getLangOpts().CPlusPlus) { |
3502 | valueKind = VK_LValue; |
3503 | break; |
3504 | } |
3505 | |
3506 | // C99 DR 316 says that, if a function type comes from a |
3507 | // function definition (without a prototype), that type is only |
3508 | // used for checking compatibility. Therefore, when referencing |
3509 | // the function, we pretend that we don't have the full function |
3510 | // type. |
3511 | if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) |
3512 | type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(), |
3513 | Info: fty->getExtInfo()); |
3514 | |
3515 | // Functions are r-values in C. |
3516 | valueKind = VK_PRValue; |
3517 | break; |
3518 | } |
3519 | |
3520 | case Decl::CXXDeductionGuide: |
3521 | llvm_unreachable("building reference to deduction guide"); |
3522 | |
3523 | case Decl::MSProperty: |
3524 | case Decl::MSGuid: |
3525 | case Decl::TemplateParamObject: |
3526 | // FIXME: Should MSGuidDecl and template parameter objects be subject to |
3527 | // capture in OpenMP, or duplicated between host and device? |
3528 | valueKind = VK_LValue; |
3529 | break; |
3530 | |
3531 | case Decl::UnnamedGlobalConstant: |
3532 | valueKind = VK_LValue; |
3533 | break; |
3534 | |
3535 | case Decl::CXXMethod: |
3536 | // If we're referring to a method with an __unknown_anytype |
3537 | // result type, make the entire expression __unknown_anytype. |
3538 | // This should only be possible with a type written directly. |
3539 | if (const FunctionProtoType *proto = |
3540 | dyn_cast<FunctionProtoType>(VD->getType())) |
3541 | if (proto->getReturnType() == Context.UnknownAnyTy) { |
3542 | type = Context.UnknownAnyTy; |
3543 | valueKind = VK_PRValue; |
3544 | break; |
3545 | } |
3546 | |
3547 | // C++ methods are l-values if static, r-values if non-static. |
3548 | if (cast<CXXMethodDecl>(VD)->isStatic()) { |
3549 | valueKind = VK_LValue; |
3550 | break; |
3551 | } |
3552 | [[fallthrough]]; |
3553 | |
3554 | case Decl::CXXConversion: |
3555 | case Decl::CXXDestructor: |
3556 | case Decl::CXXConstructor: |
3557 | valueKind = VK_PRValue; |
3558 | break; |
3559 | } |
3560 | |
3561 | auto *E = |
3562 | BuildDeclRefExpr(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD, |
3563 | /*FIXME: TemplateKWLoc*/ TemplateKWLoc: SourceLocation(), TemplateArgs); |
3564 | // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We |
3565 | // wrap a DeclRefExpr referring to an invalid decl with a dependent-type |
3566 | // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus |
3567 | // diagnostics). |
3568 | if (VD->isInvalidDecl() && E) |
3569 | return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E}); |
3570 | return E; |
3571 | } |
3572 | |
3573 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, |
3574 | SmallString<32> &Target) { |
3575 | Target.resize(N: CharByteWidth * (Source.size() + 1)); |
3576 | char *ResultPtr = &Target[0]; |
3577 | const llvm::UTF8 *ErrorPtr; |
3578 | bool success = |
3579 | llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr); |
3580 | (void)success; |
3581 | assert(success); |
3582 | Target.resize(N: ResultPtr - &Target[0]); |
3583 | } |
3584 | |
3585 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, |
3586 | PredefinedIdentKind IK) { |
3587 | Decl *currentDecl = getPredefinedExprDecl(DC: CurContext); |
3588 | if (!currentDecl) { |
3589 | Diag(Loc, diag::ext_predef_outside_function); |
3590 | currentDecl = Context.getTranslationUnitDecl(); |
3591 | } |
3592 | |
3593 | QualType ResTy; |
3594 | StringLiteral *SL = nullptr; |
3595 | if (cast<DeclContext>(Val: currentDecl)->isDependentContext()) |
3596 | ResTy = Context.DependentTy; |
3597 | else { |
3598 | // Pre-defined identifiers are of type char[x], where x is the length of |
3599 | // the string. |
3600 | bool ForceElaboratedPrinting = |
3601 | IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat; |
3602 | auto Str = |
3603 | PredefinedExpr::ComputeName(IK, CurrentDecl: currentDecl, ForceElaboratedPrinting); |
3604 | unsigned Length = Str.length(); |
3605 | |
3606 | llvm::APInt LengthI(32, Length + 1); |
3607 | if (IK == PredefinedIdentKind::LFunction || |
3608 | IK == PredefinedIdentKind::LFuncSig) { |
3609 | ResTy = |
3610 | Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst()); |
3611 | SmallString<32> RawChars; |
3612 | ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(), |
3613 | Source: Str, Target&: RawChars); |
3614 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
3615 | ASM: ArraySizeModifier::Normal, |
3616 | /*IndexTypeQuals*/ 0); |
3617 | SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide, |
3618 | /*Pascal*/ false, Ty: ResTy, Loc); |
3619 | } else { |
3620 | ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()); |
3621 | ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr, |
3622 | ASM: ArraySizeModifier::Normal, |
3623 | /*IndexTypeQuals*/ 0); |
3624 | SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary, |
3625 | /*Pascal*/ false, Ty: ResTy, Loc); |
3626 | } |
3627 | } |
3628 | |
3629 | return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt, |
3630 | SL); |
3631 | } |
3632 | |
3633 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { |
3634 | return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind)); |
3635 | } |
3636 | |
3637 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { |
3638 | SmallString<16> CharBuffer; |
3639 | bool Invalid = false; |
3640 | StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &Invalid); |
3641 | if (Invalid) |
3642 | return ExprError(); |
3643 | |
3644 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), |
3645 | PP, Tok.getKind()); |
3646 | if (Literal.hadError()) |
3647 | return ExprError(); |
3648 | |
3649 | QualType Ty; |
3650 | if (Literal.isWide()) |
3651 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. |
3652 | else if (Literal.isUTF8() && getLangOpts().C23) |
3653 | Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23 |
3654 | else if (Literal.isUTF8() && getLangOpts().Char8) |
3655 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. |
3656 | else if (Literal.isUTF16()) |
3657 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. |
3658 | else if (Literal.isUTF32()) |
3659 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. |
3660 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) |
3661 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. |
3662 | else |
3663 | Ty = Context.CharTy; // 'x' -> char in C++; |
3664 | // u8'x' -> char in C11-C17 and in C++ without char8_t. |
3665 | |
3666 | CharacterLiteralKind Kind = CharacterLiteralKind::Ascii; |
3667 | if (Literal.isWide()) |
3668 | Kind = CharacterLiteralKind::Wide; |
3669 | else if (Literal.isUTF16()) |
3670 | Kind = CharacterLiteralKind::UTF16; |
3671 | else if (Literal.isUTF32()) |
3672 | Kind = CharacterLiteralKind::UTF32; |
3673 | else if (Literal.isUTF8()) |
3674 | Kind = CharacterLiteralKind::UTF8; |
3675 | |
3676 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, |
3677 | Tok.getLocation()); |
3678 | |
3679 | if (Literal.getUDSuffix().empty()) |
3680 | return Lit; |
3681 | |
3682 | // We're building a user-defined literal. |
3683 | IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
3684 | SourceLocation UDSuffixLoc = |
3685 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
3686 | |
3687 | // Make sure we're allowed user-defined literals here. |
3688 | if (!UDLScope) |
3689 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); |
3690 | |
3691 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form |
3692 | // operator "" X (ch) |
3693 | return BuildCookedLiteralOperatorCall(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc, |
3694 | Args: Lit, LitEndLoc: Tok.getLocation()); |
3695 | } |
3696 | |
3697 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) { |
3698 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
3699 | return IntegerLiteral::Create(Context, |
3700 | llvm::APInt(IntSize, Val, /*isSigned=*/true), |
3701 | Context.IntTy, Loc); |
3702 | } |
3703 | |
3704 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, |
3705 | QualType Ty, SourceLocation Loc) { |
3706 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty); |
3707 | |
3708 | using llvm::APFloat; |
3709 | APFloat Val(Format); |
3710 | |
3711 | llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode(); |
3712 | if (RM == llvm::RoundingMode::Dynamic) |
3713 | RM = llvm::RoundingMode::NearestTiesToEven; |
3714 | APFloat::opStatus result = Literal.GetFloatValue(Result&: Val, RM); |
3715 | |
3716 | // Overflow is always an error, but underflow is only an error if |
3717 | // we underflowed to zero (APFloat reports denormals as underflow). |
3718 | if ((result & APFloat::opOverflow) || |
3719 | ((result & APFloat::opUnderflow) && Val.isZero())) { |
3720 | unsigned diagnostic; |
3721 | SmallString<20> buffer; |
3722 | if (result & APFloat::opOverflow) { |
3723 | diagnostic = diag::warn_float_overflow; |
3724 | APFloat::getLargest(Sem: Format).toString(Str&: buffer); |
3725 | } else { |
3726 | diagnostic = diag::warn_float_underflow; |
3727 | APFloat::getSmallest(Sem: Format).toString(Str&: buffer); |
3728 | } |
3729 | |
3730 | S.Diag(Loc, diagnostic) << Ty << buffer.str(); |
3731 | } |
3732 | |
3733 | bool isExact = (result == APFloat::opOK); |
3734 | return FloatingLiteral::Create(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: Loc); |
3735 | } |
3736 | |
3737 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) { |
3738 | assert(E && "Invalid expression"); |
3739 | |
3740 | if (E->isValueDependent()) |
3741 | return false; |
3742 | |
3743 | QualType QT = E->getType(); |
3744 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { |
3745 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; |
3746 | return true; |
3747 | } |
3748 | |
3749 | llvm::APSInt ValueAPS; |
3750 | ExprResult R = VerifyIntegerConstantExpression(E, Result: &ValueAPS); |
3751 | |
3752 | if (R.isInvalid()) |
3753 | return true; |
3754 | |
3755 | // GCC allows the value of unroll count to be 0. |
3756 | // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says |
3757 | // "The values of 0 and 1 block any unrolling of the loop." |
3758 | // The values doesn't have to be strictly positive in '#pragma GCC unroll' and |
3759 | // '#pragma unroll' cases. |
3760 | bool ValueIsPositive = |
3761 | AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive(); |
3762 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { |
3763 | Diag(E->getExprLoc(), diag::err_requires_positive_value) |
3764 | << toString(ValueAPS, 10) << ValueIsPositive; |
3765 | return true; |
3766 | } |
3767 | |
3768 | return false; |
3769 | } |
3770 | |
3771 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { |
3772 | // Fast path for a single digit (which is quite common). A single digit |
3773 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. |
3774 | if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) { |
3775 | const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); |
3776 | return ActOnIntegerConstant(Loc: Tok.getLocation(), Val); |
3777 | } |
3778 | |
3779 | SmallString<128> SpellingBuffer; |
3780 | // NumericLiteralParser wants to overread by one character. Add padding to |
3781 | // the buffer in case the token is copied to the buffer. If getSpelling() |
3782 | // returns a StringRef to the memory buffer, it should have a null char at |
3783 | // the EOF, so it is also safe. |
3784 | SpellingBuffer.resize(N: Tok.getLength() + 1); |
3785 | |
3786 | // Get the spelling of the token, which eliminates trigraphs, etc. |
3787 | bool Invalid = false; |
3788 | StringRef TokSpelling = PP.getSpelling(Tok, Buffer&: SpellingBuffer, Invalid: &Invalid); |
3789 | if (Invalid) |
3790 | return ExprError(); |
3791 | |
3792 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), |
3793 | PP.getSourceManager(), PP.getLangOpts(), |
3794 | PP.getTargetInfo(), PP.getDiagnostics()); |
3795 | if (Literal.hadError) |
3796 | return ExprError(); |
3797 | |
3798 | if (Literal.hasUDSuffix()) { |
3799 | // We're building a user-defined literal. |
3800 | const IdentifierInfo *UDSuffix = &Context.Idents.get(Name: Literal.getUDSuffix()); |
3801 | SourceLocation UDSuffixLoc = |
3802 | getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: Literal.getUDSuffixOffset()); |
3803 | |
3804 | // Make sure we're allowed user-defined literals here. |
3805 | if (!UDLScope) |
3806 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); |
3807 | |
3808 | QualType CookedTy; |
3809 | if (Literal.isFloatingLiteral()) { |
3810 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type |
3811 | // long double, the literal is treated as a call of the form |
3812 | // operator "" X (f L) |
3813 | CookedTy = Context.LongDoubleTy; |
3814 | } else { |
3815 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type |
3816 | // unsigned long long, the literal is treated as a call of the form |
3817 | // operator "" X (n ULL) |
3818 | CookedTy = Context.UnsignedLongLongTy; |
3819 | } |
3820 | |
3821 | DeclarationName OpName = |
3822 | Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix); |
3823 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
3824 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
3825 | |
3826 | SourceLocation TokLoc = Tok.getLocation(); |
3827 | |
3828 | // Perform literal operator lookup to determine if we're building a raw |
3829 | // literal or a cooked one. |
3830 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
3831 | switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: CookedTy, |
3832 | /*AllowRaw*/ true, /*AllowTemplate*/ true, |
3833 | /*AllowStringTemplatePack*/ AllowStringTemplate: false, |
3834 | /*DiagnoseMissing*/ !Literal.isImaginary)) { |
3835 | case LOLR_ErrorNoDiagnostic: |
3836 | // Lookup failure for imaginary constants isn't fatal, there's still the |
3837 | // GNU extension producing _Complex types. |
3838 | break; |
3839 | case LOLR_Error: |
3840 | return ExprError(); |
3841 | case LOLR_Cooked: { |
3842 | Expr *Lit; |
3843 | if (Literal.isFloatingLiteral()) { |
3844 | Lit = BuildFloatingLiteral(S&: *this, Literal, Ty: CookedTy, Loc: Tok.getLocation()); |
3845 | } else { |
3846 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); |
3847 | if (Literal.GetIntegerValue(ResultVal)) |
3848 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
3849 | << /* Unsigned */ 1; |
3850 | Lit = IntegerLiteral::Create(C: Context, V: ResultVal, type: CookedTy, |
3851 | l: Tok.getLocation()); |
3852 | } |
3853 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
3854 | } |
3855 | |
3856 | case LOLR_Raw: { |
3857 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the |
3858 | // literal is treated as a call of the form |
3859 | // operator "" X ("n") |
3860 | unsigned Length = Literal.getUDSuffixOffset(); |
3861 | QualType StrTy = Context.getConstantArrayType( |
3862 | EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()), |
3863 | ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
3864 | Expr *Lit = |
3865 | StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length), |
3866 | Kind: StringLiteralKind::Ordinary, |
3867 | /*Pascal*/ false, Ty: StrTy, Loc: &TokLoc, NumConcatenated: 1); |
3868 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: TokLoc); |
3869 | } |
3870 | |
3871 | case LOLR_Template: { |
3872 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator |
3873 | // template), L is treated as a call fo the form |
3874 | // operator "" X <'c1', 'c2', ... 'ck'>() |
3875 | // where n is the source character sequence c1 c2 ... ck. |
3876 | TemplateArgumentListInfo ExplicitArgs; |
3877 | unsigned CharBits = Context.getIntWidth(T: Context.CharTy); |
3878 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); |
3879 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
3880 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { |
3881 | Value = TokSpelling[I]; |
3882 | TemplateArgument Arg(Context, Value, Context.CharTy); |
3883 | TemplateArgumentLocInfo ArgInfo; |
3884 | ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo)); |
3885 | } |
3886 | return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: {}, LitEndLoc: TokLoc, ExplicitTemplateArgs: &ExplicitArgs); |
3887 | } |
3888 | case LOLR_StringTemplatePack: |
3889 | llvm_unreachable("unexpected literal operator lookup result"); |
3890 | } |
3891 | } |
3892 | |
3893 | Expr *Res; |
3894 | |
3895 | if (Literal.isFixedPointLiteral()) { |
3896 | QualType Ty; |
3897 | |
3898 | if (Literal.isAccum) { |
3899 | if (Literal.isHalf) { |
3900 | Ty = Context.ShortAccumTy; |
3901 | } else if (Literal.isLong) { |
3902 | Ty = Context.LongAccumTy; |
3903 | } else { |
3904 | Ty = Context.AccumTy; |
3905 | } |
3906 | } else if (Literal.isFract) { |
3907 | if (Literal.isHalf) { |
3908 | Ty = Context.ShortFractTy; |
3909 | } else if (Literal.isLong) { |
3910 | Ty = Context.LongFractTy; |
3911 | } else { |
3912 | Ty = Context.FractTy; |
3913 | } |
3914 | } |
3915 | |
3916 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(T: Ty); |
3917 | |
3918 | bool isSigned = !Literal.isUnsigned; |
3919 | unsigned scale = Context.getFixedPointScale(Ty); |
3920 | unsigned bit_width = Context.getTypeInfo(T: Ty).Width; |
3921 | |
3922 | llvm::APInt Val(bit_width, 0, isSigned); |
3923 | bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: scale); |
3924 | bool ValIsZero = Val.isZero() && !Overflowed; |
3925 | |
3926 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); |
3927 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) |
3928 | // Clause 6.4.4 - The value of a constant shall be in the range of |
3929 | // representable values for its type, with exception for constants of a |
3930 | // fract type with a value of exactly 1; such a constant shall denote |
3931 | // the maximal value for the type. |
3932 | --Val; |
3933 | else if (Val.ugt(MaxVal) || Overflowed) |
3934 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); |
3935 | |
3936 | Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty, |
3937 | l: Tok.getLocation(), Scale: scale); |
3938 | } else if (Literal.isFloatingLiteral()) { |
3939 | QualType Ty; |
3940 | if (Literal.isHalf){ |
3941 | if (getLangOpts().HLSL || |
3942 | getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts())) |
3943 | Ty = Context.HalfTy; |
3944 | else { |
3945 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); |
3946 | return ExprError(); |
3947 | } |
3948 | } else if (Literal.isFloat) |
3949 | Ty = Context.FloatTy; |
3950 | else if (Literal.isLong) |
3951 | Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy; |
3952 | else if (Literal.isFloat16) |
3953 | Ty = Context.Float16Ty; |
3954 | else if (Literal.isFloat128) |
3955 | Ty = Context.Float128Ty; |
3956 | else if (getLangOpts().HLSL) |
3957 | Ty = Context.FloatTy; |
3958 | else |
3959 | Ty = Context.DoubleTy; |
3960 | |
3961 | Res = BuildFloatingLiteral(S&: *this, Literal, Ty, Loc: Tok.getLocation()); |
3962 | |
3963 | if (Ty == Context.DoubleTy) { |
3964 | if (getLangOpts().SinglePrecisionConstants) { |
3965 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { |
3966 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
3967 | } |
3968 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( |
3969 | Ext: "cl_khr_fp64", LO: getLangOpts())) { |
3970 | // Impose single-precision float type when cl_khr_fp64 is not enabled. |
3971 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) |
3972 | << (getLangOpts().getOpenCLCompatibleVersion() >= 300); |
3973 | Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
3974 | } |
3975 | } |
3976 | } else if (!Literal.isIntegerLiteral()) { |
3977 | return ExprError(); |
3978 | } else { |
3979 | QualType Ty; |
3980 | |
3981 | // 'z/uz' literals are a C++23 feature. |
3982 | if (Literal.isSizeT) |
3983 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus |
3984 | ? getLangOpts().CPlusPlus23 |
3985 | ? diag::warn_cxx20_compat_size_t_suffix |
3986 | : diag::ext_cxx23_size_t_suffix |
3987 | : diag::err_cxx23_size_t_suffix); |
3988 | |
3989 | // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++, |
3990 | // but we do not currently support the suffix in C++ mode because it's not |
3991 | // entirely clear whether WG21 will prefer this suffix to return a library |
3992 | // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb' |
3993 | // literals are a C++ extension. |
3994 | if (Literal.isBitInt) |
3995 | PP.Diag(Tok.getLocation(), |
3996 | getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix |
3997 | : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix |
3998 | : diag::ext_c23_bitint_suffix); |
3999 | |
4000 | // Get the value in the widest-possible width. What is "widest" depends on |
4001 | // whether the literal is a bit-precise integer or not. For a bit-precise |
4002 | // integer type, try to scan the source to determine how many bits are |
4003 | // needed to represent the value. This may seem a bit expensive, but trying |
4004 | // to get the integer value from an overly-wide APInt is *extremely* |
4005 | // expensive, so the naive approach of assuming |
4006 | // llvm::IntegerType::MAX_INT_BITS is a big performance hit. |
4007 | unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth(); |
4008 | if (Literal.isBitInt) |
4009 | BitsNeeded = llvm::APInt::getSufficientBitsNeeded( |
4010 | Str: Literal.getLiteralDigits(), Radix: Literal.getRadix()); |
4011 | if (Literal.MicrosoftInteger) { |
4012 | if (Literal.MicrosoftInteger == 128 && |
4013 | !Context.getTargetInfo().hasInt128Type()) |
4014 | PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
4015 | << Literal.isUnsigned; |
4016 | BitsNeeded = Literal.MicrosoftInteger; |
4017 | } |
4018 | |
4019 | llvm::APInt ResultVal(BitsNeeded, 0); |
4020 | |
4021 | if (Literal.GetIntegerValue(Val&: ResultVal)) { |
4022 | // If this value didn't fit into uintmax_t, error and force to ull. |
4023 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
4024 | << /* Unsigned */ 1; |
4025 | Ty = Context.UnsignedLongLongTy; |
4026 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && |
4027 | "long long is not intmax_t?"); |
4028 | } else { |
4029 | // If this value fits into a ULL, try to figure out what else it fits into |
4030 | // according to the rules of C99 6.4.4.1p5. |
4031 | |
4032 | // Octal, Hexadecimal, and integers with a U suffix are allowed to |
4033 | // be an unsigned int. |
4034 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; |
4035 | |
4036 | // HLSL doesn't really have `long` or `long long`. We support the `ll` |
4037 | // suffix for portability of code with C++, but both `l` and `ll` are |
4038 | // 64-bit integer types, and we want the type of `1l` and `1ll` to be the |
4039 | // same. |
4040 | if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) { |
4041 | Literal.isLong = true; |
4042 | Literal.isLongLong = false; |
4043 | } |
4044 | |
4045 | // Check from smallest to largest, picking the smallest type we can. |
4046 | unsigned Width = 0; |
4047 | |
4048 | // Microsoft specific integer suffixes are explicitly sized. |
4049 | if (Literal.MicrosoftInteger) { |
4050 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { |
4051 | Width = 8; |
4052 | Ty = Context.CharTy; |
4053 | } else { |
4054 | Width = Literal.MicrosoftInteger; |
4055 | Ty = Context.getIntTypeForBitwidth(DestWidth: Width, |
4056 | /*Signed=*/!Literal.isUnsigned); |
4057 | } |
4058 | } |
4059 | |
4060 | // Bit-precise integer literals are automagically-sized based on the |
4061 | // width required by the literal. |
4062 | if (Literal.isBitInt) { |
4063 | // The signed version has one more bit for the sign value. There are no |
4064 | // zero-width bit-precise integers, even if the literal value is 0. |
4065 | Width = std::max(a: ResultVal.getActiveBits(), b: 1u) + |
4066 | (Literal.isUnsigned ? 0u : 1u); |
4067 | |
4068 | // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, |
4069 | // and reset the type to the largest supported width. |
4070 | unsigned int MaxBitIntWidth = |
4071 | Context.getTargetInfo().getMaxBitIntWidth(); |
4072 | if (Width > MaxBitIntWidth) { |
4073 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
4074 | << Literal.isUnsigned; |
4075 | Width = MaxBitIntWidth; |
4076 | } |
4077 | |
4078 | // Reset the result value to the smaller APInt and select the correct |
4079 | // type to be used. Note, we zext even for signed values because the |
4080 | // literal itself is always an unsigned value (a preceeding - is a |
4081 | // unary operator, not part of the literal). |
4082 | ResultVal = ResultVal.zextOrTrunc(width: Width); |
4083 | Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: Width); |
4084 | } |
4085 | |
4086 | // Check C++23 size_t literals. |
4087 | if (Literal.isSizeT) { |
4088 | assert(!Literal.MicrosoftInteger && |
4089 | "size_t literals can't be Microsoft literals"); |
4090 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( |
4091 | T: Context.getTargetInfo().getSizeType()); |
4092 | |
4093 | // Does it fit in size_t? |
4094 | if (ResultVal.isIntN(N: SizeTSize)) { |
4095 | // Does it fit in ssize_t? |
4096 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) |
4097 | Ty = Context.getSignedSizeType(); |
4098 | else if (AllowUnsigned) |
4099 | Ty = Context.getSizeType(); |
4100 | Width = SizeTSize; |
4101 | } |
4102 | } |
4103 | |
4104 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && |
4105 | !Literal.isSizeT) { |
4106 | // Are int/unsigned possibilities? |
4107 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
4108 | |
4109 | // Does it fit in a unsigned int? |
4110 | if (ResultVal.isIntN(N: IntSize)) { |
4111 | // Does it fit in a signed int? |
4112 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) |
4113 | Ty = Context.IntTy; |
4114 | else if (AllowUnsigned) |
4115 | Ty = Context.UnsignedIntTy; |
4116 | Width = IntSize; |
4117 | } |
4118 | } |
4119 | |
4120 | // Are long/unsigned long possibilities? |
4121 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { |
4122 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); |
4123 | |
4124 | // Does it fit in a unsigned long? |
4125 | if (ResultVal.isIntN(N: LongSize)) { |
4126 | // Does it fit in a signed long? |
4127 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) |
4128 | Ty = Context.LongTy; |
4129 | else if (AllowUnsigned) |
4130 | Ty = Context.UnsignedLongTy; |
4131 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 |
4132 | // is compatible. |
4133 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { |
4134 | const unsigned LongLongSize = |
4135 | Context.getTargetInfo().getLongLongWidth(); |
4136 | Diag(Tok.getLocation(), |
4137 | getLangOpts().CPlusPlus |
4138 | ? Literal.isLong |
4139 | ? diag::warn_old_implicitly_unsigned_long_cxx |
4140 | : /*C++98 UB*/ diag:: |
4141 | ext_old_implicitly_unsigned_long_cxx |
4142 | : diag::warn_old_implicitly_unsigned_long) |
4143 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 |
4144 | : /*will be ill-formed*/ 1); |
4145 | Ty = Context.UnsignedLongTy; |
4146 | } |
4147 | Width = LongSize; |
4148 | } |
4149 | } |
4150 | |
4151 | // Check long long if needed. |
4152 | if (Ty.isNull() && !Literal.isSizeT) { |
4153 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); |
4154 | |
4155 | // Does it fit in a unsigned long long? |
4156 | if (ResultVal.isIntN(N: LongLongSize)) { |
4157 | // Does it fit in a signed long long? |
4158 | // To be compatible with MSVC, hex integer literals ending with the |
4159 | // LL or i64 suffix are always signed in Microsoft mode. |
4160 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || |
4161 | (getLangOpts().MSVCCompat && Literal.isLongLong))) |
4162 | Ty = Context.LongLongTy; |
4163 | else if (AllowUnsigned) |
4164 | Ty = Context.UnsignedLongLongTy; |
4165 | Width = LongLongSize; |
4166 | |
4167 | // 'long long' is a C99 or C++11 feature, whether the literal |
4168 | // explicitly specified 'long long' or we needed the extra width. |
4169 | if (getLangOpts().CPlusPlus) |
4170 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 |
4171 | ? diag::warn_cxx98_compat_longlong |
4172 | : diag::ext_cxx11_longlong); |
4173 | else if (!getLangOpts().C99) |
4174 | Diag(Tok.getLocation(), diag::ext_c99_longlong); |
4175 | } |
4176 | } |
4177 | |
4178 | // If we still couldn't decide a type, we either have 'size_t' literal |
4179 | // that is out of range, or a decimal literal that does not fit in a |
4180 | // signed long long and has no U suffix. |
4181 | if (Ty.isNull()) { |
4182 | if (Literal.isSizeT) |
4183 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) |
4184 | << Literal.isUnsigned; |
4185 | else |
4186 | Diag(Tok.getLocation(), |
4187 | diag::ext_integer_literal_too_large_for_signed); |
4188 | Ty = Context.UnsignedLongLongTy; |
4189 | Width = Context.getTargetInfo().getLongLongWidth(); |
4190 | } |
4191 | |
4192 | if (ResultVal.getBitWidth() != Width) |
4193 | ResultVal = ResultVal.trunc(width: Width); |
4194 | } |
4195 | Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: Tok.getLocation()); |
4196 | } |
4197 | |
4198 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. |
4199 | if (Literal.isImaginary) { |
4200 | Res = new (Context) ImaginaryLiteral(Res, |
4201 | Context.getComplexType(T: Res->getType())); |
4202 | |
4203 | // In C++, this is a GNU extension. In C, it's a C2y extension. |
4204 | unsigned DiagId; |
4205 | if (getLangOpts().CPlusPlus) |
4206 | DiagId = diag::ext_gnu_imaginary_constant; |
4207 | else if (getLangOpts().C2y) |
4208 | DiagId = diag::warn_c23_compat_imaginary_constant; |
4209 | else |
4210 | DiagId = diag::ext_c2y_imaginary_constant; |
4211 | Diag(Tok.getLocation(), DiagId); |
4212 | } |
4213 | return Res; |
4214 | } |
4215 | |
4216 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { |
4217 | assert(E && "ActOnParenExpr() missing expr"); |
4218 | QualType ExprTy = E->getType(); |
4219 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && |
4220 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) |
4221 | return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); |
4222 | return new (Context) ParenExpr(L, R, E); |
4223 | } |
4224 | |
4225 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, |
4226 | SourceLocation Loc, |
4227 | SourceRange ArgRange) { |
4228 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in |
4229 | // scalar or vector data type argument..." |
4230 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic |
4231 | // type (C99 6.2.5p18) or void. |
4232 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { |
4233 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) |
4234 | << T << ArgRange; |
4235 | return true; |
4236 | } |
4237 | |
4238 | assert((T->isVoidType() || !T->isIncompleteType()) && |
4239 | "Scalar types should always be complete"); |
4240 | return false; |
4241 | } |
4242 | |
4243 | static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, |
4244 | SourceLocation Loc, |
4245 | SourceRange ArgRange) { |
4246 | // builtin_vectorelements supports both fixed-sized and scalable vectors. |
4247 | if (!T->isVectorType() && !T->isSizelessVectorType()) |
4248 | return S.Diag(Loc, diag::err_builtin_non_vector_type) |
4249 | << "" |
4250 | << "__builtin_vectorelements"<< T << ArgRange; |
4251 | |
4252 | return false; |
4253 | } |
4254 | |
4255 | static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, |
4256 | SourceLocation Loc, |
4257 | SourceRange ArgRange) { |
4258 | if (S.checkPointerAuthEnabled(Loc, Range: ArgRange)) |
4259 | return true; |
4260 | |
4261 | if (!T->isFunctionType() && !T->isFunctionPointerType() && |
4262 | !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) { |
4263 | S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange; |
4264 | return true; |
4265 | } |
4266 | |
4267 | return false; |
4268 | } |
4269 | |
4270 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, |
4271 | SourceLocation Loc, |
4272 | SourceRange ArgRange, |
4273 | UnaryExprOrTypeTrait TraitKind) { |
4274 | // Invalid types must be hard errors for SFINAE in C++. |
4275 | if (S.LangOpts.CPlusPlus) |
4276 | return true; |
4277 | |
4278 | // C99 6.5.3.4p1: |
4279 | if (T->isFunctionType() && |
4280 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || |
4281 | TraitKind == UETT_PreferredAlignOf)) { |
4282 | // sizeof(function)/alignof(function) is allowed as an extension. |
4283 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) |
4284 | << getTraitSpelling(TraitKind) << ArgRange; |
4285 | return false; |
4286 | } |
4287 | |
4288 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where |
4289 | // this is an error (OpenCL v1.1 s6.3.k) |
4290 | if (T->isVoidType()) { |
4291 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type |
4292 | : diag::ext_sizeof_alignof_void_type; |
4293 | S.Diag(Loc, DiagID) << getTraitSpelling(T: TraitKind) << ArgRange; |
4294 | return false; |
4295 | } |
4296 | |
4297 | return true; |
4298 | } |
4299 | |
4300 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, |
4301 | SourceLocation Loc, |
4302 | SourceRange ArgRange, |
4303 | UnaryExprOrTypeTrait TraitKind) { |
4304 | // Reject sizeof(interface) and sizeof(interface<proto>) if the |
4305 | // runtime doesn't allow it. |
4306 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { |
4307 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) |
4308 | << T << (TraitKind == UETT_SizeOf) |
4309 | << ArgRange; |
4310 | return true; |
4311 | } |
4312 | |
4313 | return false; |
4314 | } |
4315 | |
4316 | /// Check whether E is a pointer from a decayed array type (the decayed |
4317 | /// pointer type is equal to T) and emit a warning if it is. |
4318 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, |
4319 | const Expr *E) { |
4320 | // Don't warn if the operation changed the type. |
4321 | if (T != E->getType()) |
4322 | return; |
4323 | |
4324 | // Now look for array decays. |
4325 | const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E); |
4326 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) |
4327 | return; |
4328 | |
4329 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() |
4330 | << ICE->getType() |
4331 | << ICE->getSubExpr()->getType(); |
4332 | } |
4333 | |
4334 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, |
4335 | UnaryExprOrTypeTrait ExprKind) { |
4336 | QualType ExprTy = E->getType(); |
4337 | assert(!ExprTy->isReferenceType()); |
4338 | |
4339 | bool IsUnevaluatedOperand = |
4340 | (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf || |
4341 | ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
4342 | ExprKind == UETT_VecStep || ExprKind == UETT_CountOf); |
4343 | if (IsUnevaluatedOperand) { |
4344 | ExprResult Result = CheckUnevaluatedOperand(E); |
4345 | if (Result.isInvalid()) |
4346 | return true; |
4347 | E = Result.get(); |
4348 | } |
4349 | |
4350 | // The operand for sizeof and alignof is in an unevaluated expression context, |
4351 | // so side effects could result in unintended consequences. |
4352 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes |
4353 | // used to build SFINAE gadgets. |
4354 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? |
4355 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && |
4356 | !E->isInstantiationDependent() && |
4357 | !E->getType()->isVariableArrayType() && |
4358 | E->HasSideEffects(Context, false)) |
4359 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
4360 | |
4361 | if (ExprKind == UETT_VecStep) |
4362 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), |
4363 | E->getSourceRange()); |
4364 | |
4365 | if (ExprKind == UETT_VectorElements) |
4366 | return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(), |
4367 | E->getSourceRange()); |
4368 | |
4369 | // Explicitly list some types as extensions. |
4370 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), |
4371 | E->getSourceRange(), ExprKind)) |
4372 | return false; |
4373 | |
4374 | // WebAssembly tables are always illegal operands to unary expressions and |
4375 | // type traits. |
4376 | if (Context.getTargetInfo().getTriple().isWasm() && |
4377 | E->getType()->isWebAssemblyTableType()) { |
4378 | Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand) |
4379 | << getTraitSpelling(ExprKind); |
4380 | return true; |
4381 | } |
4382 | |
4383 | // 'alignof' applied to an expression only requires the base element type of |
4384 | // the expression to be complete. 'sizeof' requires the expression's type to |
4385 | // be complete (and will attempt to complete it if it's an array of unknown |
4386 | // bound). |
4387 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
4388 | if (RequireCompleteSizedType( |
4389 | E->getExprLoc(), Context.getBaseElementType(E->getType()), |
4390 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4391 | getTraitSpelling(ExprKind), E->getSourceRange())) |
4392 | return true; |
4393 | } else { |
4394 | if (RequireCompleteSizedExprType( |
4395 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4396 | getTraitSpelling(ExprKind), E->getSourceRange())) |
4397 | return true; |
4398 | } |
4399 | |
4400 | // Completing the expression's type may have changed it. |
4401 | ExprTy = E->getType(); |
4402 | assert(!ExprTy->isReferenceType()); |
4403 | |
4404 | if (ExprTy->isFunctionType()) { |
4405 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) |
4406 | << getTraitSpelling(ExprKind) << E->getSourceRange(); |
4407 | return true; |
4408 | } |
4409 | |
4410 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), |
4411 | E->getSourceRange(), ExprKind)) |
4412 | return true; |
4413 | |
4414 | if (ExprKind == UETT_CountOf) { |
4415 | // The type has to be an array type. We already checked for incomplete |
4416 | // types above. |
4417 | QualType ExprType = E->IgnoreParens()->getType(); |
4418 | if (!ExprType->isArrayType()) { |
4419 | Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType; |
4420 | return true; |
4421 | } |
4422 | // FIXME: warn on _Countof on an array parameter. Not warning on it |
4423 | // currently because there are papers in WG14 about array types which do |
4424 | // not decay that could impact this behavior, so we want to see if anything |
4425 | // changes here before coming up with a warning group for _Countof-related |
4426 | // diagnostics. |
4427 | } |
4428 | |
4429 | if (ExprKind == UETT_SizeOf) { |
4430 | if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) { |
4431 | if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DeclRef->getFoundDecl())) { |
4432 | QualType OType = PVD->getOriginalType(); |
4433 | QualType Type = PVD->getType(); |
4434 | if (Type->isPointerType() && OType->isArrayType()) { |
4435 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) |
4436 | << Type << OType; |
4437 | Diag(PVD->getLocation(), diag::note_declared_at); |
4438 | } |
4439 | } |
4440 | } |
4441 | |
4442 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array |
4443 | // decays into a pointer and returns an unintended result. This is most |
4444 | // likely a typo for "sizeof(array) op x". |
4445 | if (const auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParens())) { |
4446 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), |
4447 | BO->getLHS()); |
4448 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), |
4449 | BO->getRHS()); |
4450 | } |
4451 | } |
4452 | |
4453 | return false; |
4454 | } |
4455 | |
4456 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { |
4457 | // Cannot know anything else if the expression is dependent. |
4458 | if (E->isTypeDependent()) |
4459 | return false; |
4460 | |
4461 | if (E->getObjectKind() == OK_BitField) { |
4462 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) |
4463 | << 1 << E->getSourceRange(); |
4464 | return true; |
4465 | } |
4466 | |
4467 | ValueDecl *D = nullptr; |
4468 | Expr *Inner = E->IgnoreParens(); |
4469 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Inner)) { |
4470 | D = DRE->getDecl(); |
4471 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Inner)) { |
4472 | D = ME->getMemberDecl(); |
4473 | } |
4474 | |
4475 | // If it's a field, require the containing struct to have a |
4476 | // complete definition so that we can compute the layout. |
4477 | // |
4478 | // This can happen in C++11 onwards, either by naming the member |
4479 | // in a way that is not transformed into a member access expression |
4480 | // (in an unevaluated operand, for instance), or by naming the member |
4481 | // in a trailing-return-type. |
4482 | // |
4483 | // For the record, since __alignof__ on expressions is a GCC |
4484 | // extension, GCC seems to permit this but always gives the |
4485 | // nonsensical answer 0. |
4486 | // |
4487 | // We don't really need the layout here --- we could instead just |
4488 | // directly check for all the appropriate alignment-lowing |
4489 | // attributes --- but that would require duplicating a lot of |
4490 | // logic that just isn't worth duplicating for such a marginal |
4491 | // use-case. |
4492 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(Val: D)) { |
4493 | // Fast path this check, since we at least know the record has a |
4494 | // definition if we can find a member of it. |
4495 | if (!FD->getParent()->isCompleteDefinition()) { |
4496 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) |
4497 | << E->getSourceRange(); |
4498 | return true; |
4499 | } |
4500 | |
4501 | // Otherwise, if it's a field, and the field doesn't have |
4502 | // reference type, then it must have a complete type (or be a |
4503 | // flexible array member, which we explicitly want to |
4504 | // white-list anyway), which makes the following checks trivial. |
4505 | if (!FD->getType()->isReferenceType()) |
4506 | return false; |
4507 | } |
4508 | |
4509 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
4510 | } |
4511 | |
4512 | bool Sema::CheckVecStepExpr(Expr *E) { |
4513 | E = E->IgnoreParens(); |
4514 | |
4515 | // Cannot know anything else if the expression is dependent. |
4516 | if (E->isTypeDependent()) |
4517 | return false; |
4518 | |
4519 | return CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_VecStep); |
4520 | } |
4521 | |
4522 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, |
4523 | CapturingScopeInfo *CSI) { |
4524 | assert(T->isVariablyModifiedType()); |
4525 | assert(CSI != nullptr); |
4526 | |
4527 | // We're going to walk down into the type and look for VLA expressions. |
4528 | do { |
4529 | const Type *Ty = T.getTypePtr(); |
4530 | switch (Ty->getTypeClass()) { |
4531 | #define TYPE(Class, Base) |
4532 | #define ABSTRACT_TYPE(Class, Base) |
4533 | #define NON_CANONICAL_TYPE(Class, Base) |
4534 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
4535 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) |
4536 | #include "clang/AST/TypeNodes.inc" |
4537 | T = QualType(); |
4538 | break; |
4539 | // These types are never variably-modified. |
4540 | case Type::Builtin: |
4541 | case Type::Complex: |
4542 | case Type::Vector: |
4543 | case Type::ExtVector: |
4544 | case Type::ConstantMatrix: |
4545 | case Type::Record: |
4546 | case Type::Enum: |
4547 | case Type::TemplateSpecialization: |
4548 | case Type::ObjCObject: |
4549 | case Type::ObjCInterface: |
4550 | case Type::ObjCObjectPointer: |
4551 | case Type::ObjCTypeParam: |
4552 | case Type::Pipe: |
4553 | case Type::BitInt: |
4554 | case Type::HLSLInlineSpirv: |
4555 | llvm_unreachable("type class is never variably-modified!"); |
4556 | case Type::Elaborated: |
4557 | T = cast<ElaboratedType>(Ty)->getNamedType(); |
4558 | break; |
4559 | case Type::Adjusted: |
4560 | T = cast<AdjustedType>(Ty)->getOriginalType(); |
4561 | break; |
4562 | case Type::Decayed: |
4563 | T = cast<DecayedType>(Ty)->getPointeeType(); |
4564 | break; |
4565 | case Type::ArrayParameter: |
4566 | T = cast<ArrayParameterType>(Ty)->getElementType(); |
4567 | break; |
4568 | case Type::Pointer: |
4569 | T = cast<PointerType>(Ty)->getPointeeType(); |
4570 | break; |
4571 | case Type::BlockPointer: |
4572 | T = cast<BlockPointerType>(Ty)->getPointeeType(); |
4573 | break; |
4574 | case Type::LValueReference: |
4575 | case Type::RValueReference: |
4576 | T = cast<ReferenceType>(Ty)->getPointeeType(); |
4577 | break; |
4578 | case Type::MemberPointer: |
4579 | T = cast<MemberPointerType>(Ty)->getPointeeType(); |
4580 | break; |
4581 | case Type::ConstantArray: |
4582 | case Type::IncompleteArray: |
4583 | // Losing element qualification here is fine. |
4584 | T = cast<ArrayType>(Ty)->getElementType(); |
4585 | break; |
4586 | case Type::VariableArray: { |
4587 | // Losing element qualification here is fine. |
4588 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); |
4589 | |
4590 | // Unknown size indication requires no size computation. |
4591 | // Otherwise, evaluate and record it. |
4592 | auto Size = VAT->getSizeExpr(); |
4593 | if (Size && !CSI->isVLATypeCaptured(VAT) && |
4594 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) |
4595 | CSI->addVLATypeCapture(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: Context.getSizeType()); |
4596 | |
4597 | T = VAT->getElementType(); |
4598 | break; |
4599 | } |
4600 | case Type::FunctionProto: |
4601 | case Type::FunctionNoProto: |
4602 | T = cast<FunctionType>(Ty)->getReturnType(); |
4603 | break; |
4604 | case Type::Paren: |
4605 | case Type::TypeOf: |
4606 | case Type::UnaryTransform: |
4607 | case Type::Attributed: |
4608 | case Type::BTFTagAttributed: |
4609 | case Type::HLSLAttributedResource: |
4610 | case Type::SubstTemplateTypeParm: |
4611 | case Type::MacroQualified: |
4612 | case Type::CountAttributed: |
4613 | // Keep walking after single level desugaring. |
4614 | T = T.getSingleStepDesugaredType(Context); |
4615 | break; |
4616 | case Type::Typedef: |
4617 | T = cast<TypedefType>(Ty)->desugar(); |
4618 | break; |
4619 | case Type::Decltype: |
4620 | T = cast<DecltypeType>(Ty)->desugar(); |
4621 | break; |
4622 | case Type::PackIndexing: |
4623 | T = cast<PackIndexingType>(Ty)->desugar(); |
4624 | break; |
4625 | case Type::Using: |
4626 | T = cast<UsingType>(Ty)->desugar(); |
4627 | break; |
4628 | case Type::Auto: |
4629 | case Type::DeducedTemplateSpecialization: |
4630 | T = cast<DeducedType>(Ty)->getDeducedType(); |
4631 | break; |
4632 | case Type::TypeOfExpr: |
4633 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); |
4634 | break; |
4635 | case Type::Atomic: |
4636 | T = cast<AtomicType>(Ty)->getValueType(); |
4637 | break; |
4638 | } |
4639 | } while (!T.isNull() && T->isVariablyModifiedType()); |
4640 | } |
4641 | |
4642 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, |
4643 | SourceLocation OpLoc, |
4644 | SourceRange ExprRange, |
4645 | UnaryExprOrTypeTrait ExprKind, |
4646 | StringRef KWName) { |
4647 | if (ExprType->isDependentType()) |
4648 | return false; |
4649 | |
4650 | // C++ [expr.sizeof]p2: |
4651 | // When applied to a reference or a reference type, the result |
4652 | // is the size of the referenced type. |
4653 | // C++11 [expr.alignof]p3: |
4654 | // When alignof is applied to a reference type, the result |
4655 | // shall be the alignment of the referenced type. |
4656 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) |
4657 | ExprType = Ref->getPointeeType(); |
4658 | |
4659 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: |
4660 | // When alignof or _Alignof is applied to an array type, the result |
4661 | // is the alignment of the element type. |
4662 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
4663 | ExprKind == UETT_OpenMPRequiredSimdAlign) { |
4664 | // If the trait is 'alignof' in C before C2y, the ability to apply the |
4665 | // trait to an incomplete array is an extension. |
4666 | if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus && |
4667 | ExprType->isIncompleteArrayType()) |
4668 | Diag(OpLoc, getLangOpts().C2y |
4669 | ? diag::warn_c2y_compat_alignof_incomplete_array |
4670 | : diag::ext_c2y_alignof_incomplete_array); |
4671 | ExprType = Context.getBaseElementType(QT: ExprType); |
4672 | } |
4673 | |
4674 | if (ExprKind == UETT_VecStep) |
4675 | return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange); |
4676 | |
4677 | if (ExprKind == UETT_VectorElements) |
4678 | return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
4679 | ArgRange: ExprRange); |
4680 | |
4681 | if (ExprKind == UETT_PtrAuthTypeDiscriminator) |
4682 | return checkPtrAuthTypeDiscriminatorOperandType(S&: *this, T: ExprType, Loc: OpLoc, |
4683 | ArgRange: ExprRange); |
4684 | |
4685 | // Explicitly list some types as extensions. |
4686 | if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
4687 | TraitKind: ExprKind)) |
4688 | return false; |
4689 | |
4690 | if (RequireCompleteSizedType( |
4691 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, |
4692 | KWName, ExprRange)) |
4693 | return true; |
4694 | |
4695 | if (ExprType->isFunctionType()) { |
4696 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange; |
4697 | return true; |
4698 | } |
4699 | |
4700 | if (ExprKind == UETT_CountOf) { |
4701 | // The type has to be an array type. We already checked for incomplete |
4702 | // types above. |
4703 | if (!ExprType->isArrayType()) { |
4704 | Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType; |
4705 | return true; |
4706 | } |
4707 | } |
4708 | |
4709 | // WebAssembly tables are always illegal operands to unary expressions and |
4710 | // type traits. |
4711 | if (Context.getTargetInfo().getTriple().isWasm() && |
4712 | ExprType->isWebAssemblyTableType()) { |
4713 | Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand) |
4714 | << getTraitSpelling(ExprKind); |
4715 | return true; |
4716 | } |
4717 | |
4718 | if (CheckObjCTraitOperandConstraints(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange, |
4719 | TraitKind: ExprKind)) |
4720 | return true; |
4721 | |
4722 | if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) { |
4723 | if (auto *TT = ExprType->getAs<TypedefType>()) { |
4724 | for (auto I = FunctionScopes.rbegin(), |
4725 | E = std::prev(x: FunctionScopes.rend()); |
4726 | I != E; ++I) { |
4727 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
4728 | if (CSI == nullptr) |
4729 | break; |
4730 | DeclContext *DC = nullptr; |
4731 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
4732 | DC = LSI->CallOperator; |
4733 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
4734 | DC = CRSI->TheCapturedDecl; |
4735 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
4736 | DC = BSI->TheDecl; |
4737 | if (DC) { |
4738 | if (DC->containsDecl(TT->getDecl())) |
4739 | break; |
4740 | captureVariablyModifiedType(Context, T: ExprType, CSI); |
4741 | } |
4742 | } |
4743 | } |
4744 | } |
4745 | |
4746 | return false; |
4747 | } |
4748 | |
4749 | ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
4750 | SourceLocation OpLoc, |
4751 | UnaryExprOrTypeTrait ExprKind, |
4752 | SourceRange R) { |
4753 | if (!TInfo) |
4754 | return ExprError(); |
4755 | |
4756 | QualType T = TInfo->getType(); |
4757 | |
4758 | if (!T->isDependentType() && |
4759 | CheckUnaryExprOrTypeTraitOperand(ExprType: T, OpLoc, ExprRange: R, ExprKind, |
4760 | KWName: getTraitSpelling(T: ExprKind))) |
4761 | return ExprError(); |
4762 | |
4763 | // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to |
4764 | // properly deal with VLAs in nested calls of sizeof and typeof. |
4765 | if (currentEvaluationContext().isUnevaluated() && |
4766 | currentEvaluationContext().InConditionallyConstantEvaluateContext && |
4767 | (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && |
4768 | TInfo->getType()->isVariablyModifiedType()) |
4769 | TInfo = TransformToPotentiallyEvaluated(TInfo); |
4770 | |
4771 | // It's possible that the transformation above failed. |
4772 | if (!TInfo) |
4773 | return ExprError(); |
4774 | |
4775 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
4776 | return new (Context) UnaryExprOrTypeTraitExpr( |
4777 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); |
4778 | } |
4779 | |
4780 | ExprResult |
4781 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
4782 | UnaryExprOrTypeTrait ExprKind) { |
4783 | ExprResult PE = CheckPlaceholderExpr(E); |
4784 | if (PE.isInvalid()) |
4785 | return ExprError(); |
4786 | |
4787 | E = PE.get(); |
4788 | |
4789 | // Verify that the operand is valid. |
4790 | bool isInvalid = false; |
4791 | if (E->isTypeDependent()) { |
4792 | // Delay type-checking for type-dependent expressions. |
4793 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
4794 | isInvalid = CheckAlignOfExpr(S&: *this, E, ExprKind); |
4795 | } else if (ExprKind == UETT_VecStep) { |
4796 | isInvalid = CheckVecStepExpr(E); |
4797 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { |
4798 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); |
4799 | isInvalid = true; |
4800 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. |
4801 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; |
4802 | isInvalid = true; |
4803 | } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf || |
4804 | ExprKind == UETT_CountOf) { // FIXME: __datasizeof? |
4805 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
4806 | } |
4807 | |
4808 | if (isInvalid) |
4809 | return ExprError(); |
4810 | |
4811 | if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && |
4812 | E->getType()->isVariableArrayType()) { |
4813 | PE = TransformToPotentiallyEvaluated(E); |
4814 | if (PE.isInvalid()) return ExprError(); |
4815 | E = PE.get(); |
4816 | } |
4817 | |
4818 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
4819 | return new (Context) UnaryExprOrTypeTraitExpr( |
4820 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); |
4821 | } |
4822 | |
4823 | ExprResult |
4824 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
4825 | UnaryExprOrTypeTrait ExprKind, bool IsType, |
4826 | void *TyOrEx, SourceRange ArgRange) { |
4827 | // If error parsing type, ignore. |
4828 | if (!TyOrEx) return ExprError(); |
4829 | |
4830 | if (IsType) { |
4831 | TypeSourceInfo *TInfo; |
4832 | (void) GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo); |
4833 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange); |
4834 | } |
4835 | |
4836 | Expr *ArgEx = (Expr *)TyOrEx; |
4837 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind); |
4838 | return Result; |
4839 | } |
4840 | |
4841 | bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, |
4842 | SourceLocation OpLoc, SourceRange R) { |
4843 | if (!TInfo) |
4844 | return true; |
4845 | return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R, |
4846 | ExprKind: UETT_AlignOf, KWName); |
4847 | } |
4848 | |
4849 | bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, |
4850 | SourceLocation OpLoc, SourceRange R) { |
4851 | TypeSourceInfo *TInfo; |
4852 | (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()), |
4853 | TInfo: &TInfo); |
4854 | return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R); |
4855 | } |
4856 | |
4857 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, |
4858 | bool IsReal) { |
4859 | if (V.get()->isTypeDependent()) |
4860 | return S.Context.DependentTy; |
4861 | |
4862 | // _Real and _Imag are only l-values for normal l-values. |
4863 | if (V.get()->getObjectKind() != OK_Ordinary) { |
4864 | V = S.DefaultLvalueConversion(E: V.get()); |
4865 | if (V.isInvalid()) |
4866 | return QualType(); |
4867 | } |
4868 | |
4869 | // These operators return the element type of a complex type. |
4870 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) |
4871 | return CT->getElementType(); |
4872 | |
4873 | // Otherwise they pass through real integer and floating point types here. |
4874 | if (V.get()->getType()->isArithmeticType()) |
4875 | return V.get()->getType(); |
4876 | |
4877 | // Test for placeholders. |
4878 | ExprResult PR = S.CheckPlaceholderExpr(E: V.get()); |
4879 | if (PR.isInvalid()) return QualType(); |
4880 | if (PR.get() != V.get()) { |
4881 | V = PR; |
4882 | return CheckRealImagOperand(S, V, Loc, IsReal); |
4883 | } |
4884 | |
4885 | // Reject anything else. |
4886 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() |
4887 | << (IsReal ? "__real": "__imag"); |
4888 | return QualType(); |
4889 | } |
4890 | |
4891 | |
4892 | |
4893 | ExprResult |
4894 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
4895 | tok::TokenKind Kind, Expr *Input) { |
4896 | UnaryOperatorKind Opc; |
4897 | switch (Kind) { |
4898 | default: llvm_unreachable("Unknown unary op!"); |
4899 | case tok::plusplus: Opc = UO_PostInc; break; |
4900 | case tok::minusminus: Opc = UO_PostDec; break; |
4901 | } |
4902 | |
4903 | // Since this might is a postfix expression, get rid of ParenListExprs. |
4904 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input); |
4905 | if (Result.isInvalid()) return ExprError(); |
4906 | Input = Result.get(); |
4907 | |
4908 | return BuildUnaryOp(S, OpLoc, Opc, Input); |
4909 | } |
4910 | |
4911 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. |
4912 | /// |
4913 | /// \return true on error |
4914 | static bool checkArithmeticOnObjCPointer(Sema &S, |
4915 | SourceLocation opLoc, |
4916 | Expr *op) { |
4917 | assert(op->getType()->isObjCObjectPointerType()); |
4918 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && |
4919 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) |
4920 | return false; |
4921 | |
4922 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) |
4923 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() |
4924 | << op->getSourceRange(); |
4925 | return true; |
4926 | } |
4927 | |
4928 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { |
4929 | auto *BaseNoParens = Base->IgnoreParens(); |
4930 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens)) |
4931 | return MSProp->getPropertyDecl()->getType()->isArrayType(); |
4932 | return isa<MSPropertySubscriptExpr>(Val: BaseNoParens); |
4933 | } |
4934 | |
4935 | // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. |
4936 | // Typically this is DependentTy, but can sometimes be more precise. |
4937 | // |
4938 | // There are cases when we could determine a non-dependent type: |
4939 | // - LHS and RHS may have non-dependent types despite being type-dependent |
4940 | // (e.g. unbounded array static members of the current instantiation) |
4941 | // - one may be a dependent-sized array with known element type |
4942 | // - one may be a dependent-typed valid index (enum in current instantiation) |
4943 | // |
4944 | // We *always* return a dependent type, in such cases it is DependentTy. |
4945 | // This avoids creating type-dependent expressions with non-dependent types. |
4946 | // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 |
4947 | static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, |
4948 | const ASTContext &Ctx) { |
4949 | assert(LHS->isTypeDependent() || RHS->isTypeDependent()); |
4950 | QualType LTy = LHS->getType(), RTy = RHS->getType(); |
4951 | QualType Result = Ctx.DependentTy; |
4952 | if (RTy->isIntegralOrUnscopedEnumerationType()) { |
4953 | if (const PointerType *PT = LTy->getAs<PointerType>()) |
4954 | Result = PT->getPointeeType(); |
4955 | else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) |
4956 | Result = AT->getElementType(); |
4957 | } else if (LTy->isIntegralOrUnscopedEnumerationType()) { |
4958 | if (const PointerType *PT = RTy->getAs<PointerType>()) |
4959 | Result = PT->getPointeeType(); |
4960 | else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) |
4961 | Result = AT->getElementType(); |
4962 | } |
4963 | // Ensure we return a dependent type. |
4964 | return Result->isDependentType() ? Result : Ctx.DependentTy; |
4965 | } |
4966 | |
4967 | ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, |
4968 | SourceLocation lbLoc, |
4969 | MultiExprArg ArgExprs, |
4970 | SourceLocation rbLoc) { |
4971 | |
4972 | if (base && !base->getType().isNull() && |
4973 | base->hasPlaceholderType(K: BuiltinType::ArraySection)) { |
4974 | auto *AS = cast<ArraySectionExpr>(Val: base); |
4975 | if (AS->isOMPArraySection()) |
4976 | return OpenMP().ActOnOMPArraySectionExpr( |
4977 | Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(), |
4978 | /*Length*/ nullptr, |
4979 | /*Stride=*/nullptr, RBLoc: rbLoc); |
4980 | |
4981 | return OpenACC().ActOnArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(), |
4982 | ColonLocFirst: SourceLocation(), /*Length*/ nullptr, |
4983 | RBLoc: rbLoc); |
4984 | } |
4985 | |
4986 | // Since this might be a postfix expression, get rid of ParenListExprs. |
4987 | if (isa<ParenListExpr>(Val: base)) { |
4988 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: base); |
4989 | if (result.isInvalid()) |
4990 | return ExprError(); |
4991 | base = result.get(); |
4992 | } |
4993 | |
4994 | // Check if base and idx form a MatrixSubscriptExpr. |
4995 | // |
4996 | // Helper to check for comma expressions, which are not allowed as indices for |
4997 | // matrix subscript expressions. |
4998 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { |
4999 | if (isa<BinaryOperator>(Val: E) && cast<BinaryOperator>(Val: E)->isCommaOp()) { |
5000 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) |
5001 | << SourceRange(base->getBeginLoc(), rbLoc); |
5002 | return true; |
5003 | } |
5004 | return false; |
5005 | }; |
5006 | // The matrix subscript operator ([][])is considered a single operator. |
5007 | // Separating the index expressions by parenthesis is not allowed. |
5008 | if (base && !base->getType().isNull() && |
5009 | base->hasPlaceholderType(K: BuiltinType::IncompleteMatrixIdx) && |
5010 | !isa<MatrixSubscriptExpr>(Val: base)) { |
5011 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) |
5012 | << SourceRange(base->getBeginLoc(), rbLoc); |
5013 | return ExprError(); |
5014 | } |
5015 | // If the base is a MatrixSubscriptExpr, try to create a new |
5016 | // MatrixSubscriptExpr. |
5017 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(Val: base); |
5018 | if (matSubscriptE) { |
5019 | assert(ArgExprs.size() == 1); |
5020 | if (CheckAndReportCommaError(ArgExprs.front())) |
5021 | return ExprError(); |
5022 | |
5023 | assert(matSubscriptE->isIncomplete() && |
5024 | "base has to be an incomplete matrix subscript"); |
5025 | return CreateBuiltinMatrixSubscriptExpr(Base: matSubscriptE->getBase(), |
5026 | RowIdx: matSubscriptE->getRowIdx(), |
5027 | ColumnIdx: ArgExprs.front(), RBLoc: rbLoc); |
5028 | } |
5029 | if (base->getType()->isWebAssemblyTableType()) { |
5030 | Diag(base->getExprLoc(), diag::err_wasm_table_art) |
5031 | << SourceRange(base->getBeginLoc(), rbLoc) << 3; |
5032 | return ExprError(); |
5033 | } |
5034 | |
5035 | CheckInvalidBuiltinCountedByRef(E: base, |
5036 | K: BuiltinCountedByRefKind::ArraySubscript); |
5037 | |
5038 | // Handle any non-overload placeholder types in the base and index |
5039 | // expressions. We can't handle overloads here because the other |
5040 | // operand might be an overloadable type, in which case the overload |
5041 | // resolution for the operator overload should get the first crack |
5042 | // at the overload. |
5043 | bool IsMSPropertySubscript = false; |
5044 | if (base->getType()->isNonOverloadPlaceholderType()) { |
5045 | IsMSPropertySubscript = isMSPropertySubscriptExpr(S&: *this, Base: base); |
5046 | if (!IsMSPropertySubscript) { |
5047 | ExprResult result = CheckPlaceholderExpr(E: base); |
5048 | if (result.isInvalid()) |
5049 | return ExprError(); |
5050 | base = result.get(); |
5051 | } |
5052 | } |
5053 | |
5054 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. |
5055 | if (base->getType()->isMatrixType()) { |
5056 | assert(ArgExprs.size() == 1); |
5057 | if (CheckAndReportCommaError(ArgExprs.front())) |
5058 | return ExprError(); |
5059 | |
5060 | return CreateBuiltinMatrixSubscriptExpr(Base: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr, |
5061 | RBLoc: rbLoc); |
5062 | } |
5063 | |
5064 | if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { |
5065 | Expr *idx = ArgExprs[0]; |
5066 | if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) || |
5067 | (isa<CXXOperatorCallExpr>(Val: idx) && |
5068 | cast<CXXOperatorCallExpr>(Val: idx)->getOperator() == OO_Comma)) { |
5069 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) |
5070 | << SourceRange(base->getBeginLoc(), rbLoc); |
5071 | } |
5072 | } |
5073 | |
5074 | if (ArgExprs.size() == 1 && |
5075 | ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { |
5076 | ExprResult result = CheckPlaceholderExpr(E: ArgExprs[0]); |
5077 | if (result.isInvalid()) |
5078 | return ExprError(); |
5079 | ArgExprs[0] = result.get(); |
5080 | } else { |
5081 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
5082 | return ExprError(); |
5083 | } |
5084 | |
5085 | // Build an unanalyzed expression if either operand is type-dependent. |
5086 | if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && |
5087 | (base->isTypeDependent() || |
5088 | Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) && |
5089 | !isa<PackExpansionExpr>(Val: ArgExprs[0])) { |
5090 | return new (Context) ArraySubscriptExpr( |
5091 | base, ArgExprs.front(), |
5092 | getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: getASTContext()), |
5093 | VK_LValue, OK_Ordinary, rbLoc); |
5094 | } |
5095 | |
5096 | // MSDN, property (C++) |
5097 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx |
5098 | // This attribute can also be used in the declaration of an empty array in a |
5099 | // class or structure definition. For example: |
5100 | // __declspec(property(get=GetX, put=PutX)) int x[]; |
5101 | // The above statement indicates that x[] can be used with one or more array |
5102 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), |
5103 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); |
5104 | if (IsMSPropertySubscript) { |
5105 | assert(ArgExprs.size() == 1); |
5106 | // Build MS property subscript expression if base is MS property reference |
5107 | // or MS property subscript. |
5108 | return new (Context) |
5109 | MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, |
5110 | VK_LValue, OK_Ordinary, rbLoc); |
5111 | } |
5112 | |
5113 | // Use C++ overloaded-operator rules if either operand has record |
5114 | // type. The spec says to do this if either type is *overloadable*, |
5115 | // but enum types can't declare subscript operators or conversion |
5116 | // operators, so there's nothing interesting for overload resolution |
5117 | // to do if there aren't any record types involved. |
5118 | // |
5119 | // ObjC pointers have their own subscripting logic that is not tied |
5120 | // to overload resolution and so should not take this path. |
5121 | if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && |
5122 | ((base->getType()->isRecordType() || |
5123 | (ArgExprs.size() != 1 || isa<PackExpansionExpr>(Val: ArgExprs[0]) || |
5124 | ArgExprs[0]->getType()->isRecordType())))) { |
5125 | return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs); |
5126 | } |
5127 | |
5128 | ExprResult Res = |
5129 | CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc); |
5130 | |
5131 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get())) |
5132 | CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get())); |
5133 | |
5134 | return Res; |
5135 | } |
5136 | |
5137 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { |
5138 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty); |
5139 | InitializationKind Kind = |
5140 | InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation()); |
5141 | InitializationSequence InitSeq(*this, Entity, Kind, E); |
5142 | return InitSeq.Perform(S&: *this, Entity, Kind, Args: E); |
5143 | } |
5144 | |
5145 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, |
5146 | Expr *ColumnIdx, |
5147 | SourceLocation RBLoc) { |
5148 | ExprResult BaseR = CheckPlaceholderExpr(E: Base); |
5149 | if (BaseR.isInvalid()) |
5150 | return BaseR; |
5151 | Base = BaseR.get(); |
5152 | |
5153 | ExprResult RowR = CheckPlaceholderExpr(E: RowIdx); |
5154 | if (RowR.isInvalid()) |
5155 | return RowR; |
5156 | RowIdx = RowR.get(); |
5157 | |
5158 | if (!ColumnIdx) |
5159 | return new (Context) MatrixSubscriptExpr( |
5160 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); |
5161 | |
5162 | // Build an unanalyzed expression if any of the operands is type-dependent. |
5163 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || |
5164 | ColumnIdx->isTypeDependent()) |
5165 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
5166 | Context.DependentTy, RBLoc); |
5167 | |
5168 | ExprResult ColumnR = CheckPlaceholderExpr(E: ColumnIdx); |
5169 | if (ColumnR.isInvalid()) |
5170 | return ColumnR; |
5171 | ColumnIdx = ColumnR.get(); |
5172 | |
5173 | // Check that IndexExpr is an integer expression. If it is a constant |
5174 | // expression, check that it is less than Dim (= the number of elements in the |
5175 | // corresponding dimension). |
5176 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, |
5177 | bool IsColumnIdx) -> Expr * { |
5178 | if (!IndexExpr->getType()->isIntegerType() && |
5179 | !IndexExpr->isTypeDependent()) { |
5180 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) |
5181 | << IsColumnIdx; |
5182 | return nullptr; |
5183 | } |
5184 | |
5185 | if (std::optional<llvm::APSInt> Idx = |
5186 | IndexExpr->getIntegerConstantExpr(Ctx: Context)) { |
5187 | if ((*Idx < 0 || *Idx >= Dim)) { |
5188 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) |
5189 | << IsColumnIdx << Dim; |
5190 | return nullptr; |
5191 | } |
5192 | } |
5193 | |
5194 | ExprResult ConvExpr = IndexExpr; |
5195 | assert(!ConvExpr.isInvalid() && |
5196 | "should be able to convert any integer type to size type"); |
5197 | return ConvExpr.get(); |
5198 | }; |
5199 | |
5200 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); |
5201 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); |
5202 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); |
5203 | if (!RowIdx || !ColumnIdx) |
5204 | return ExprError(); |
5205 | |
5206 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, |
5207 | MTy->getElementType(), RBLoc); |
5208 | } |
5209 | |
5210 | void Sema::CheckAddressOfNoDeref(const Expr *E) { |
5211 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
5212 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); |
5213 | |
5214 | // For expressions like `&(*s).b`, the base is recorded and what should be |
5215 | // checked. |
5216 | const MemberExpr *Member = nullptr; |
5217 | while ((Member = dyn_cast<MemberExpr>(Val: StrippedExpr)) && !Member->isArrow()) |
5218 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); |
5219 | |
5220 | LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr); |
5221 | } |
5222 | |
5223 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { |
5224 | if (isUnevaluatedContext()) |
5225 | return; |
5226 | |
5227 | QualType ResultTy = E->getType(); |
5228 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
5229 | |
5230 | // Bail if the element is an array since it is not memory access. |
5231 | if (isa<ArrayType>(Val: ResultTy)) |
5232 | return; |
5233 | |
5234 | if (ResultTy->hasAttr(attr::NoDeref)) { |
5235 | LastRecord.PossibleDerefs.insert(E); |
5236 | return; |
5237 | } |
5238 | |
5239 | // Check if the base type is a pointer to a member access of a struct |
5240 | // marked with noderef. |
5241 | const Expr *Base = E->getBase(); |
5242 | QualType BaseTy = Base->getType(); |
5243 | if (!(isa<ArrayType>(Val: BaseTy) || isa<PointerType>(Val: BaseTy))) |
5244 | // Not a pointer access |
5245 | return; |
5246 | |
5247 | const MemberExpr *Member = nullptr; |
5248 | while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) && |
5249 | Member->isArrow()) |
5250 | Base = Member->getBase(); |
5251 | |
5252 | if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) { |
5253 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) |
5254 | LastRecord.PossibleDerefs.insert(E); |
5255 | } |
5256 | } |
5257 | |
5258 | ExprResult |
5259 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
5260 | Expr *Idx, SourceLocation RLoc) { |
5261 | Expr *LHSExp = Base; |
5262 | Expr *RHSExp = Idx; |
5263 | |
5264 | ExprValueKind VK = VK_LValue; |
5265 | ExprObjectKind OK = OK_Ordinary; |
5266 | |
5267 | // Per C++ core issue 1213, the result is an xvalue if either operand is |
5268 | // a non-lvalue array, and an lvalue otherwise. |
5269 | if (getLangOpts().CPlusPlus11) { |
5270 | for (auto *Op : {LHSExp, RHSExp}) { |
5271 | Op = Op->IgnoreImplicit(); |
5272 | if (Op->getType()->isArrayType() && !Op->isLValue()) |
5273 | VK = VK_XValue; |
5274 | } |
5275 | } |
5276 | |
5277 | // Perform default conversions. |
5278 | if (!LHSExp->getType()->isSubscriptableVectorType()) { |
5279 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp); |
5280 | if (Result.isInvalid()) |
5281 | return ExprError(); |
5282 | LHSExp = Result.get(); |
5283 | } |
5284 | ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp); |
5285 | if (Result.isInvalid()) |
5286 | return ExprError(); |
5287 | RHSExp = Result.get(); |
5288 | |
5289 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); |
5290 | |
5291 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent |
5292 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be |
5293 | // in the subscript position. As a result, we need to derive the array base |
5294 | // and index from the expression types. |
5295 | Expr *BaseExpr, *IndexExpr; |
5296 | QualType ResultType; |
5297 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { |
5298 | BaseExpr = LHSExp; |
5299 | IndexExpr = RHSExp; |
5300 | ResultType = |
5301 | getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext()); |
5302 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { |
5303 | BaseExpr = LHSExp; |
5304 | IndexExpr = RHSExp; |
5305 | ResultType = PTy->getPointeeType(); |
5306 | } else if (const ObjCObjectPointerType *PTy = |
5307 | LHSTy->getAs<ObjCObjectPointerType>()) { |
5308 | BaseExpr = LHSExp; |
5309 | IndexExpr = RHSExp; |
5310 | |
5311 | // Use custom logic if this should be the pseudo-object subscript |
5312 | // expression. |
5313 | if (!LangOpts.isSubscriptPointerArithmetic()) |
5314 | return ObjC().BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr, |
5315 | getterMethod: nullptr, setterMethod: nullptr); |
5316 | |
5317 | ResultType = PTy->getPointeeType(); |
5318 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { |
5319 | // Handle the uncommon case of "123[Ptr]". |
5320 | BaseExpr = RHSExp; |
5321 | IndexExpr = LHSExp; |
5322 | ResultType = PTy->getPointeeType(); |
5323 | } else if (const ObjCObjectPointerType *PTy = |
5324 | RHSTy->getAs<ObjCObjectPointerType>()) { |
5325 | // Handle the uncommon case of "123[Ptr]". |
5326 | BaseExpr = RHSExp; |
5327 | IndexExpr = LHSExp; |
5328 | ResultType = PTy->getPointeeType(); |
5329 | if (!LangOpts.isSubscriptPointerArithmetic()) { |
5330 | Diag(LLoc, diag::err_subscript_nonfragile_interface) |
5331 | << ResultType << BaseExpr->getSourceRange(); |
5332 | return ExprError(); |
5333 | } |
5334 | } else if (LHSTy->isSubscriptableVectorType()) { |
5335 | if (LHSTy->isBuiltinType() && |
5336 | LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) { |
5337 | const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); |
5338 | if (BTy->isSVEBool()) |
5339 | return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) |
5340 | << LHSExp->getSourceRange() |
5341 | << RHSExp->getSourceRange()); |
5342 | ResultType = BTy->getSveEltType(Context); |
5343 | } else { |
5344 | const VectorType *VTy = LHSTy->getAs<VectorType>(); |
5345 | ResultType = VTy->getElementType(); |
5346 | } |
5347 | BaseExpr = LHSExp; // vectors: V[123] |
5348 | IndexExpr = RHSExp; |
5349 | // We apply C++ DR1213 to vector subscripting too. |
5350 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { |
5351 | ExprResult Materialized = TemporaryMaterializationConversion(E: LHSExp); |
5352 | if (Materialized.isInvalid()) |
5353 | return ExprError(); |
5354 | LHSExp = Materialized.get(); |
5355 | } |
5356 | VK = LHSExp->getValueKind(); |
5357 | if (VK != VK_PRValue) |
5358 | OK = OK_VectorComponent; |
5359 | |
5360 | QualType BaseType = BaseExpr->getType(); |
5361 | Qualifiers BaseQuals = BaseType.getQualifiers(); |
5362 | Qualifiers MemberQuals = ResultType.getQualifiers(); |
5363 | Qualifiers Combined = BaseQuals + MemberQuals; |
5364 | if (Combined != MemberQuals) |
5365 | ResultType = Context.getQualifiedType(T: ResultType, Qs: Combined); |
5366 | } else if (LHSTy->isArrayType()) { |
5367 | // If we see an array that wasn't promoted by |
5368 | // DefaultFunctionArrayLvalueConversion, it must be an array that |
5369 | // wasn't promoted because of the C90 rule that doesn't |
5370 | // allow promoting non-lvalue arrays. Warn, then |
5371 | // force the promotion here. |
5372 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) |
5373 | << LHSExp->getSourceRange(); |
5374 | LHSExp = ImpCastExprToType(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy), |
5375 | CK: CK_ArrayToPointerDecay).get(); |
5376 | LHSTy = LHSExp->getType(); |
5377 | |
5378 | BaseExpr = LHSExp; |
5379 | IndexExpr = RHSExp; |
5380 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); |
5381 | } else if (RHSTy->isArrayType()) { |
5382 | // Same as previous, except for 123[f().a] case |
5383 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) |
5384 | << RHSExp->getSourceRange(); |
5385 | RHSExp = ImpCastExprToType(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy), |
5386 | CK: CK_ArrayToPointerDecay).get(); |
5387 | RHSTy = RHSExp->getType(); |
5388 | |
5389 | BaseExpr = RHSExp; |
5390 | IndexExpr = LHSExp; |
5391 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); |
5392 | } else { |
5393 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) |
5394 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); |
5395 | } |
5396 | // C99 6.5.2.1p1 |
5397 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) |
5398 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) |
5399 | << IndexExpr->getSourceRange()); |
5400 | |
5401 | if ((IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
5402 | IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) && |
5403 | !IndexExpr->isTypeDependent()) { |
5404 | std::optional<llvm::APSInt> IntegerContantExpr = |
5405 | IndexExpr->getIntegerConstantExpr(Ctx: getASTContext()); |
5406 | if (!IntegerContantExpr.has_value() || |
5407 | IntegerContantExpr.value().isNegative()) |
5408 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); |
5409 | } |
5410 | |
5411 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, |
5412 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object |
5413 | // type. Note that Functions are not objects, and that (in C99 parlance) |
5414 | // incomplete types are not object types. |
5415 | if (ResultType->isFunctionType()) { |
5416 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) |
5417 | << ResultType << BaseExpr->getSourceRange(); |
5418 | return ExprError(); |
5419 | } |
5420 | |
5421 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { |
5422 | // GNU extension: subscripting on pointer to void |
5423 | Diag(LLoc, diag::ext_gnu_subscript_void_type) |
5424 | << BaseExpr->getSourceRange(); |
5425 | |
5426 | // C forbids expressions of unqualified void type from being l-values. |
5427 | // See IsCForbiddenLValueType. |
5428 | if (!ResultType.hasQualifiers()) |
5429 | VK = VK_PRValue; |
5430 | } else if (!ResultType->isDependentType() && |
5431 | !ResultType.isWebAssemblyReferenceType() && |
5432 | RequireCompleteSizedType( |
5433 | LLoc, ResultType, |
5434 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) |
5435 | return ExprError(); |
5436 | |
5437 | assert(VK == VK_PRValue || LangOpts.CPlusPlus || |
5438 | !ResultType.isCForbiddenLValueType()); |
5439 | |
5440 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && |
5441 | FunctionScopes.size() > 1) { |
5442 | if (auto *TT = |
5443 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { |
5444 | for (auto I = FunctionScopes.rbegin(), |
5445 | E = std::prev(x: FunctionScopes.rend()); |
5446 | I != E; ++I) { |
5447 | auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I); |
5448 | if (CSI == nullptr) |
5449 | break; |
5450 | DeclContext *DC = nullptr; |
5451 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI)) |
5452 | DC = LSI->CallOperator; |
5453 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) |
5454 | DC = CRSI->TheCapturedDecl; |
5455 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) |
5456 | DC = BSI->TheDecl; |
5457 | if (DC) { |
5458 | if (DC->containsDecl(TT->getDecl())) |
5459 | break; |
5460 | captureVariablyModifiedType( |
5461 | Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI); |
5462 | } |
5463 | } |
5464 | } |
5465 | } |
5466 | |
5467 | return new (Context) |
5468 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); |
5469 | } |
5470 | |
5471 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
5472 | ParmVarDecl *Param, Expr *RewrittenInit, |
5473 | bool SkipImmediateInvocations) { |
5474 | if (Param->hasUnparsedDefaultArg()) { |
5475 | assert(!RewrittenInit && "Should not have a rewritten init expression yet"); |
5476 | // If we've already cleared out the location for the default argument, |
5477 | // that means we're parsing it right now. |
5478 | if (!UnparsedDefaultArgLocs.count(Val: Param)) { |
5479 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; |
5480 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); |
5481 | Param->setInvalidDecl(); |
5482 | return true; |
5483 | } |
5484 | |
5485 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) |
5486 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); |
5487 | Diag(UnparsedDefaultArgLocs[Param], |
5488 | diag::note_default_argument_declared_here); |
5489 | return true; |
5490 | } |
5491 | |
5492 | if (Param->hasUninstantiatedDefaultArg()) { |
5493 | assert(!RewrittenInit && "Should not have a rewitten init expression yet"); |
5494 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
5495 | return true; |
5496 | } |
5497 | |
5498 | Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); |
5499 | assert(Init && "default argument but no initializer?"); |
5500 | |
5501 | // If the default expression creates temporaries, we need to |
5502 | // push them to the current stack of expression temporaries so they'll |
5503 | // be properly destroyed. |
5504 | // FIXME: We should really be rebuilding the default argument with new |
5505 | // bound temporaries; see the comment in PR5810. |
5506 | // We don't need to do that with block decls, though, because |
5507 | // blocks in default argument expression can never capture anything. |
5508 | if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) { |
5509 | // Set the "needs cleanups" bit regardless of whether there are |
5510 | // any explicit objects. |
5511 | Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); |
5512 | // Append all the objects to the cleanup list. Right now, this |
5513 | // should always be a no-op, because blocks in default argument |
5514 | // expressions should never be able to capture anything. |
5515 | assert(!InitWithCleanup->getNumObjects() && |
5516 | "default argument expression has capturing blocks?"); |
5517 | } |
5518 | // C++ [expr.const]p15.1: |
5519 | // An expression or conversion is in an immediate function context if it is |
5520 | // potentially evaluated and [...] its innermost enclosing non-block scope |
5521 | // is a function parameter scope of an immediate function. |
5522 | EnterExpressionEvaluationContext EvalContext( |
5523 | *this, |
5524 | FD->isImmediateFunction() |
5525 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
5526 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
5527 | Param); |
5528 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
5529 | SkipImmediateInvocations; |
5530 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
5531 | MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true); |
5532 | }); |
5533 | return false; |
5534 | } |
5535 | |
5536 | struct ImmediateCallVisitor : DynamicRecursiveASTVisitor { |
5537 | const ASTContext &Context; |
5538 | ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) { |
5539 | ShouldVisitImplicitCode = true; |
5540 | } |
5541 | |
5542 | bool HasImmediateCalls = false; |
5543 | |
5544 | bool VisitCallExpr(CallExpr *E) override { |
5545 | if (const FunctionDecl *FD = E->getDirectCallee()) |
5546 | HasImmediateCalls |= FD->isImmediateFunction(); |
5547 | return DynamicRecursiveASTVisitor::VisitStmt(E); |
5548 | } |
5549 | |
5550 | bool VisitCXXConstructExpr(CXXConstructExpr *E) override { |
5551 | if (const FunctionDecl *FD = E->getConstructor()) |
5552 | HasImmediateCalls |= FD->isImmediateFunction(); |
5553 | return DynamicRecursiveASTVisitor::VisitStmt(E); |
5554 | } |
5555 | |
5556 | // SourceLocExpr are not immediate invocations |
5557 | // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr |
5558 | // need to be rebuilt so that they refer to the correct SourceLocation and |
5559 | // DeclContext. |
5560 | bool VisitSourceLocExpr(SourceLocExpr *E) override { |
5561 | HasImmediateCalls = true; |
5562 | return DynamicRecursiveASTVisitor::VisitStmt(E); |
5563 | } |
5564 | |
5565 | // A nested lambda might have parameters with immediate invocations |
5566 | // in their default arguments. |
5567 | // The compound statement is not visited (as it does not constitute a |
5568 | // subexpression). |
5569 | // FIXME: We should consider visiting and transforming captures |
5570 | // with init expressions. |
5571 | bool VisitLambdaExpr(LambdaExpr *E) override { |
5572 | return VisitCXXMethodDecl(E->getCallOperator()); |
5573 | } |
5574 | |
5575 | bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override { |
5576 | return TraverseStmt(E->getExpr()); |
5577 | } |
5578 | |
5579 | bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override { |
5580 | return TraverseStmt(E->getExpr()); |
5581 | } |
5582 | }; |
5583 | |
5584 | struct EnsureImmediateInvocationInDefaultArgs |
5585 | : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { |
5586 | EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) |
5587 | : TreeTransform(SemaRef) {} |
5588 | |
5589 | bool AlwaysRebuild() { return true; } |
5590 | |
5591 | // Lambda can only have immediate invocations in the default |
5592 | // args of their parameters, which is transformed upon calling the closure. |
5593 | // The body is not a subexpression, so we have nothing to do. |
5594 | // FIXME: Immediate calls in capture initializers should be transformed. |
5595 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } |
5596 | ExprResult TransformBlockExpr(BlockExpr *E) { return E; } |
5597 | |
5598 | // Make sure we don't rebuild the this pointer as it would |
5599 | // cause it to incorrectly point it to the outermost class |
5600 | // in the case of nested struct initialization. |
5601 | ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } |
5602 | |
5603 | // Rewrite to source location to refer to the context in which they are used. |
5604 | ExprResult TransformSourceLocExpr(SourceLocExpr *E) { |
5605 | DeclContext *DC = E->getParentContext(); |
5606 | if (DC == SemaRef.CurContext) |
5607 | return E; |
5608 | |
5609 | // FIXME: During instantiation, because the rebuild of defaults arguments |
5610 | // is not always done in the context of the template instantiator, |
5611 | // we run the risk of producing a dependent source location |
5612 | // that would never be rebuilt. |
5613 | // This usually happens during overload resolution, or in contexts |
5614 | // where the value of the source location does not matter. |
5615 | // However, we should find a better way to deal with source location |
5616 | // of function templates. |
5617 | if (!SemaRef.CurrentInstantiationScope || |
5618 | !SemaRef.CurContext->isDependentContext() || DC->isDependentContext()) |
5619 | DC = SemaRef.CurContext; |
5620 | |
5621 | return getDerived().RebuildSourceLocExpr( |
5622 | E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC); |
5623 | } |
5624 | }; |
5625 | |
5626 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
5627 | FunctionDecl *FD, ParmVarDecl *Param, |
5628 | Expr *Init) { |
5629 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); |
5630 | |
5631 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
5632 | bool NeedRebuild = needsRebuildOfDefaultArgOrInit(); |
5633 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
5634 | InitializationContext = |
5635 | OutermostDeclarationWithDelayedImmediateInvocations(); |
5636 | if (!InitializationContext.has_value()) |
5637 | InitializationContext.emplace(CallLoc, Param, CurContext); |
5638 | |
5639 | if (!Init && !Param->hasUnparsedDefaultArg()) { |
5640 | // Mark that we are replacing a default argument first. |
5641 | // If we are instantiating a template we won't have to |
5642 | // retransform immediate calls. |
5643 | // C++ [expr.const]p15.1: |
5644 | // An expression or conversion is in an immediate function context if it |
5645 | // is potentially evaluated and [...] its innermost enclosing non-block |
5646 | // scope is a function parameter scope of an immediate function. |
5647 | EnterExpressionEvaluationContext EvalContext( |
5648 | *this, |
5649 | FD->isImmediateFunction() |
5650 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
5651 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
5652 | Param); |
5653 | |
5654 | if (Param->hasUninstantiatedDefaultArg()) { |
5655 | if (InstantiateDefaultArgument(CallLoc, FD, Param)) |
5656 | return ExprError(); |
5657 | } |
5658 | // CWG2631 |
5659 | // An immediate invocation that is not evaluated where it appears is |
5660 | // evaluated and checked for whether it is a constant expression at the |
5661 | // point where the enclosing initializer is used in a function call. |
5662 | ImmediateCallVisitor V(getASTContext()); |
5663 | if (!NestedDefaultChecking) |
5664 | V.TraverseDecl(Param); |
5665 | |
5666 | // Rewrite the call argument that was created from the corresponding |
5667 | // parameter's default argument. |
5668 | if (V.HasImmediateCalls || |
5669 | (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) { |
5670 | if (V.HasImmediateCalls) |
5671 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
5672 | CallLoc, Param, CurContext}; |
5673 | // Pass down lifetime extending flag, and collect temporaries in |
5674 | // CreateMaterializeTemporaryExpr when we rewrite the call argument. |
5675 | currentEvaluationContext().InLifetimeExtendingContext = |
5676 | parentEvaluationContext().InLifetimeExtendingContext; |
5677 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
5678 | ExprResult Res; |
5679 | runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] { |
5680 | Res = Immediate.TransformInitializer(Param->getInit(), |
5681 | /*NotCopy=*/false); |
5682 | }); |
5683 | if (Res.isInvalid()) |
5684 | return ExprError(); |
5685 | Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(), |
5686 | EqualLoc: Res.get()->getBeginLoc()); |
5687 | if (Res.isInvalid()) |
5688 | return ExprError(); |
5689 | Init = Res.get(); |
5690 | } |
5691 | } |
5692 | |
5693 | if (CheckCXXDefaultArgExpr( |
5694 | CallLoc, FD, Param, RewrittenInit: Init, |
5695 | /*SkipImmediateInvocations=*/NestedDefaultChecking)) |
5696 | return ExprError(); |
5697 | |
5698 | return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param, |
5699 | RewrittenExpr: Init, UsedContext: InitializationContext->Context); |
5700 | } |
5701 | |
5702 | static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx, |
5703 | FieldDecl *Field) { |
5704 | if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field)) |
5705 | return Pattern; |
5706 | auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent()); |
5707 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); |
5708 | DeclContext::lookup_result Lookup = |
5709 | ClassPattern->lookup(Name: Field->getDeclName()); |
5710 | auto Rng = llvm::make_filter_range( |
5711 | Range&: Lookup, Pred: [](auto &&L) { return isa<FieldDecl>(*L); }); |
5712 | if (Rng.empty()) |
5713 | return nullptr; |
5714 | // FIXME: this breaks clang/test/Modules/pr28812.cpp |
5715 | // assert(std::distance(Rng.begin(), Rng.end()) <= 1 |
5716 | // && "Duplicated instantiation pattern for field decl"); |
5717 | return cast<FieldDecl>(*Rng.begin()); |
5718 | } |
5719 | |
5720 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { |
5721 | assert(Field->hasInClassInitializer()); |
5722 | |
5723 | CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers()); |
5724 | |
5725 | auto *ParentRD = cast<CXXRecordDecl>(Val: Field->getParent()); |
5726 | |
5727 | std::optional<ExpressionEvaluationContextRecord::InitializationContext> |
5728 | InitializationContext = |
5729 | OutermostDeclarationWithDelayedImmediateInvocations(); |
5730 | if (!InitializationContext.has_value()) |
5731 | InitializationContext.emplace(Loc, Field, CurContext); |
5732 | |
5733 | Expr *Init = nullptr; |
5734 | |
5735 | bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); |
5736 | bool NeedRebuild = needsRebuildOfDefaultArgOrInit(); |
5737 | EnterExpressionEvaluationContext EvalContext( |
5738 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); |
5739 | |
5740 | if (!Field->getInClassInitializer()) { |
5741 | // Maybe we haven't instantiated the in-class initializer. Go check the |
5742 | // pattern FieldDecl to see if it has one. |
5743 | if (isTemplateInstantiation(Kind: ParentRD->getTemplateSpecializationKind())) { |
5744 | FieldDecl *Pattern = |
5745 | FindFieldDeclInstantiationPattern(Ctx: getASTContext(), Field); |
5746 | assert(Pattern && "We must have set the Pattern!"); |
5747 | if (!Pattern->hasInClassInitializer() || |
5748 | InstantiateInClassInitializer(PointOfInstantiation: Loc, Instantiation: Field, Pattern, |
5749 | TemplateArgs: getTemplateInstantiationArgs(Field))) { |
5750 | Field->setInvalidDecl(); |
5751 | return ExprError(); |
5752 | } |
5753 | } |
5754 | } |
5755 | |
5756 | // CWG2631 |
5757 | // An immediate invocation that is not evaluated where it appears is |
5758 | // evaluated and checked for whether it is a constant expression at the |
5759 | // point where the enclosing initializer is used in a [...] a constructor |
5760 | // definition, or an aggregate initialization. |
5761 | ImmediateCallVisitor V(getASTContext()); |
5762 | if (!NestedDefaultChecking) |
5763 | V.TraverseDecl(Field); |
5764 | |
5765 | // CWG1815 |
5766 | // Support lifetime extension of temporary created by aggregate |
5767 | // initialization using a default member initializer. We should rebuild |
5768 | // the initializer in a lifetime extension context if the initializer |
5769 | // expression is an ExprWithCleanups. Then make sure the normal lifetime |
5770 | // extension code recurses into the default initializer and does lifetime |
5771 | // extension when warranted. |
5772 | bool ContainsAnyTemporaries = |
5773 | isa_and_present<ExprWithCleanups>(Val: Field->getInClassInitializer()); |
5774 | if (Field->getInClassInitializer() && |
5775 | !Field->getInClassInitializer()->containsErrors() && |
5776 | (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) { |
5777 | ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, |
5778 | CurContext}; |
5779 | ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = |
5780 | NestedDefaultChecking; |
5781 | // Pass down lifetime extending flag, and collect temporaries in |
5782 | // CreateMaterializeTemporaryExpr when we rewrite the call argument. |
5783 | currentEvaluationContext().InLifetimeExtendingContext = |
5784 | parentEvaluationContext().InLifetimeExtendingContext; |
5785 | EnsureImmediateInvocationInDefaultArgs Immediate(*this); |
5786 | ExprResult Res; |
5787 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5788 | Res = Immediate.TransformInitializer(Field->getInClassInitializer(), |
5789 | /*CXXDirectInit=*/false); |
5790 | }); |
5791 | if (!Res.isInvalid()) |
5792 | Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: Loc); |
5793 | if (Res.isInvalid()) { |
5794 | Field->setInvalidDecl(); |
5795 | return ExprError(); |
5796 | } |
5797 | Init = Res.get(); |
5798 | } |
5799 | |
5800 | if (Field->getInClassInitializer()) { |
5801 | Expr *E = Init ? Init : Field->getInClassInitializer(); |
5802 | if (!NestedDefaultChecking) |
5803 | runWithSufficientStackSpace(Loc, Fn: [&] { |
5804 | MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); |
5805 | }); |
5806 | if (isInLifetimeExtendingContext()) |
5807 | DiscardCleanupsInEvaluationContext(); |
5808 | // C++11 [class.base.init]p7: |
5809 | // The initialization of each base and member constitutes a |
5810 | // full-expression. |
5811 | ExprResult Res = ActOnFinishFullExpr(Expr: E, /*DiscardedValue=*/false); |
5812 | if (Res.isInvalid()) { |
5813 | Field->setInvalidDecl(); |
5814 | return ExprError(); |
5815 | } |
5816 | Init = Res.get(); |
5817 | |
5818 | return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc, |
5819 | Field, UsedContext: InitializationContext->Context, |
5820 | RewrittenInitExpr: Init); |
5821 | } |
5822 | |
5823 | // DR1351: |
5824 | // If the brace-or-equal-initializer of a non-static data member |
5825 | // invokes a defaulted default constructor of its class or of an |
5826 | // enclosing class in a potentially evaluated subexpression, the |
5827 | // program is ill-formed. |
5828 | // |
5829 | // This resolution is unworkable: the exception specification of the |
5830 | // default constructor can be needed in an unevaluated context, in |
5831 | // particular, in the operand of a noexcept-expression, and we can be |
5832 | // unable to compute an exception specification for an enclosed class. |
5833 | // |
5834 | // Any attempt to resolve the exception specification of a defaulted default |
5835 | // constructor before the initializer is lexically complete will ultimately |
5836 | // come here at which point we can diagnose it. |
5837 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); |
5838 | Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) |
5839 | << OutermostClass << Field; |
5840 | Diag(Field->getEndLoc(), |
5841 | diag::note_default_member_initializer_not_yet_parsed); |
5842 | // Recover by marking the field invalid, unless we're in a SFINAE context. |
5843 | if (!isSFINAEContext()) |
5844 | Field->setInvalidDecl(); |
5845 | return ExprError(); |
5846 | } |
5847 | |
5848 | VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl, |
5849 | const FunctionProtoType *Proto, |
5850 | Expr *Fn) { |
5851 | if (Proto && Proto->isVariadic()) { |
5852 | if (isa_and_nonnull<CXXConstructorDecl>(Val: FDecl)) |
5853 | return VariadicCallType::Constructor; |
5854 | else if (Fn && Fn->getType()->isBlockPointerType()) |
5855 | return VariadicCallType::Block; |
5856 | else if (FDecl) { |
5857 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: FDecl)) |
5858 | if (Method->isInstance()) |
5859 | return VariadicCallType::Method; |
5860 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) |
5861 | return VariadicCallType::Method; |
5862 | return VariadicCallType::Function; |
5863 | } |
5864 | return VariadicCallType::DoesNotApply; |
5865 | } |
5866 | |
5867 | namespace { |
5868 | class FunctionCallCCC final : public FunctionCallFilterCCC { |
5869 | public: |
5870 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, |
5871 | unsigned NumArgs, MemberExpr *ME) |
5872 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), |
5873 | FunctionName(FuncName) {} |
5874 | |
5875 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
5876 | if (!candidate.getCorrectionSpecifier() || |
5877 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { |
5878 | return false; |
5879 | } |
5880 | |
5881 | return FunctionCallFilterCCC::ValidateCandidate(candidate); |
5882 | } |
5883 | |
5884 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
5885 | return std::make_unique<FunctionCallCCC>(args&: *this); |
5886 | } |
5887 | |
5888 | private: |
5889 | const IdentifierInfo *const FunctionName; |
5890 | }; |
5891 | } |
5892 | |
5893 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, |
5894 | FunctionDecl *FDecl, |
5895 | ArrayRef<Expr *> Args) { |
5896 | MemberExpr *ME = dyn_cast<MemberExpr>(Val: Fn); |
5897 | DeclarationName FuncName = FDecl->getDeclName(); |
5898 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); |
5899 | |
5900 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); |
5901 | if (TypoCorrection Corrected = S.CorrectTypo( |
5902 | Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName, |
5903 | S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC, |
5904 | Mode: CorrectTypoKind::ErrorRecovery)) { |
5905 | if (NamedDecl *ND = Corrected.getFoundDecl()) { |
5906 | if (Corrected.isOverloaded()) { |
5907 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); |
5908 | OverloadCandidateSet::iterator Best; |
5909 | for (NamedDecl *CD : Corrected) { |
5910 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) |
5911 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, |
5912 | OCS); |
5913 | } |
5914 | switch (OCS.BestViableFunction(S, Loc: NameLoc, Best)) { |
5915 | case OR_Success: |
5916 | ND = Best->FoundDecl; |
5917 | Corrected.setCorrectionDecl(ND); |
5918 | break; |
5919 | default: |
5920 | break; |
5921 | } |
5922 | } |
5923 | ND = ND->getUnderlyingDecl(); |
5924 | if (isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND)) |
5925 | return Corrected; |
5926 | } |
5927 | } |
5928 | return TypoCorrection(); |
5929 | } |
5930 | |
5931 | // [C++26][[expr.unary.op]/p4 |
5932 | // A pointer to member is only formed when an explicit & |
5933 | // is used and its operand is a qualified-id not enclosed in parentheses. |
5934 | static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) { |
5935 | if (!isa<ParenExpr>(Val: Fn)) |
5936 | return false; |
5937 | |
5938 | Fn = Fn->IgnoreParens(); |
5939 | |
5940 | auto *UO = dyn_cast<UnaryOperator>(Val: Fn); |
5941 | if (!UO || UO->getOpcode() != clang::UO_AddrOf) |
5942 | return false; |
5943 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParens())) { |
5944 | return DRE->hasQualifier(); |
5945 | } |
5946 | if (auto *OVL = dyn_cast<OverloadExpr>(Val: UO->getSubExpr()->IgnoreParens())) |
5947 | return OVL->getQualifier(); |
5948 | return false; |
5949 | } |
5950 | |
5951 | bool |
5952 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
5953 | FunctionDecl *FDecl, |
5954 | const FunctionProtoType *Proto, |
5955 | ArrayRef<Expr *> Args, |
5956 | SourceLocation RParenLoc, |
5957 | bool IsExecConfig) { |
5958 | // Bail out early if calling a builtin with custom typechecking. |
5959 | if (FDecl) |
5960 | if (unsigned ID = FDecl->getBuiltinID()) |
5961 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) |
5962 | return false; |
5963 | |
5964 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by |
5965 | // assignment, to the types of the corresponding parameter, ... |
5966 | |
5967 | bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn); |
5968 | bool HasExplicitObjectParameter = |
5969 | !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter(); |
5970 | unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0; |
5971 | unsigned NumParams = Proto->getNumParams(); |
5972 | bool Invalid = false; |
5973 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; |
5974 | unsigned FnKind = Fn->getType()->isBlockPointerType() |
5975 | ? 1 /* block */ |
5976 | : (IsExecConfig ? 3 /* kernel function (exec config) */ |
5977 | : 0 /* function */); |
5978 | |
5979 | // If too few arguments are available (and we don't have default |
5980 | // arguments for the remaining parameters), don't make the call. |
5981 | if (Args.size() < NumParams) { |
5982 | if (Args.size() < MinArgs) { |
5983 | TypoCorrection TC; |
5984 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
5985 | unsigned diag_id = |
5986 | MinArgs == NumParams && !Proto->isVariadic() |
5987 | ? diag::err_typecheck_call_too_few_args_suggest |
5988 | : diag::err_typecheck_call_too_few_args_at_least_suggest; |
5989 | diagnoseTypo( |
5990 | TC, PDiag(diag_id) |
5991 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
5992 | << static_cast<unsigned>(Args.size()) - |
5993 | ExplicitObjectParameterOffset |
5994 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
5995 | } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl && |
5996 | FDecl->getParamDecl(ExplicitObjectParameterOffset) |
5997 | ->getDeclName()) |
5998 | Diag(RParenLoc, |
5999 | MinArgs == NumParams && !Proto->isVariadic() |
6000 | ? diag::err_typecheck_call_too_few_args_one |
6001 | : diag::err_typecheck_call_too_few_args_at_least_one) |
6002 | << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset) |
6003 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
6004 | else |
6005 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() |
6006 | ? diag::err_typecheck_call_too_few_args |
6007 | : diag::err_typecheck_call_too_few_args_at_least) |
6008 | << FnKind << MinArgs - ExplicitObjectParameterOffset |
6009 | << static_cast<unsigned>(Args.size()) - |
6010 | ExplicitObjectParameterOffset |
6011 | << HasExplicitObjectParameter << Fn->getSourceRange(); |
6012 | |
6013 | // Emit the location of the prototype. |
6014 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
6015 | Diag(FDecl->getLocation(), diag::note_callee_decl) |
6016 | << FDecl << FDecl->getParametersSourceRange(); |
6017 | |
6018 | return true; |
6019 | } |
6020 | // We reserve space for the default arguments when we create |
6021 | // the call expression, before calling ConvertArgumentsForCall. |
6022 | assert((Call->getNumArgs() == NumParams) && |
6023 | "We should have reserved space for the default arguments before!"); |
6024 | } |
6025 | |
6026 | // If too many are passed and not variadic, error on the extras and drop |
6027 | // them. |
6028 | if (Args.size() > NumParams) { |
6029 | if (!Proto->isVariadic()) { |
6030 | TypoCorrection TC; |
6031 | if (FDecl && (TC = TryTypoCorrectionForCall(S&: *this, Fn, FDecl, Args))) { |
6032 | unsigned diag_id = |
6033 | MinArgs == NumParams && !Proto->isVariadic() |
6034 | ? diag::err_typecheck_call_too_many_args_suggest |
6035 | : diag::err_typecheck_call_too_many_args_at_most_suggest; |
6036 | diagnoseTypo( |
6037 | TC, PDiag(diag_id) |
6038 | << FnKind << NumParams - ExplicitObjectParameterOffset |
6039 | << static_cast<unsigned>(Args.size()) - |
6040 | ExplicitObjectParameterOffset |
6041 | << HasExplicitObjectParameter << TC.getCorrectionRange()); |
6042 | } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl && |
6043 | FDecl->getParamDecl(ExplicitObjectParameterOffset) |
6044 | ->getDeclName()) |
6045 | Diag(Args[NumParams]->getBeginLoc(), |
6046 | MinArgs == NumParams |
6047 | ? diag::err_typecheck_call_too_many_args_one |
6048 | : diag::err_typecheck_call_too_many_args_at_most_one) |
6049 | << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset) |
6050 | << static_cast<unsigned>(Args.size()) - |
6051 | ExplicitObjectParameterOffset |
6052 | << HasExplicitObjectParameter << Fn->getSourceRange() |
6053 | << SourceRange(Args[NumParams]->getBeginLoc(), |
6054 | Args.back()->getEndLoc()); |
6055 | else |
6056 | Diag(Args[NumParams]->getBeginLoc(), |
6057 | MinArgs == NumParams |
6058 | ? diag::err_typecheck_call_too_many_args |
6059 | : diag::err_typecheck_call_too_many_args_at_most) |
6060 | << FnKind << NumParams - ExplicitObjectParameterOffset |
6061 | << static_cast<unsigned>(Args.size()) - |
6062 | ExplicitObjectParameterOffset |
6063 | << HasExplicitObjectParameter << Fn->getSourceRange() |
6064 | << SourceRange(Args[NumParams]->getBeginLoc(), |
6065 | Args.back()->getEndLoc()); |
6066 | |
6067 | // Emit the location of the prototype. |
6068 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
6069 | Diag(FDecl->getLocation(), diag::note_callee_decl) |
6070 | << FDecl << FDecl->getParametersSourceRange(); |
6071 | |
6072 | // This deletes the extra arguments. |
6073 | Call->shrinkNumArgs(NewNumArgs: NumParams); |
6074 | return true; |
6075 | } |
6076 | } |
6077 | SmallVector<Expr *, 8> AllArgs; |
6078 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); |
6079 | |
6080 | Invalid = GatherArgumentsForCall(CallLoc: Call->getExprLoc(), FDecl, Proto, FirstParam: 0, Args, |
6081 | AllArgs, CallType); |
6082 | if (Invalid) |
6083 | return true; |
6084 | unsigned TotalNumArgs = AllArgs.size(); |
6085 | for (unsigned i = 0; i < TotalNumArgs; ++i) |
6086 | Call->setArg(Arg: i, ArgExpr: AllArgs[i]); |
6087 | |
6088 | Call->computeDependence(); |
6089 | return false; |
6090 | } |
6091 | |
6092 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
6093 | const FunctionProtoType *Proto, |
6094 | unsigned FirstParam, ArrayRef<Expr *> Args, |
6095 | SmallVectorImpl<Expr *> &AllArgs, |
6096 | VariadicCallType CallType, bool AllowExplicit, |
6097 | bool IsListInitialization) { |
6098 | unsigned NumParams = Proto->getNumParams(); |
6099 | bool Invalid = false; |
6100 | size_t ArgIx = 0; |
6101 | // Continue to check argument types (even if we have too few/many args). |
6102 | for (unsigned i = FirstParam; i < NumParams; i++) { |
6103 | QualType ProtoArgType = Proto->getParamType(i); |
6104 | |
6105 | Expr *Arg; |
6106 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; |
6107 | if (ArgIx < Args.size()) { |
6108 | Arg = Args[ArgIx++]; |
6109 | |
6110 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, |
6111 | diag::err_call_incomplete_argument, Arg)) |
6112 | return true; |
6113 | |
6114 | // Strip the unbridged-cast placeholder expression off, if applicable. |
6115 | bool CFAudited = false; |
6116 | if (Arg->getType() == Context.ARCUnbridgedCastTy && |
6117 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
6118 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
6119 | Arg = ObjC().stripARCUnbridgedCast(e: Arg); |
6120 | else if (getLangOpts().ObjCAutoRefCount && |
6121 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
6122 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
6123 | CFAudited = true; |
6124 | |
6125 | if (Proto->getExtParameterInfo(I: i).isNoEscape() && |
6126 | ProtoArgType->isBlockPointerType()) |
6127 | if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context))) |
6128 | BE->getBlockDecl()->setDoesNotEscape(); |
6129 | if ((Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLOut || |
6130 | Proto->getExtParameterInfo(I: i).getABI() == ParameterABI::HLSLInOut)) { |
6131 | ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg); |
6132 | if (ArgExpr.isInvalid()) |
6133 | return true; |
6134 | Arg = ArgExpr.getAs<Expr>(); |
6135 | } |
6136 | |
6137 | InitializedEntity Entity = |
6138 | Param ? InitializedEntity::InitializeParameter(Context, Parm: Param, |
6139 | Type: ProtoArgType) |
6140 | : InitializedEntity::InitializeParameter( |
6141 | Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i)); |
6142 | |
6143 | // Remember that parameter belongs to a CF audited API. |
6144 | if (CFAudited) |
6145 | Entity.setParameterCFAudited(); |
6146 | |
6147 | ExprResult ArgE = PerformCopyInitialization( |
6148 | Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: IsListInitialization, AllowExplicit); |
6149 | if (ArgE.isInvalid()) |
6150 | return true; |
6151 | |
6152 | Arg = ArgE.getAs<Expr>(); |
6153 | } else { |
6154 | assert(Param && "can't use default arguments without a known callee"); |
6155 | |
6156 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FD: FDecl, Param); |
6157 | if (ArgExpr.isInvalid()) |
6158 | return true; |
6159 | |
6160 | Arg = ArgExpr.getAs<Expr>(); |
6161 | } |
6162 | |
6163 | // Check for array bounds violations for each argument to the call. This |
6164 | // check only triggers warnings when the argument isn't a more complex Expr |
6165 | // with its own checking, such as a BinaryOperator. |
6166 | CheckArrayAccess(E: Arg); |
6167 | |
6168 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). |
6169 | CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg); |
6170 | |
6171 | AllArgs.push_back(Elt: Arg); |
6172 | } |
6173 | |
6174 | // If this is a variadic call, handle args passed through "...". |
6175 | if (CallType != VariadicCallType::DoesNotApply) { |
6176 | // Assume that extern "C" functions with variadic arguments that |
6177 | // return __unknown_anytype aren't *really* variadic. |
6178 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && |
6179 | FDecl->isExternC()) { |
6180 | for (Expr *A : Args.slice(N: ArgIx)) { |
6181 | QualType paramType; // ignored |
6182 | ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType); |
6183 | Invalid |= arg.isInvalid(); |
6184 | AllArgs.push_back(Elt: arg.get()); |
6185 | } |
6186 | |
6187 | // Otherwise do argument promotion, (C99 6.5.2.2p7). |
6188 | } else { |
6189 | for (Expr *A : Args.slice(N: ArgIx)) { |
6190 | ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl); |
6191 | Invalid |= Arg.isInvalid(); |
6192 | AllArgs.push_back(Elt: Arg.get()); |
6193 | } |
6194 | } |
6195 | |
6196 | // Check for array bounds violations. |
6197 | for (Expr *A : Args.slice(N: ArgIx)) |
6198 | CheckArrayAccess(E: A); |
6199 | } |
6200 | return Invalid; |
6201 | } |
6202 | |
6203 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { |
6204 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); |
6205 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) |
6206 | TL = DTL.getOriginalLoc(); |
6207 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) |
6208 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) |
6209 | << ATL.getLocalSourceRange(); |
6210 | } |
6211 | |
6212 | void |
6213 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, |
6214 | ParmVarDecl *Param, |
6215 | const Expr *ArgExpr) { |
6216 | // Static array parameters are not supported in C++. |
6217 | if (!Param || getLangOpts().CPlusPlus) |
6218 | return; |
6219 | |
6220 | QualType OrigTy = Param->getOriginalType(); |
6221 | |
6222 | const ArrayType *AT = Context.getAsArrayType(T: OrigTy); |
6223 | if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static) |
6224 | return; |
6225 | |
6226 | if (ArgExpr->isNullPointerConstant(Ctx&: Context, |
6227 | NPC: Expr::NPC_NeverValueDependent)) { |
6228 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); |
6229 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6230 | return; |
6231 | } |
6232 | |
6233 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT); |
6234 | if (!CAT) |
6235 | return; |
6236 | |
6237 | const ConstantArrayType *ArgCAT = |
6238 | Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType()); |
6239 | if (!ArgCAT) |
6240 | return; |
6241 | |
6242 | if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(), |
6243 | T2: ArgCAT->getElementType())) { |
6244 | if (ArgCAT->getSize().ult(RHS: CAT->getSize())) { |
6245 | Diag(CallLoc, diag::warn_static_array_too_small) |
6246 | << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize() |
6247 | << (unsigned)CAT->getZExtSize() << 0; |
6248 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6249 | } |
6250 | return; |
6251 | } |
6252 | |
6253 | std::optional<CharUnits> ArgSize = |
6254 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); |
6255 | std::optional<CharUnits> ParmSize = |
6256 | getASTContext().getTypeSizeInCharsIfKnown(CAT); |
6257 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { |
6258 | Diag(CallLoc, diag::warn_static_array_too_small) |
6259 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() |
6260 | << (unsigned)ParmSize->getQuantity() << 1; |
6261 | DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param); |
6262 | } |
6263 | } |
6264 | |
6265 | /// Given a function expression of unknown-any type, try to rebuild it |
6266 | /// to have a function type. |
6267 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); |
6268 | |
6269 | /// Is the given type a placeholder that we need to lower out |
6270 | /// immediately during argument processing? |
6271 | static bool isPlaceholderToRemoveAsArg(QualType type) { |
6272 | // Placeholders are never sugared. |
6273 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: type); |
6274 | if (!placeholder) return false; |
6275 | |
6276 | switch (placeholder->getKind()) { |
6277 | // Ignore all the non-placeholder types. |
6278 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6279 | case BuiltinType::Id: |
6280 | #include "clang/Basic/OpenCLImageTypes.def" |
6281 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6282 | case BuiltinType::Id: |
6283 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6284 | // In practice we'll never use this, since all SVE types are sugared |
6285 | // via TypedefTypes rather than exposed directly as BuiltinTypes. |
6286 | #define SVE_TYPE(Name, Id, SingletonId) \ |
6287 | case BuiltinType::Id: |
6288 | #include "clang/Basic/AArch64ACLETypes.def" |
6289 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
6290 | case BuiltinType::Id: |
6291 | #include "clang/Basic/PPCTypes.def" |
6292 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6293 | #include "clang/Basic/RISCVVTypes.def" |
6294 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6295 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
6296 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: |
6297 | #include "clang/Basic/AMDGPUTypes.def" |
6298 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
6299 | #include "clang/Basic/HLSLIntangibleTypes.def" |
6300 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) |
6301 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: |
6302 | #include "clang/AST/BuiltinTypes.def" |
6303 | return false; |
6304 | |
6305 | case BuiltinType::UnresolvedTemplate: |
6306 | // We cannot lower out overload sets; they might validly be resolved |
6307 | // by the call machinery. |
6308 | case BuiltinType::Overload: |
6309 | return false; |
6310 | |
6311 | // Unbridged casts in ARC can be handled in some call positions and |
6312 | // should be left in place. |
6313 | case BuiltinType::ARCUnbridgedCast: |
6314 | return false; |
6315 | |
6316 | // Pseudo-objects should be converted as soon as possible. |
6317 | case BuiltinType::PseudoObject: |
6318 | return true; |
6319 | |
6320 | // The debugger mode could theoretically but currently does not try |
6321 | // to resolve unknown-typed arguments based on known parameter types. |
6322 | case BuiltinType::UnknownAny: |
6323 | return true; |
6324 | |
6325 | // These are always invalid as call arguments and should be reported. |
6326 | case BuiltinType::BoundMember: |
6327 | case BuiltinType::BuiltinFn: |
6328 | case BuiltinType::IncompleteMatrixIdx: |
6329 | case BuiltinType::ArraySection: |
6330 | case BuiltinType::OMPArrayShaping: |
6331 | case BuiltinType::OMPIterator: |
6332 | return true; |
6333 | |
6334 | } |
6335 | llvm_unreachable("bad builtin type kind"); |
6336 | } |
6337 | |
6338 | bool Sema::CheckArgsForPlaceholders(MultiExprArg args) { |
6339 | // Apply this processing to all the arguments at once instead of |
6340 | // dying at the first failure. |
6341 | bool hasInvalid = false; |
6342 | for (size_t i = 0, e = args.size(); i != e; i++) { |
6343 | if (isPlaceholderToRemoveAsArg(type: args[i]->getType())) { |
6344 | ExprResult result = CheckPlaceholderExpr(E: args[i]); |
6345 | if (result.isInvalid()) hasInvalid = true; |
6346 | else args[i] = result.get(); |
6347 | } |
6348 | } |
6349 | return hasInvalid; |
6350 | } |
6351 | |
6352 | /// If a builtin function has a pointer argument with no explicit address |
6353 | /// space, then it should be able to accept a pointer to any address |
6354 | /// space as input. In order to do this, we need to replace the |
6355 | /// standard builtin declaration with one that uses the same address space |
6356 | /// as the call. |
6357 | /// |
6358 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. |
6359 | /// it does not contain any pointer arguments without |
6360 | /// an address space qualifer. Otherwise the rewritten |
6361 | /// FunctionDecl is returned. |
6362 | /// TODO: Handle pointer return types. |
6363 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, |
6364 | FunctionDecl *FDecl, |
6365 | MultiExprArg ArgExprs) { |
6366 | |
6367 | QualType DeclType = FDecl->getType(); |
6368 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType); |
6369 | |
6370 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: FDecl->getBuiltinID()) || !FT || |
6371 | ArgExprs.size() < FT->getNumParams()) |
6372 | return nullptr; |
6373 | |
6374 | bool NeedsNewDecl = false; |
6375 | unsigned i = 0; |
6376 | SmallVector<QualType, 8> OverloadParams; |
6377 | |
6378 | for (QualType ParamType : FT->param_types()) { |
6379 | |
6380 | // Convert array arguments to pointer to simplify type lookup. |
6381 | ExprResult ArgRes = |
6382 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); |
6383 | if (ArgRes.isInvalid()) |
6384 | return nullptr; |
6385 | Expr *Arg = ArgRes.get(); |
6386 | QualType ArgType = Arg->getType(); |
6387 | if (!ParamType->isPointerType() || |
6388 | ParamType->getPointeeType().hasAddressSpace() || |
6389 | !ArgType->isPointerType() || |
6390 | !ArgType->getPointeeType().hasAddressSpace() || |
6391 | isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) { |
6392 | OverloadParams.push_back(ParamType); |
6393 | continue; |
6394 | } |
6395 | |
6396 | QualType PointeeType = ParamType->getPointeeType(); |
6397 | NeedsNewDecl = true; |
6398 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); |
6399 | |
6400 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); |
6401 | OverloadParams.push_back(Context.getPointerType(PointeeType)); |
6402 | } |
6403 | |
6404 | if (!NeedsNewDecl) |
6405 | return nullptr; |
6406 | |
6407 | FunctionProtoType::ExtProtoInfo EPI; |
6408 | EPI.Variadic = FT->isVariadic(); |
6409 | QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(), |
6410 | Args: OverloadParams, EPI); |
6411 | DeclContext *Parent = FDecl->getParent(); |
6412 | FunctionDecl *OverloadDecl = FunctionDecl::Create( |
6413 | Context, Parent, FDecl->getLocation(), FDecl->getLocation(), |
6414 | FDecl->getIdentifier(), OverloadTy, |
6415 | /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), |
6416 | false, |
6417 | /*hasPrototype=*/true); |
6418 | SmallVector<ParmVarDecl*, 16> Params; |
6419 | FT = cast<FunctionProtoType>(Val&: OverloadTy); |
6420 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
6421 | QualType ParamType = FT->getParamType(i); |
6422 | ParmVarDecl *Parm = |
6423 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), |
6424 | SourceLocation(), nullptr, ParamType, |
6425 | /*TInfo=*/nullptr, SC_None, nullptr); |
6426 | Parm->setScopeInfo(scopeDepth: 0, parameterIndex: i); |
6427 | Params.push_back(Elt: Parm); |
6428 | } |
6429 | OverloadDecl->setParams(Params); |
6430 | // We cannot merge host/device attributes of redeclarations. They have to |
6431 | // be consistent when created. |
6432 | if (Sema->LangOpts.CUDA) { |
6433 | if (FDecl->hasAttr<CUDAHostAttr>()) |
6434 | OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context)); |
6435 | if (FDecl->hasAttr<CUDADeviceAttr>()) |
6436 | OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context)); |
6437 | } |
6438 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); |
6439 | return OverloadDecl; |
6440 | } |
6441 | |
6442 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, |
6443 | FunctionDecl *Callee, |
6444 | MultiExprArg ArgExprs) { |
6445 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and |
6446 | // similar attributes) really don't like it when functions are called with an |
6447 | // invalid number of args. |
6448 | if (S.TooManyArguments(NumParams: Callee->getNumParams(), NumArgs: ArgExprs.size(), |
6449 | /*PartialOverloading=*/false) && |
6450 | !Callee->isVariadic()) |
6451 | return; |
6452 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) |
6453 | return; |
6454 | |
6455 | if (const EnableIfAttr *Attr = |
6456 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { |
6457 | S.Diag(Fn->getBeginLoc(), |
6458 | isa<CXXMethodDecl>(Callee) |
6459 | ? diag::err_ovl_no_viable_member_function_in_call |
6460 | : diag::err_ovl_no_viable_function_in_call) |
6461 | << Callee << Callee->getSourceRange(); |
6462 | S.Diag(Callee->getLocation(), |
6463 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
6464 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
6465 | return; |
6466 | } |
6467 | } |
6468 | |
6469 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( |
6470 | const UnresolvedMemberExpr *const UME, Sema &S) { |
6471 | |
6472 | const auto GetFunctionLevelDCIfCXXClass = |
6473 | [](Sema &S) -> const CXXRecordDecl * { |
6474 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); |
6475 | if (!DC || !DC->getParent()) |
6476 | return nullptr; |
6477 | |
6478 | // If the call to some member function was made from within a member |
6479 | // function body 'M' return return 'M's parent. |
6480 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC)) |
6481 | return MD->getParent()->getCanonicalDecl(); |
6482 | // else the call was made from within a default member initializer of a |
6483 | // class, so return the class. |
6484 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) |
6485 | return RD->getCanonicalDecl(); |
6486 | return nullptr; |
6487 | }; |
6488 | // If our DeclContext is neither a member function nor a class (in the |
6489 | // case of a lambda in a default member initializer), we can't have an |
6490 | // enclosing 'this'. |
6491 | |
6492 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); |
6493 | if (!CurParentClass) |
6494 | return false; |
6495 | |
6496 | // The naming class for implicit member functions call is the class in which |
6497 | // name lookup starts. |
6498 | const CXXRecordDecl *const NamingClass = |
6499 | UME->getNamingClass()->getCanonicalDecl(); |
6500 | assert(NamingClass && "Must have naming class even for implicit access"); |
6501 | |
6502 | // If the unresolved member functions were found in a 'naming class' that is |
6503 | // related (either the same or derived from) to the class that contains the |
6504 | // member function that itself contained the implicit member access. |
6505 | |
6506 | return CurParentClass == NamingClass || |
6507 | CurParentClass->isDerivedFrom(Base: NamingClass); |
6508 | } |
6509 | |
6510 | static void |
6511 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
6512 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { |
6513 | |
6514 | if (!UME) |
6515 | return; |
6516 | |
6517 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); |
6518 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't |
6519 | // already been captured, or if this is an implicit member function call (if |
6520 | // it isn't, an attempt to capture 'this' should already have been made). |
6521 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || |
6522 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) |
6523 | return; |
6524 | |
6525 | // Check if the naming class in which the unresolved members were found is |
6526 | // related (same as or is a base of) to the enclosing class. |
6527 | |
6528 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) |
6529 | return; |
6530 | |
6531 | |
6532 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); |
6533 | // If the enclosing function is not dependent, then this lambda is |
6534 | // capture ready, so if we can capture this, do so. |
6535 | if (!EnclosingFunctionCtx->isDependentContext()) { |
6536 | // If the current lambda and all enclosing lambdas can capture 'this' - |
6537 | // then go ahead and capture 'this' (since our unresolved overload set |
6538 | // contains at least one non-static member function). |
6539 | if (!S.CheckCXXThisCapture(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false)) |
6540 | S.CheckCXXThisCapture(Loc: CallLoc); |
6541 | } else if (S.CurContext->isDependentContext()) { |
6542 | // ... since this is an implicit member reference, that might potentially |
6543 | // involve a 'this' capture, mark 'this' for potential capture in |
6544 | // enclosing lambdas. |
6545 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) |
6546 | CurLSI->addPotentialThisCapture(Loc: CallLoc); |
6547 | } |
6548 | } |
6549 | |
6550 | // Once a call is fully resolved, warn for unqualified calls to specific |
6551 | // C++ standard functions, like move and forward. |
6552 | static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, |
6553 | const CallExpr *Call) { |
6554 | // We are only checking unary move and forward so exit early here. |
6555 | if (Call->getNumArgs() != 1) |
6556 | return; |
6557 | |
6558 | const Expr *E = Call->getCallee()->IgnoreParenImpCasts(); |
6559 | if (!E || isa<UnresolvedLookupExpr>(Val: E)) |
6560 | return; |
6561 | const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: E); |
6562 | if (!DRE || !DRE->getLocation().isValid()) |
6563 | return; |
6564 | |
6565 | if (DRE->getQualifier()) |
6566 | return; |
6567 | |
6568 | const FunctionDecl *FD = Call->getDirectCallee(); |
6569 | if (!FD) |
6570 | return; |
6571 | |
6572 | // Only warn for some functions deemed more frequent or problematic. |
6573 | unsigned BuiltinID = FD->getBuiltinID(); |
6574 | if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) |
6575 | return; |
6576 | |
6577 | S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) |
6578 | << FD->getQualifiedNameAsString() |
6579 | << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); |
6580 | } |
6581 | |
6582 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
6583 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6584 | Expr *ExecConfig) { |
6585 | ExprResult Call = |
6586 | BuildCallExpr(S: Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, |
6587 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); |
6588 | if (Call.isInvalid()) |
6589 | return Call; |
6590 | |
6591 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier |
6592 | // language modes. |
6593 | if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: Fn); |
6594 | ULE && ULE->hasExplicitTemplateArgs() && |
6595 | ULE->decls_begin() == ULE->decls_end()) { |
6596 | DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id) |
6597 | << ULE->getName(); |
6598 | } |
6599 | |
6600 | if (LangOpts.OpenMP) |
6601 | Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, |
6602 | ExecConfig); |
6603 | if (LangOpts.CPlusPlus) { |
6604 | if (const auto *CE = dyn_cast<CallExpr>(Val: Call.get())) |
6605 | DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE); |
6606 | |
6607 | // If we previously found that the id-expression of this call refers to a |
6608 | // consteval function but the call is dependent, we should not treat is an |
6609 | // an invalid immediate call. |
6610 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Fn->IgnoreParens()); |
6611 | DRE && Call.get()->isValueDependent()) { |
6612 | currentEvaluationContext().ReferenceToConsteval.erase(Ptr: DRE); |
6613 | } |
6614 | } |
6615 | return Call; |
6616 | } |
6617 | |
6618 | // Any type that could be used to form a callable expression |
6619 | static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) { |
6620 | QualType T = E->getType(); |
6621 | if (T->isDependentType()) |
6622 | return true; |
6623 | |
6624 | if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy || |
6625 | T == Context.BuiltinFnTy || T == Context.OverloadTy || |
6626 | T->isFunctionType() || T->isFunctionReferenceType() || |
6627 | T->isMemberFunctionPointerType() || T->isFunctionPointerType() || |
6628 | T->isBlockPointerType() || T->isRecordType()) |
6629 | return true; |
6630 | |
6631 | return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr, |
6632 | OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(Val: E); |
6633 | } |
6634 | |
6635 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
6636 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
6637 | Expr *ExecConfig, bool IsExecConfig, |
6638 | bool AllowRecovery) { |
6639 | // Since this might be a postfix expression, get rid of ParenListExprs. |
6640 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn); |
6641 | if (Result.isInvalid()) return ExprError(); |
6642 | Fn = Result.get(); |
6643 | |
6644 | if (CheckArgsForPlaceholders(args: ArgExprs)) |
6645 | return ExprError(); |
6646 | |
6647 | // The result of __builtin_counted_by_ref cannot be used as a function |
6648 | // argument. It allows leaking and modification of bounds safety information. |
6649 | for (const Expr *Arg : ArgExprs) |
6650 | if (CheckInvalidBuiltinCountedByRef(E: Arg, |
6651 | K: BuiltinCountedByRefKind::FunctionArg)) |
6652 | return ExprError(); |
6653 | |
6654 | if (getLangOpts().CPlusPlus) { |
6655 | // If this is a pseudo-destructor expression, build the call immediately. |
6656 | if (isa<CXXPseudoDestructorExpr>(Val: Fn)) { |
6657 | if (!ArgExprs.empty()) { |
6658 | // Pseudo-destructor calls should not have any arguments. |
6659 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) |
6660 | << FixItHint::CreateRemoval( |
6661 | SourceRange(ArgExprs.front()->getBeginLoc(), |
6662 | ArgExprs.back()->getEndLoc())); |
6663 | } |
6664 | |
6665 | return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy, |
6666 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6667 | } |
6668 | if (Fn->getType() == Context.PseudoObjectTy) { |
6669 | ExprResult result = CheckPlaceholderExpr(E: Fn); |
6670 | if (result.isInvalid()) return ExprError(); |
6671 | Fn = result.get(); |
6672 | } |
6673 | |
6674 | // Determine whether this is a dependent call inside a C++ template, |
6675 | // in which case we won't do any semantic analysis now. |
6676 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) { |
6677 | if (ExecConfig) { |
6678 | return CUDAKernelCallExpr::Create(Ctx: Context, Fn, |
6679 | Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs, |
6680 | Ty: Context.DependentTy, VK: VK_PRValue, |
6681 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6682 | } else { |
6683 | |
6684 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
6685 | *this, dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()), |
6686 | Fn->getBeginLoc()); |
6687 | |
6688 | // If the type of the function itself is not dependent |
6689 | // check that it is a reasonable as a function, as type deduction |
6690 | // later assume the CallExpr has a sensible TYPE. |
6691 | if (!MayBeFunctionType(Context, Fn)) |
6692 | return ExprError( |
6693 | Diag(LParenLoc, diag::err_typecheck_call_not_function) |
6694 | << Fn->getType() << Fn->getSourceRange()); |
6695 | |
6696 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6697 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6698 | } |
6699 | } |
6700 | |
6701 | // Determine whether this is a call to an object (C++ [over.call.object]). |
6702 | if (Fn->getType()->isRecordType()) |
6703 | return BuildCallToObjectOfClassType(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs, |
6704 | RParenLoc); |
6705 | |
6706 | if (Fn->getType() == Context.UnknownAnyTy) { |
6707 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6708 | if (result.isInvalid()) return ExprError(); |
6709 | Fn = result.get(); |
6710 | } |
6711 | |
6712 | if (Fn->getType() == Context.BoundMemberTy) { |
6713 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
6714 | RParenLoc, ExecConfig, IsExecConfig, |
6715 | AllowRecovery); |
6716 | } |
6717 | } |
6718 | |
6719 | // Check for overloaded calls. This can happen even in C due to extensions. |
6720 | if (Fn->getType() == Context.OverloadTy) { |
6721 | OverloadExpr::FindResult find = OverloadExpr::find(E: Fn); |
6722 | |
6723 | // We aren't supposed to apply this logic if there's an '&' involved. |
6724 | if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) { |
6725 | if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) |
6726 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6727 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6728 | OverloadExpr *ovl = find.Expression; |
6729 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl)) |
6730 | return BuildOverloadedCallExpr( |
6731 | S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig, |
6732 | /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand); |
6733 | return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: ArgExprs, |
6734 | RParenLoc, ExecConfig, IsExecConfig, |
6735 | AllowRecovery); |
6736 | } |
6737 | } |
6738 | |
6739 | // If we're directly calling a function, get the appropriate declaration. |
6740 | if (Fn->getType() == Context.UnknownAnyTy) { |
6741 | ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6742 | if (result.isInvalid()) return ExprError(); |
6743 | Fn = result.get(); |
6744 | } |
6745 | |
6746 | Expr *NakedFn = Fn->IgnoreParens(); |
6747 | |
6748 | bool CallingNDeclIndirectly = false; |
6749 | NamedDecl *NDecl = nullptr; |
6750 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: NakedFn)) { |
6751 | if (UnOp->getOpcode() == UO_AddrOf) { |
6752 | CallingNDeclIndirectly = true; |
6753 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); |
6754 | } |
6755 | } |
6756 | |
6757 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) { |
6758 | NDecl = DRE->getDecl(); |
6759 | |
6760 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: NDecl); |
6761 | if (FDecl && FDecl->getBuiltinID()) { |
6762 | // Rewrite the function decl for this builtin by replacing parameters |
6763 | // with no explicit address space with the address space of the arguments |
6764 | // in ArgExprs. |
6765 | if ((FDecl = |
6766 | rewriteBuiltinFunctionDecl(Sema: this, Context, FDecl, ArgExprs))) { |
6767 | NDecl = FDecl; |
6768 | Fn = DeclRefExpr::Create( |
6769 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, |
6770 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, |
6771 | nullptr, DRE->isNonOdrUse()); |
6772 | } |
6773 | } |
6774 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: NakedFn)) |
6775 | NDecl = ME->getMemberDecl(); |
6776 | |
6777 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) { |
6778 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( |
6779 | Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc())) |
6780 | return ExprError(); |
6781 | |
6782 | checkDirectCallValidity(S&: *this, Fn, Callee: FD, ArgExprs); |
6783 | |
6784 | // If this expression is a call to a builtin function in HIP device |
6785 | // compilation, allow a pointer-type argument to default address space to be |
6786 | // passed as a pointer-type parameter to a non-default address space. |
6787 | // If Arg is declared in the default address space and Param is declared |
6788 | // in a non-default address space, perform an implicit address space cast to |
6789 | // the parameter type. |
6790 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && |
6791 | FD->getBuiltinID()) { |
6792 | for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size(); |
6793 | ++Idx) { |
6794 | ParmVarDecl *Param = FD->getParamDecl(i: Idx); |
6795 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || |
6796 | !ArgExprs[Idx]->getType()->isPointerType()) |
6797 | continue; |
6798 | |
6799 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); |
6800 | auto ArgTy = ArgExprs[Idx]->getType(); |
6801 | auto ArgPtTy = ArgTy->getPointeeType(); |
6802 | auto ArgAS = ArgPtTy.getAddressSpace(); |
6803 | |
6804 | // Add address space cast if target address spaces are different |
6805 | bool NeedImplicitASC = |
6806 | ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. |
6807 | ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS |
6808 | // or from specific AS which has target AS matching that of Param. |
6809 | getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS)); |
6810 | if (!NeedImplicitASC) |
6811 | continue; |
6812 | |
6813 | // First, ensure that the Arg is an RValue. |
6814 | if (ArgExprs[Idx]->isGLValue()) { |
6815 | ArgExprs[Idx] = ImplicitCastExpr::Create( |
6816 | Context, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx], |
6817 | BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
6818 | } |
6819 | |
6820 | // Construct a new arg type with address space of Param |
6821 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); |
6822 | ArgPtQuals.setAddressSpace(ParamAS); |
6823 | auto NewArgPtTy = |
6824 | Context.getQualifiedType(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals); |
6825 | auto NewArgTy = |
6826 | Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy), |
6827 | Qs: ArgTy.getQualifiers()); |
6828 | |
6829 | // Finally perform an implicit address space cast |
6830 | ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy, |
6831 | CK: CK_AddressSpaceConversion) |
6832 | .get(); |
6833 | } |
6834 | } |
6835 | } |
6836 | |
6837 | if (Context.isDependenceAllowed() && |
6838 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) { |
6839 | assert(!getLangOpts().CPlusPlus); |
6840 | assert((Fn->containsErrors() || |
6841 | llvm::any_of(ArgExprs, |
6842 | [](clang::Expr *E) { return E->containsErrors(); })) && |
6843 | "should only occur in error-recovery path."); |
6844 | return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy, |
6845 | VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides()); |
6846 | } |
6847 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc, |
6848 | Config: ExecConfig, IsExecConfig); |
6849 | } |
6850 | |
6851 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, |
6852 | MultiExprArg CallArgs) { |
6853 | std::string Name = Context.BuiltinInfo.getName(ID: Id); |
6854 | LookupResult R(*this, &Context.Idents.get(Name), Loc, |
6855 | Sema::LookupOrdinaryName); |
6856 | LookupName(R, S: TUScope, /*AllowBuiltinCreation=*/true); |
6857 | |
6858 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); |
6859 | assert(BuiltInDecl && "failed to find builtin declaration"); |
6860 | |
6861 | ExprResult DeclRef = |
6862 | BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); |
6863 | assert(DeclRef.isUsable() && "Builtin reference cannot fail"); |
6864 | |
6865 | ExprResult Call = |
6866 | BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc); |
6867 | |
6868 | assert(!Call.isInvalid() && "Call to builtin cannot fail!"); |
6869 | return Call.get(); |
6870 | } |
6871 | |
6872 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
6873 | SourceLocation BuiltinLoc, |
6874 | SourceLocation RParenLoc) { |
6875 | QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy); |
6876 | return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc); |
6877 | } |
6878 | |
6879 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, |
6880 | SourceLocation BuiltinLoc, |
6881 | SourceLocation RParenLoc) { |
6882 | ExprValueKind VK = VK_PRValue; |
6883 | ExprObjectKind OK = OK_Ordinary; |
6884 | QualType SrcTy = E->getType(); |
6885 | if (!SrcTy->isDependentType() && |
6886 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) |
6887 | return ExprError( |
6888 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) |
6889 | << DestTy << SrcTy << E->getSourceRange()); |
6890 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); |
6891 | } |
6892 | |
6893 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
6894 | SourceLocation BuiltinLoc, |
6895 | SourceLocation RParenLoc) { |
6896 | TypeSourceInfo *TInfo; |
6897 | GetTypeFromParser(Ty: ParsedDestTy, TInfo: &TInfo); |
6898 | return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); |
6899 | } |
6900 | |
6901 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, |
6902 | SourceLocation LParenLoc, |
6903 | ArrayRef<Expr *> Args, |
6904 | SourceLocation RParenLoc, Expr *Config, |
6905 | bool IsExecConfig, ADLCallKind UsesADL) { |
6906 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(Val: NDecl); |
6907 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); |
6908 | |
6909 | // Functions with 'interrupt' attribute cannot be called directly. |
6910 | if (FDecl) { |
6911 | if (FDecl->hasAttr<AnyX86InterruptAttr>()) { |
6912 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); |
6913 | return ExprError(); |
6914 | } |
6915 | if (FDecl->hasAttr<ARMInterruptAttr>()) { |
6916 | Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called); |
6917 | return ExprError(); |
6918 | } |
6919 | } |
6920 | |
6921 | // X86 interrupt handlers may only call routines with attribute |
6922 | // no_caller_saved_registers since there is no efficient way to |
6923 | // save and restore the non-GPR state. |
6924 | if (auto *Caller = getCurFunctionDecl()) { |
6925 | if (Caller->hasAttr<AnyX86InterruptAttr>() || |
6926 | Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) { |
6927 | const TargetInfo &TI = Context.getTargetInfo(); |
6928 | bool HasNonGPRRegisters = |
6929 | TI.hasFeature(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "mmx"); |
6930 | if (HasNonGPRRegisters && |
6931 | (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) { |
6932 | Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave) |
6933 | << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1); |
6934 | if (FDecl) |
6935 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; |
6936 | } |
6937 | } |
6938 | } |
6939 | |
6940 | // Promote the function operand. |
6941 | // We special-case function promotion here because we only allow promoting |
6942 | // builtin functions to function pointers in the callee of a call. |
6943 | ExprResult Result; |
6944 | QualType ResultTy; |
6945 | if (BuiltinID && |
6946 | Fn->getType()->isSpecificBuiltinType(K: BuiltinType::BuiltinFn)) { |
6947 | // Extract the return type from the (builtin) function pointer type. |
6948 | // FIXME Several builtins still have setType in |
6949 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in |
6950 | // Builtins.td to ensure they are correct before removing setType calls. |
6951 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); |
6952 | Result = ImpCastExprToType(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get(); |
6953 | ResultTy = FDecl->getCallResultType(); |
6954 | } else { |
6955 | Result = CallExprUnaryConversions(E: Fn); |
6956 | ResultTy = Context.BoolTy; |
6957 | } |
6958 | if (Result.isInvalid()) |
6959 | return ExprError(); |
6960 | Fn = Result.get(); |
6961 | |
6962 | // Check for a valid function type, but only if it is not a builtin which |
6963 | // requires custom type checking. These will be handled by |
6964 | // CheckBuiltinFunctionCall below just after creation of the call expression. |
6965 | const FunctionType *FuncT = nullptr; |
6966 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
6967 | retry: |
6968 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { |
6969 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall |
6970 | // have type pointer to function". |
6971 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); |
6972 | if (!FuncT) |
6973 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) |
6974 | << Fn->getType() << Fn->getSourceRange()); |
6975 | } else if (const BlockPointerType *BPT = |
6976 | Fn->getType()->getAs<BlockPointerType>()) { |
6977 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); |
6978 | } else { |
6979 | // Handle calls to expressions of unknown-any type. |
6980 | if (Fn->getType() == Context.UnknownAnyTy) { |
6981 | ExprResult rewrite = rebuildUnknownAnyFunction(S&: *this, fn: Fn); |
6982 | if (rewrite.isInvalid()) |
6983 | return ExprError(); |
6984 | Fn = rewrite.get(); |
6985 | goto retry; |
6986 | } |
6987 | |
6988 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) |
6989 | << Fn->getType() << Fn->getSourceRange()); |
6990 | } |
6991 | } |
6992 | |
6993 | // Get the number of parameters in the function prototype, if any. |
6994 | // We will allocate space for max(Args.size(), NumParams) arguments |
6995 | // in the call expression. |
6996 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FuncT); |
6997 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; |
6998 | |
6999 | CallExpr *TheCall; |
7000 | if (Config) { |
7001 | assert(UsesADL == ADLCallKind::NotADL && |
7002 | "CUDAKernelCallExpr should not use ADL"); |
7003 | TheCall = CUDAKernelCallExpr::Create(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), |
7004 | Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc, |
7005 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams); |
7006 | } else { |
7007 | TheCall = |
7008 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc, |
7009 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL); |
7010 | } |
7011 | |
7012 | if (!Context.isDependenceAllowed()) { |
7013 | // Forget about the nulled arguments since typo correction |
7014 | // do not handle them well. |
7015 | TheCall->shrinkNumArgs(NewNumArgs: Args.size()); |
7016 | // C cannot always handle TypoExpr nodes in builtin calls and direct |
7017 | // function calls as their argument checking don't necessarily handle |
7018 | // dependent types properly, so make sure any TypoExprs have been |
7019 | // dealt with. |
7020 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); |
7021 | if (!Result.isUsable()) return ExprError(); |
7022 | CallExpr *TheOldCall = TheCall; |
7023 | TheCall = dyn_cast<CallExpr>(Val: Result.get()); |
7024 | bool CorrectedTypos = TheCall != TheOldCall; |
7025 | if (!TheCall) return Result; |
7026 | Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); |
7027 | |
7028 | // A new call expression node was created if some typos were corrected. |
7029 | // However it may not have been constructed with enough storage. In this |
7030 | // case, rebuild the node with enough storage. The waste of space is |
7031 | // immaterial since this only happens when some typos were corrected. |
7032 | if (CorrectedTypos && Args.size() < NumParams) { |
7033 | if (Config) |
7034 | TheCall = CUDAKernelCallExpr::Create( |
7035 | Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), Args, Ty: ResultTy, VK: VK_PRValue, |
7036 | RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams); |
7037 | else |
7038 | TheCall = |
7039 | CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc, |
7040 | FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL); |
7041 | } |
7042 | // We can now handle the nulled arguments for the default arguments. |
7043 | TheCall->setNumArgsUnsafe(std::max<unsigned>(a: Args.size(), b: NumParams)); |
7044 | } |
7045 | |
7046 | // Bail out early if calling a builtin with custom type checking. |
7047 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: BuiltinID)) { |
7048 | ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
7049 | if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(ID: BuiltinID)) |
7050 | E = CheckForImmediateInvocation(E, Decl: FDecl); |
7051 | return E; |
7052 | } |
7053 | |
7054 | if (getLangOpts().CUDA) { |
7055 | if (Config) { |
7056 | // CUDA: Kernel calls must be to global functions |
7057 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) |
7058 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) |
7059 | << FDecl << Fn->getSourceRange()); |
7060 | |
7061 | // CUDA: Kernel function must have 'void' return type |
7062 | if (!FuncT->getReturnType()->isVoidType() && |
7063 | !FuncT->getReturnType()->getAs<AutoType>() && |
7064 | !FuncT->getReturnType()->isInstantiationDependentType()) |
7065 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) |
7066 | << Fn->getType() << Fn->getSourceRange()); |
7067 | } else { |
7068 | // CUDA: Calls to global functions must be configured |
7069 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) |
7070 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) |
7071 | << FDecl << Fn->getSourceRange()); |
7072 | } |
7073 | } |
7074 | |
7075 | // Check for a valid return type |
7076 | if (CheckCallReturnType(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall, |
7077 | FD: FDecl)) |
7078 | return ExprError(); |
7079 | |
7080 | // We know the result type of the call, set it. |
7081 | TheCall->setType(FuncT->getCallResultType(Context)); |
7082 | TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType())); |
7083 | |
7084 | // WebAssembly tables can't be used as arguments. |
7085 | if (Context.getTargetInfo().getTriple().isWasm()) { |
7086 | for (const Expr *Arg : Args) { |
7087 | if (Arg && Arg->getType()->isWebAssemblyTableType()) { |
7088 | return ExprError(Diag(Arg->getExprLoc(), |
7089 | diag::err_wasm_table_as_function_parameter)); |
7090 | } |
7091 | } |
7092 | } |
7093 | |
7094 | if (Proto) { |
7095 | if (ConvertArgumentsForCall(Call: TheCall, Fn, FDecl, Proto, Args, RParenLoc, |
7096 | IsExecConfig)) |
7097 | return ExprError(); |
7098 | } else { |
7099 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); |
7100 | |
7101 | if (FDecl) { |
7102 | // Check if we have too few/too many template arguments, based |
7103 | // on our knowledge of the function definition. |
7104 | const FunctionDecl *Def = nullptr; |
7105 | if (FDecl->hasBody(Definition&: Def) && Args.size() != Def->param_size()) { |
7106 | Proto = Def->getType()->getAs<FunctionProtoType>(); |
7107 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) |
7108 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) |
7109 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); |
7110 | } |
7111 | |
7112 | // If the function we're calling isn't a function prototype, but we have |
7113 | // a function prototype from a prior declaratiom, use that prototype. |
7114 | if (!FDecl->hasPrototype()) |
7115 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); |
7116 | } |
7117 | |
7118 | // If we still haven't found a prototype to use but there are arguments to |
7119 | // the call, diagnose this as calling a function without a prototype. |
7120 | // However, if we found a function declaration, check to see if |
7121 | // -Wdeprecated-non-prototype was disabled where the function was declared. |
7122 | // If so, we will silence the diagnostic here on the assumption that this |
7123 | // interface is intentional and the user knows what they're doing. We will |
7124 | // also silence the diagnostic if there is a function declaration but it |
7125 | // was implicitly defined (the user already gets diagnostics about the |
7126 | // creation of the implicit function declaration, so the additional warning |
7127 | // is not helpful). |
7128 | if (!Proto && !Args.empty() && |
7129 | (!FDecl || (!FDecl->isImplicit() && |
7130 | !Diags.isIgnored(diag::warn_strict_uses_without_prototype, |
7131 | FDecl->getLocation())))) |
7132 | Diag(LParenLoc, diag::warn_strict_uses_without_prototype) |
7133 | << (FDecl != nullptr) << FDecl; |
7134 | |
7135 | // Promote the arguments (C99 6.5.2.2p6). |
7136 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
7137 | Expr *Arg = Args[i]; |
7138 | |
7139 | if (Proto && i < Proto->getNumParams()) { |
7140 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
7141 | Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i)); |
7142 | ExprResult ArgE = |
7143 | PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg); |
7144 | if (ArgE.isInvalid()) |
7145 | return true; |
7146 | |
7147 | Arg = ArgE.getAs<Expr>(); |
7148 | |
7149 | } else { |
7150 | ExprResult ArgE = DefaultArgumentPromotion(E: Arg); |
7151 | |
7152 | if (ArgE.isInvalid()) |
7153 | return true; |
7154 | |
7155 | Arg = ArgE.getAs<Expr>(); |
7156 | } |
7157 | |
7158 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), |
7159 | diag::err_call_incomplete_argument, Arg)) |
7160 | return ExprError(); |
7161 | |
7162 | TheCall->setArg(Arg: i, ArgExpr: Arg); |
7163 | } |
7164 | TheCall->computeDependence(); |
7165 | } |
7166 | |
7167 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) |
7168 | if (Method->isImplicitObjectMemberFunction()) |
7169 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) |
7170 | << Fn->getSourceRange() << 0); |
7171 | |
7172 | // Check for sentinels |
7173 | if (NDecl) |
7174 | DiagnoseSentinelCalls(D: NDecl, Loc: LParenLoc, Args); |
7175 | |
7176 | // Warn for unions passing across security boundary (CMSE). |
7177 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { |
7178 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
7179 | if (const auto *RT = |
7180 | dyn_cast<RecordType>(Val: Args[i]->getType().getCanonicalType())) { |
7181 | if (RT->getDecl()->isOrContainsUnion()) |
7182 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) |
7183 | << 0 << i; |
7184 | } |
7185 | } |
7186 | } |
7187 | |
7188 | // Do special checking on direct calls to functions. |
7189 | if (FDecl) { |
7190 | if (CheckFunctionCall(FDecl, TheCall, Proto)) |
7191 | return ExprError(); |
7192 | |
7193 | checkFortifiedBuiltinMemoryFunction(FD: FDecl, TheCall); |
7194 | |
7195 | if (BuiltinID) |
7196 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
7197 | } else if (NDecl) { |
7198 | if (CheckPointerCall(NDecl, TheCall, Proto)) |
7199 | return ExprError(); |
7200 | } else { |
7201 | if (CheckOtherCall(TheCall, Proto)) |
7202 | return ExprError(); |
7203 | } |
7204 | |
7205 | return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), Decl: FDecl); |
7206 | } |
7207 | |
7208 | ExprResult |
7209 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, |
7210 | SourceLocation RParenLoc, Expr *InitExpr) { |
7211 | assert(Ty && "ActOnCompoundLiteral(): missing type"); |
7212 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); |
7213 | |
7214 | TypeSourceInfo *TInfo; |
7215 | QualType literalType = GetTypeFromParser(Ty, TInfo: &TInfo); |
7216 | if (!TInfo) |
7217 | TInfo = Context.getTrivialTypeSourceInfo(T: literalType); |
7218 | |
7219 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr); |
7220 | } |
7221 | |
7222 | ExprResult |
7223 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, |
7224 | SourceLocation RParenLoc, Expr *LiteralExpr) { |
7225 | QualType literalType = TInfo->getType(); |
7226 | |
7227 | if (literalType->isArrayType()) { |
7228 | if (RequireCompleteSizedType( |
7229 | LParenLoc, Context.getBaseElementType(literalType), |
7230 | diag::err_array_incomplete_or_sizeless_type, |
7231 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
7232 | return ExprError(); |
7233 | if (literalType->isVariableArrayType()) { |
7234 | // C23 6.7.10p4: An entity of variable length array type shall not be |
7235 | // initialized except by an empty initializer. |
7236 | // |
7237 | // The C extension warnings are issued from ParseBraceInitializer() and |
7238 | // do not need to be issued here. However, we continue to issue an error |
7239 | // in the case there are initializers or we are compiling C++. We allow |
7240 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
7241 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
7242 | // FIXME: should we allow this construct in C++ when it makes sense to do |
7243 | // so? |
7244 | // |
7245 | // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name |
7246 | // shall specify an object type or an array of unknown size, but not a |
7247 | // variable length array type. This seems odd, as it allows 'int a[size] = |
7248 | // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard |
7249 | // says, this is what's implemented here for C (except for the extension |
7250 | // that permits constant foldable size arrays) |
7251 | |
7252 | auto diagID = LangOpts.CPlusPlus |
7253 | ? diag::err_variable_object_no_init |
7254 | : diag::err_compound_literal_with_vla_type; |
7255 | if (!tryToFixVariablyModifiedVarType(TInfo, T&: literalType, Loc: LParenLoc, |
7256 | FailedFoldDiagID: diagID)) |
7257 | return ExprError(); |
7258 | } |
7259 | } else if (!literalType->isDependentType() && |
7260 | RequireCompleteType(LParenLoc, literalType, |
7261 | diag::err_typecheck_decl_incomplete_type, |
7262 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
7263 | return ExprError(); |
7264 | |
7265 | InitializedEntity Entity |
7266 | = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo); |
7267 | InitializationKind Kind |
7268 | = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc, |
7269 | TypeRange: SourceRange(LParenLoc, RParenLoc), |
7270 | /*InitList=*/true); |
7271 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); |
7272 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr, |
7273 | ResultType: &literalType); |
7274 | if (Result.isInvalid()) |
7275 | return ExprError(); |
7276 | LiteralExpr = Result.get(); |
7277 | |
7278 | // We treat the compound literal as being at file scope if it's not in a |
7279 | // function or method body, or within the function's prototype scope. This |
7280 | // means the following compound literal is not at file scope: |
7281 | // void func(char *para[(int [1]){ 0 }[0]); |
7282 | const Scope *S = getCurScope(); |
7283 | bool IsFileScope = !CurContext->isFunctionOrMethod() && |
7284 | (!S || !S->isFunctionPrototypeScope()); |
7285 | |
7286 | // In C, compound literals are l-values for some reason. |
7287 | // For GCC compatibility, in C++, file-scope array compound literals with |
7288 | // constant initializers are also l-values, and compound literals are |
7289 | // otherwise prvalues. |
7290 | // |
7291 | // (GCC also treats C++ list-initialized file-scope array prvalues with |
7292 | // constant initializers as l-values, but that's non-conforming, so we don't |
7293 | // follow it there.) |
7294 | // |
7295 | // FIXME: It would be better to handle the lvalue cases as materializing and |
7296 | // lifetime-extending a temporary object, but our materialized temporaries |
7297 | // representation only supports lifetime extension from a variable, not "out |
7298 | // of thin air". |
7299 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer |
7300 | // is bound to the result of applying array-to-pointer decay to the compound |
7301 | // literal. |
7302 | // FIXME: GCC supports compound literals of reference type, which should |
7303 | // obviously have a value kind derived from the kind of reference involved. |
7304 | ExprValueKind VK = |
7305 | (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType())) |
7306 | ? VK_PRValue |
7307 | : VK_LValue; |
7308 | |
7309 | // C99 6.5.2.5 |
7310 | // "If the compound literal occurs outside the body of a function, the |
7311 | // initializer list shall consist of constant expressions." |
7312 | if (IsFileScope) |
7313 | if (auto ILE = dyn_cast<InitListExpr>(Val: LiteralExpr)) |
7314 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { |
7315 | Expr *Init = ILE->getInit(Init: i); |
7316 | if (!Init->isTypeDependent() && !Init->isValueDependent() && |
7317 | !Init->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false)) { |
7318 | Diag(Init->getExprLoc(), diag::err_init_element_not_constant) |
7319 | << Init->getSourceBitField(); |
7320 | return ExprError(); |
7321 | } |
7322 | |
7323 | ILE->setInit(i, ConstantExpr::Create(Context, E: Init)); |
7324 | } |
7325 | |
7326 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK, |
7327 | LiteralExpr, IsFileScope); |
7328 | if (IsFileScope) { |
7329 | if (!LiteralExpr->isTypeDependent() && |
7330 | !LiteralExpr->isValueDependent() && |
7331 | !literalType->isDependentType()) // C99 6.5.2.5p3 |
7332 | if (CheckForConstantInitializer(Init: LiteralExpr)) |
7333 | return ExprError(); |
7334 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && |
7335 | literalType.getAddressSpace() != LangAS::Default) { |
7336 | // Embedded-C extensions to C99 6.5.2.5: |
7337 | // "If the compound literal occurs inside the body of a function, the |
7338 | // type name shall not be qualified by an address-space qualifier." |
7339 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) |
7340 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); |
7341 | return ExprError(); |
7342 | } |
7343 | |
7344 | if (!IsFileScope && !getLangOpts().CPlusPlus) { |
7345 | // Compound literals that have automatic storage duration are destroyed at |
7346 | // the end of the scope in C; in C++, they're just temporaries. |
7347 | |
7348 | // Emit diagnostics if it is or contains a C union type that is non-trivial |
7349 | // to destruct. |
7350 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) |
7351 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
7352 | UseContext: NonTrivialCUnionContext::CompoundLiteral, |
7353 | NonTrivialKind: NTCUK_Destruct); |
7354 | |
7355 | // Diagnose jumps that enter or exit the lifetime of the compound literal. |
7356 | if (literalType.isDestructedType()) { |
7357 | Cleanup.setExprNeedsCleanups(true); |
7358 | ExprCleanupObjects.push_back(Elt: E); |
7359 | getCurFunction()->setHasBranchProtectedScope(); |
7360 | } |
7361 | } |
7362 | |
7363 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || |
7364 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
7365 | checkNonTrivialCUnionInInitializer(Init: E->getInitializer(), |
7366 | Loc: E->getInitializer()->getExprLoc()); |
7367 | |
7368 | return MaybeBindToTemporary(E); |
7369 | } |
7370 | |
7371 | ExprResult |
7372 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7373 | SourceLocation RBraceLoc) { |
7374 | // Only produce each kind of designated initialization diagnostic once. |
7375 | SourceLocation FirstDesignator; |
7376 | bool DiagnosedArrayDesignator = false; |
7377 | bool DiagnosedNestedDesignator = false; |
7378 | bool DiagnosedMixedDesignator = false; |
7379 | |
7380 | // Check that any designated initializers are syntactically valid in the |
7381 | // current language mode. |
7382 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
7383 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(Val: InitArgList[I])) { |
7384 | if (FirstDesignator.isInvalid()) |
7385 | FirstDesignator = DIE->getBeginLoc(); |
7386 | |
7387 | if (!getLangOpts().CPlusPlus) |
7388 | break; |
7389 | |
7390 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { |
7391 | DiagnosedNestedDesignator = true; |
7392 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) |
7393 | << DIE->getDesignatorsSourceRange(); |
7394 | } |
7395 | |
7396 | for (auto &Desig : DIE->designators()) { |
7397 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { |
7398 | DiagnosedArrayDesignator = true; |
7399 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) |
7400 | << Desig.getSourceRange(); |
7401 | } |
7402 | } |
7403 | |
7404 | if (!DiagnosedMixedDesignator && |
7405 | !isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
7406 | DiagnosedMixedDesignator = true; |
7407 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) |
7408 | << DIE->getSourceRange(); |
7409 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) |
7410 | << InitArgList[0]->getSourceRange(); |
7411 | } |
7412 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && |
7413 | isa<DesignatedInitExpr>(Val: InitArgList[0])) { |
7414 | DiagnosedMixedDesignator = true; |
7415 | auto *DIE = cast<DesignatedInitExpr>(Val: InitArgList[0]); |
7416 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) |
7417 | << DIE->getSourceRange(); |
7418 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) |
7419 | << InitArgList[I]->getSourceRange(); |
7420 | } |
7421 | } |
7422 | |
7423 | if (FirstDesignator.isValid()) { |
7424 | // Only diagnose designated initiaization as a C++20 extension if we didn't |
7425 | // already diagnose use of (non-C++20) C99 designator syntax. |
7426 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && |
7427 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { |
7428 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 |
7429 | ? diag::warn_cxx17_compat_designated_init |
7430 | : diag::ext_cxx_designated_init); |
7431 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { |
7432 | Diag(FirstDesignator, diag::ext_designated_init); |
7433 | } |
7434 | } |
7435 | |
7436 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); |
7437 | } |
7438 | |
7439 | ExprResult |
7440 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
7441 | SourceLocation RBraceLoc) { |
7442 | // Semantic analysis for initializers is done by ActOnDeclarator() and |
7443 | // CheckInitializer() - it requires knowledge of the object being initialized. |
7444 | |
7445 | // Immediately handle non-overload placeholders. Overloads can be |
7446 | // resolved contextually, but everything else here can't. |
7447 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
7448 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { |
7449 | ExprResult result = CheckPlaceholderExpr(E: InitArgList[I]); |
7450 | |
7451 | // Ignore failures; dropping the entire initializer list because |
7452 | // of one failure would be terrible for indexing/etc. |
7453 | if (result.isInvalid()) continue; |
7454 | |
7455 | InitArgList[I] = result.get(); |
7456 | } |
7457 | } |
7458 | |
7459 | InitListExpr *E = |
7460 | new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc); |
7461 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. |
7462 | return E; |
7463 | } |
7464 | |
7465 | void Sema::maybeExtendBlockObject(ExprResult &E) { |
7466 | assert(E.get()->getType()->isBlockPointerType()); |
7467 | assert(E.get()->isPRValue()); |
7468 | |
7469 | // Only do this in an r-value context. |
7470 | if (!getLangOpts().ObjCAutoRefCount) return; |
7471 | |
7472 | E = ImplicitCastExpr::Create( |
7473 | Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(), |
7474 | /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
7475 | Cleanup.setExprNeedsCleanups(true); |
7476 | } |
7477 | |
7478 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { |
7479 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. |
7480 | // Also, callers should have filtered out the invalid cases with |
7481 | // pointers. Everything else should be possible. |
7482 | |
7483 | QualType SrcTy = Src.get()->getType(); |
7484 | if (Context.hasSameUnqualifiedType(T1: SrcTy, T2: DestTy)) |
7485 | return CK_NoOp; |
7486 | |
7487 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { |
7488 | case Type::STK_MemberPointer: |
7489 | llvm_unreachable("member pointer type in C"); |
7490 | |
7491 | case Type::STK_CPointer: |
7492 | case Type::STK_BlockPointer: |
7493 | case Type::STK_ObjCObjectPointer: |
7494 | switch (DestTy->getScalarTypeKind()) { |
7495 | case Type::STK_CPointer: { |
7496 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); |
7497 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); |
7498 | if (SrcAS != DestAS) |
7499 | return CK_AddressSpaceConversion; |
7500 | if (Context.hasCvrSimilarType(T1: SrcTy, T2: DestTy)) |
7501 | return CK_NoOp; |
7502 | return CK_BitCast; |
7503 | } |
7504 | case Type::STK_BlockPointer: |
7505 | return (SrcKind == Type::STK_BlockPointer |
7506 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); |
7507 | case Type::STK_ObjCObjectPointer: |
7508 | if (SrcKind == Type::STK_ObjCObjectPointer) |
7509 | return CK_BitCast; |
7510 | if (SrcKind == Type::STK_CPointer) |
7511 | return CK_CPointerToObjCPointerCast; |
7512 | maybeExtendBlockObject(E&: Src); |
7513 | return CK_BlockPointerToObjCPointerCast; |
7514 | case Type::STK_Bool: |
7515 | return CK_PointerToBoolean; |
7516 | case Type::STK_Integral: |
7517 | return CK_PointerToIntegral; |
7518 | case Type::STK_Floating: |
7519 | case Type::STK_FloatingComplex: |
7520 | case Type::STK_IntegralComplex: |
7521 | case Type::STK_MemberPointer: |
7522 | case Type::STK_FixedPoint: |
7523 | llvm_unreachable("illegal cast from pointer"); |
7524 | } |
7525 | llvm_unreachable("Should have returned before this"); |
7526 | |
7527 | case Type::STK_FixedPoint: |
7528 | switch (DestTy->getScalarTypeKind()) { |
7529 | case Type::STK_FixedPoint: |
7530 | return CK_FixedPointCast; |
7531 | case Type::STK_Bool: |
7532 | return CK_FixedPointToBoolean; |
7533 | case Type::STK_Integral: |
7534 | return CK_FixedPointToIntegral; |
7535 | case Type::STK_Floating: |
7536 | return CK_FixedPointToFloating; |
7537 | case Type::STK_IntegralComplex: |
7538 | case Type::STK_FloatingComplex: |
7539 | Diag(Src.get()->getExprLoc(), |
7540 | diag::err_unimplemented_conversion_with_fixed_point_type) |
7541 | << DestTy; |
7542 | return CK_IntegralCast; |
7543 | case Type::STK_CPointer: |
7544 | case Type::STK_ObjCObjectPointer: |
7545 | case Type::STK_BlockPointer: |
7546 | case Type::STK_MemberPointer: |
7547 | llvm_unreachable("illegal cast to pointer type"); |
7548 | } |
7549 | llvm_unreachable("Should have returned before this"); |
7550 | |
7551 | case Type::STK_Bool: // casting from bool is like casting from an integer |
7552 | case Type::STK_Integral: |
7553 | switch (DestTy->getScalarTypeKind()) { |
7554 | case Type::STK_CPointer: |
7555 | case Type::STK_ObjCObjectPointer: |
7556 | case Type::STK_BlockPointer: |
7557 | if (Src.get()->isNullPointerConstant(Ctx&: Context, |
7558 | NPC: Expr::NPC_ValueDependentIsNull)) |
7559 | return CK_NullToPointer; |
7560 | return CK_IntegralToPointer; |
7561 | case Type::STK_Bool: |
7562 | return CK_IntegralToBoolean; |
7563 | case Type::STK_Integral: |
7564 | return CK_IntegralCast; |
7565 | case Type::STK_Floating: |
7566 | return CK_IntegralToFloating; |
7567 | case Type::STK_IntegralComplex: |
7568 | Src = ImpCastExprToType(E: Src.get(), |
7569 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7570 | CK: CK_IntegralCast); |
7571 | return CK_IntegralRealToComplex; |
7572 | case Type::STK_FloatingComplex: |
7573 | Src = ImpCastExprToType(E: Src.get(), |
7574 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7575 | CK: CK_IntegralToFloating); |
7576 | return CK_FloatingRealToComplex; |
7577 | case Type::STK_MemberPointer: |
7578 | llvm_unreachable("member pointer type in C"); |
7579 | case Type::STK_FixedPoint: |
7580 | return CK_IntegralToFixedPoint; |
7581 | } |
7582 | llvm_unreachable("Should have returned before this"); |
7583 | |
7584 | case Type::STK_Floating: |
7585 | switch (DestTy->getScalarTypeKind()) { |
7586 | case Type::STK_Floating: |
7587 | return CK_FloatingCast; |
7588 | case Type::STK_Bool: |
7589 | return CK_FloatingToBoolean; |
7590 | case Type::STK_Integral: |
7591 | return CK_FloatingToIntegral; |
7592 | case Type::STK_FloatingComplex: |
7593 | Src = ImpCastExprToType(E: Src.get(), |
7594 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7595 | CK: CK_FloatingCast); |
7596 | return CK_FloatingRealToComplex; |
7597 | case Type::STK_IntegralComplex: |
7598 | Src = ImpCastExprToType(E: Src.get(), |
7599 | Type: DestTy->castAs<ComplexType>()->getElementType(), |
7600 | CK: CK_FloatingToIntegral); |
7601 | return CK_IntegralRealToComplex; |
7602 | case Type::STK_CPointer: |
7603 | case Type::STK_ObjCObjectPointer: |
7604 | case Type::STK_BlockPointer: |
7605 | llvm_unreachable("valid float->pointer cast?"); |
7606 | case Type::STK_MemberPointer: |
7607 | llvm_unreachable("member pointer type in C"); |
7608 | case Type::STK_FixedPoint: |
7609 | return CK_FloatingToFixedPoint; |
7610 | } |
7611 | llvm_unreachable("Should have returned before this"); |
7612 | |
7613 | case Type::STK_FloatingComplex: |
7614 | switch (DestTy->getScalarTypeKind()) { |
7615 | case Type::STK_FloatingComplex: |
7616 | return CK_FloatingComplexCast; |
7617 | case Type::STK_IntegralComplex: |
7618 | return CK_FloatingComplexToIntegralComplex; |
7619 | case Type::STK_Floating: { |
7620 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
7621 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
7622 | return CK_FloatingComplexToReal; |
7623 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal); |
7624 | return CK_FloatingCast; |
7625 | } |
7626 | case Type::STK_Bool: |
7627 | return CK_FloatingComplexToBoolean; |
7628 | case Type::STK_Integral: |
7629 | Src = ImpCastExprToType(E: Src.get(), |
7630 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
7631 | CK: CK_FloatingComplexToReal); |
7632 | return CK_FloatingToIntegral; |
7633 | case Type::STK_CPointer: |
7634 | case Type::STK_ObjCObjectPointer: |
7635 | case Type::STK_BlockPointer: |
7636 | llvm_unreachable("valid complex float->pointer cast?"); |
7637 | case Type::STK_MemberPointer: |
7638 | llvm_unreachable("member pointer type in C"); |
7639 | case Type::STK_FixedPoint: |
7640 | Diag(Src.get()->getExprLoc(), |
7641 | diag::err_unimplemented_conversion_with_fixed_point_type) |
7642 | << SrcTy; |
7643 | return CK_IntegralCast; |
7644 | } |
7645 | llvm_unreachable("Should have returned before this"); |
7646 | |
7647 | case Type::STK_IntegralComplex: |
7648 | switch (DestTy->getScalarTypeKind()) { |
7649 | case Type::STK_FloatingComplex: |
7650 | return CK_IntegralComplexToFloatingComplex; |
7651 | case Type::STK_IntegralComplex: |
7652 | return CK_IntegralComplexCast; |
7653 | case Type::STK_Integral: { |
7654 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
7655 | if (Context.hasSameType(T1: ET, T2: DestTy)) |
7656 | return CK_IntegralComplexToReal; |
7657 | Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal); |
7658 | return CK_IntegralCast; |
7659 | } |
7660 | case Type::STK_Bool: |
7661 | return CK_IntegralComplexToBoolean; |
7662 | case Type::STK_Floating: |
7663 | Src = ImpCastExprToType(E: Src.get(), |
7664 | Type: SrcTy->castAs<ComplexType>()->getElementType(), |
7665 | CK: CK_IntegralComplexToReal); |
7666 | return CK_IntegralToFloating; |
7667 | case Type::STK_CPointer: |
7668 | case Type::STK_ObjCObjectPointer: |
7669 | case Type::STK_BlockPointer: |
7670 | llvm_unreachable("valid complex int->pointer cast?"); |
7671 | case Type::STK_MemberPointer: |
7672 | llvm_unreachable("member pointer type in C"); |
7673 | case Type::STK_FixedPoint: |
7674 | Diag(Src.get()->getExprLoc(), |
7675 | diag::err_unimplemented_conversion_with_fixed_point_type) |
7676 | << SrcTy; |
7677 | return CK_IntegralCast; |
7678 | } |
7679 | llvm_unreachable("Should have returned before this"); |
7680 | } |
7681 | |
7682 | llvm_unreachable("Unhandled scalar cast"); |
7683 | } |
7684 | |
7685 | static bool breakDownVectorType(QualType type, uint64_t &len, |
7686 | QualType &eltType) { |
7687 | // Vectors are simple. |
7688 | if (const VectorType *vecType = type->getAs<VectorType>()) { |
7689 | len = vecType->getNumElements(); |
7690 | eltType = vecType->getElementType(); |
7691 | assert(eltType->isScalarType() || eltType->isMFloat8Type()); |
7692 | return true; |
7693 | } |
7694 | |
7695 | // We allow lax conversion to and from non-vector types, but only if |
7696 | // they're real types (i.e. non-complex, non-pointer scalar types). |
7697 | if (!type->isRealType()) return false; |
7698 | |
7699 | len = 1; |
7700 | eltType = type; |
7701 | return true; |
7702 | } |
7703 | |
7704 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { |
7705 | assert(srcTy->isVectorType() || destTy->isVectorType()); |
7706 | |
7707 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { |
7708 | if (!FirstType->isSVESizelessBuiltinType()) |
7709 | return false; |
7710 | |
7711 | const auto *VecTy = SecondType->getAs<VectorType>(); |
7712 | return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData; |
7713 | }; |
7714 | |
7715 | return ValidScalableConversion(srcTy, destTy) || |
7716 | ValidScalableConversion(destTy, srcTy); |
7717 | } |
7718 | |
7719 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { |
7720 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) |
7721 | return false; |
7722 | |
7723 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); |
7724 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); |
7725 | |
7726 | return matSrcType->getNumRows() == matDestType->getNumRows() && |
7727 | matSrcType->getNumColumns() == matDestType->getNumColumns(); |
7728 | } |
7729 | |
7730 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { |
7731 | assert(DestTy->isVectorType() || SrcTy->isVectorType()); |
7732 | |
7733 | uint64_t SrcLen, DestLen; |
7734 | QualType SrcEltTy, DestEltTy; |
7735 | if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy)) |
7736 | return false; |
7737 | if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: DestEltTy)) |
7738 | return false; |
7739 | |
7740 | // ASTContext::getTypeSize will return the size rounded up to a |
7741 | // power of 2, so instead of using that, we need to use the raw |
7742 | // element size multiplied by the element count. |
7743 | uint64_t SrcEltSize = Context.getTypeSize(T: SrcEltTy); |
7744 | uint64_t DestEltSize = Context.getTypeSize(T: DestEltTy); |
7745 | |
7746 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); |
7747 | } |
7748 | |
7749 | bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { |
7750 | assert((DestTy->isVectorType() || SrcTy->isVectorType()) && |
7751 | "expected at least one type to be a vector here"); |
7752 | |
7753 | bool IsSrcTyAltivec = |
7754 | SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() == |
7755 | VectorKind::AltiVecVector) || |
7756 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
7757 | VectorKind::AltiVecBool) || |
7758 | (SrcTy->castAs<VectorType>()->getVectorKind() == |
7759 | VectorKind::AltiVecPixel)); |
7760 | |
7761 | bool IsDestTyAltivec = DestTy->isVectorType() && |
7762 | ((DestTy->castAs<VectorType>()->getVectorKind() == |
7763 | VectorKind::AltiVecVector) || |
7764 | (DestTy->castAs<VectorType>()->getVectorKind() == |
7765 | VectorKind::AltiVecBool) || |
7766 | (DestTy->castAs<VectorType>()->getVectorKind() == |
7767 | VectorKind::AltiVecPixel)); |
7768 | |
7769 | return (IsSrcTyAltivec || IsDestTyAltivec); |
7770 | } |
7771 | |
7772 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { |
7773 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
7774 | |
7775 | // Disallow lax conversions between scalars and ExtVectors (these |
7776 | // conversions are allowed for other vector types because common headers |
7777 | // depend on them). Most scalar OP ExtVector cases are handled by the |
7778 | // splat path anyway, which does what we want (convert, not bitcast). |
7779 | // What this rules out for ExtVectors is crazy things like char4*float. |
7780 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; |
7781 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; |
7782 | |
7783 | return areVectorTypesSameSize(SrcTy: srcTy, DestTy: destTy); |
7784 | } |
7785 | |
7786 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { |
7787 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
7788 | |
7789 | switch (Context.getLangOpts().getLaxVectorConversions()) { |
7790 | case LangOptions::LaxVectorConversionKind::None: |
7791 | return false; |
7792 | |
7793 | case LangOptions::LaxVectorConversionKind::Integer: |
7794 | if (!srcTy->isIntegralOrEnumerationType()) { |
7795 | auto *Vec = srcTy->getAs<VectorType>(); |
7796 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
7797 | return false; |
7798 | } |
7799 | if (!destTy->isIntegralOrEnumerationType()) { |
7800 | auto *Vec = destTy->getAs<VectorType>(); |
7801 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) |
7802 | return false; |
7803 | } |
7804 | // OK, integer (vector) -> integer (vector) bitcast. |
7805 | break; |
7806 | |
7807 | case LangOptions::LaxVectorConversionKind::All: |
7808 | break; |
7809 | } |
7810 | |
7811 | return areLaxCompatibleVectorTypes(srcTy, destTy); |
7812 | } |
7813 | |
7814 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, |
7815 | CastKind &Kind) { |
7816 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { |
7817 | if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: DestTy)) { |
7818 | return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) |
7819 | << DestTy << SrcTy << R; |
7820 | } |
7821 | } else if (SrcTy->isMatrixType()) { |
7822 | return Diag(R.getBegin(), |
7823 | diag::err_invalid_conversion_between_matrix_and_type) |
7824 | << SrcTy << DestTy << R; |
7825 | } else if (DestTy->isMatrixType()) { |
7826 | return Diag(R.getBegin(), |
7827 | diag::err_invalid_conversion_between_matrix_and_type) |
7828 | << DestTy << SrcTy << R; |
7829 | } |
7830 | |
7831 | Kind = CK_MatrixCast; |
7832 | return false; |
7833 | } |
7834 | |
7835 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
7836 | CastKind &Kind) { |
7837 | assert(VectorTy->isVectorType() && "Not a vector type!"); |
7838 | |
7839 | if (Ty->isVectorType() || Ty->isIntegralType(Ctx: Context)) { |
7840 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) |
7841 | return Diag(R.getBegin(), |
7842 | Ty->isVectorType() ? |
7843 | diag::err_invalid_conversion_between_vectors : |
7844 | diag::err_invalid_conversion_between_vector_and_integer) |
7845 | << VectorTy << Ty << R; |
7846 | } else |
7847 | return Diag(R.getBegin(), |
7848 | diag::err_invalid_conversion_between_vector_and_scalar) |
7849 | << VectorTy << Ty << R; |
7850 | |
7851 | Kind = CK_BitCast; |
7852 | return false; |
7853 | } |
7854 | |
7855 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { |
7856 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); |
7857 | |
7858 | if (DestElemTy == SplattedExpr->getType()) |
7859 | return SplattedExpr; |
7860 | |
7861 | assert(DestElemTy->isFloatingType() || |
7862 | DestElemTy->isIntegralOrEnumerationType()); |
7863 | |
7864 | CastKind CK; |
7865 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { |
7866 | // OpenCL requires that we convert `true` boolean expressions to -1, but |
7867 | // only when splatting vectors. |
7868 | if (DestElemTy->isFloatingType()) { |
7869 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast |
7870 | // in two steps: boolean to signed integral, then to floating. |
7871 | ExprResult CastExprRes = ImpCastExprToType(E: SplattedExpr, Type: Context.IntTy, |
7872 | CK: CK_BooleanToSignedIntegral); |
7873 | SplattedExpr = CastExprRes.get(); |
7874 | CK = CK_IntegralToFloating; |
7875 | } else { |
7876 | CK = CK_BooleanToSignedIntegral; |
7877 | } |
7878 | } else { |
7879 | ExprResult CastExprRes = SplattedExpr; |
7880 | CK = PrepareScalarCast(Src&: CastExprRes, DestTy: DestElemTy); |
7881 | if (CastExprRes.isInvalid()) |
7882 | return ExprError(); |
7883 | SplattedExpr = CastExprRes.get(); |
7884 | } |
7885 | return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK); |
7886 | } |
7887 | |
7888 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, |
7889 | Expr *CastExpr, CastKind &Kind) { |
7890 | assert(DestTy->isExtVectorType() && "Not an extended vector type!"); |
7891 | |
7892 | QualType SrcTy = CastExpr->getType(); |
7893 | |
7894 | // If SrcTy is a VectorType, the total size must match to explicitly cast to |
7895 | // an ExtVectorType. |
7896 | // In OpenCL, casts between vectors of different types are not allowed. |
7897 | // (See OpenCL 6.2). |
7898 | if (SrcTy->isVectorType()) { |
7899 | if (!areLaxCompatibleVectorTypes(srcTy: SrcTy, destTy: DestTy) || |
7900 | (getLangOpts().OpenCL && |
7901 | !Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy))) { |
7902 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) |
7903 | << DestTy << SrcTy << R; |
7904 | return ExprError(); |
7905 | } |
7906 | Kind = CK_BitCast; |
7907 | return CastExpr; |
7908 | } |
7909 | |
7910 | // All non-pointer scalars can be cast to ExtVector type. The appropriate |
7911 | // conversion will take place first from scalar to elt type, and then |
7912 | // splat from elt type to vector. |
7913 | if (SrcTy->isPointerType()) |
7914 | return Diag(R.getBegin(), |
7915 | diag::err_invalid_conversion_between_vector_and_scalar) |
7916 | << DestTy << SrcTy << R; |
7917 | |
7918 | Kind = CK_VectorSplat; |
7919 | return prepareVectorSplat(VectorTy: DestTy, SplattedExpr: CastExpr); |
7920 | } |
7921 | |
7922 | ExprResult |
7923 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
7924 | Declarator &D, ParsedType &Ty, |
7925 | SourceLocation RParenLoc, Expr *CastExpr) { |
7926 | assert(!D.isInvalidType() && (CastExpr != nullptr) && |
7927 | "ActOnCastExpr(): missing type or expr"); |
7928 | |
7929 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType()); |
7930 | if (D.isInvalidType()) |
7931 | return ExprError(); |
7932 | |
7933 | if (getLangOpts().CPlusPlus) { |
7934 | // Check that there are no default arguments (C++ only). |
7935 | CheckExtraCXXDefaultArguments(D); |
7936 | } else { |
7937 | // Make sure any TypoExprs have been dealt with. |
7938 | ExprResult Res = CorrectDelayedTyposInExpr(E: CastExpr); |
7939 | if (!Res.isUsable()) |
7940 | return ExprError(); |
7941 | CastExpr = Res.get(); |
7942 | } |
7943 | |
7944 | checkUnusedDeclAttributes(D); |
7945 | |
7946 | QualType castType = castTInfo->getType(); |
7947 | Ty = CreateParsedType(T: castType, TInfo: castTInfo); |
7948 | |
7949 | bool isVectorLiteral = false; |
7950 | |
7951 | // Check for an altivec or OpenCL literal, |
7952 | // i.e. all the elements are integer constants. |
7953 | ParenExpr *PE = dyn_cast<ParenExpr>(Val: CastExpr); |
7954 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: CastExpr); |
7955 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) |
7956 | && castType->isVectorType() && (PE || PLE)) { |
7957 | if (PLE && PLE->getNumExprs() == 0) { |
7958 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); |
7959 | return ExprError(); |
7960 | } |
7961 | if (PE || PLE->getNumExprs() == 1) { |
7962 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(Init: 0)); |
7963 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) |
7964 | isVectorLiteral = true; |
7965 | } |
7966 | else |
7967 | isVectorLiteral = true; |
7968 | } |
7969 | |
7970 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' |
7971 | // then handle it as such. |
7972 | if (isVectorLiteral) |
7973 | return BuildVectorLiteral(LParenLoc, RParenLoc, E: CastExpr, TInfo: castTInfo); |
7974 | |
7975 | // If the Expr being casted is a ParenListExpr, handle it specially. |
7976 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a |
7977 | // sequence of BinOp comma operators. |
7978 | if (isa<ParenListExpr>(Val: CastExpr)) { |
7979 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: CastExpr); |
7980 | if (Result.isInvalid()) return ExprError(); |
7981 | CastExpr = Result.get(); |
7982 | } |
7983 | |
7984 | if (getLangOpts().CPlusPlus && !castType->isVoidType()) |
7985 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); |
7986 | |
7987 | ObjC().CheckTollFreeBridgeCast(castType, castExpr: CastExpr); |
7988 | |
7989 | ObjC().CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr); |
7990 | |
7991 | DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr); |
7992 | |
7993 | return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr); |
7994 | } |
7995 | |
7996 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, |
7997 | SourceLocation RParenLoc, Expr *E, |
7998 | TypeSourceInfo *TInfo) { |
7999 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && |
8000 | "Expected paren or paren list expression"); |
8001 | |
8002 | Expr **exprs; |
8003 | unsigned numExprs; |
8004 | Expr *subExpr; |
8005 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; |
8006 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(Val: E)) { |
8007 | LiteralLParenLoc = PE->getLParenLoc(); |
8008 | LiteralRParenLoc = PE->getRParenLoc(); |
8009 | exprs = PE->getExprs(); |
8010 | numExprs = PE->getNumExprs(); |
8011 | } else { // isa<ParenExpr> by assertion at function entrance |
8012 | LiteralLParenLoc = cast<ParenExpr>(Val: E)->getLParen(); |
8013 | LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen(); |
8014 | subExpr = cast<ParenExpr>(Val: E)->getSubExpr(); |
8015 | exprs = &subExpr; |
8016 | numExprs = 1; |
8017 | } |
8018 | |
8019 | QualType Ty = TInfo->getType(); |
8020 | assert(Ty->isVectorType() && "Expected vector type"); |
8021 | |
8022 | SmallVector<Expr *, 8> initExprs; |
8023 | const VectorType *VTy = Ty->castAs<VectorType>(); |
8024 | unsigned numElems = VTy->getNumElements(); |
8025 | |
8026 | // '(...)' form of vector initialization in AltiVec: the number of |
8027 | // initializers must be one or must match the size of the vector. |
8028 | // If a single value is specified in the initializer then it will be |
8029 | // replicated to all the components of the vector |
8030 | if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty, |
8031 | SrcTy: VTy->getElementType())) |
8032 | return ExprError(); |
8033 | if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) { |
8034 | // The number of initializers must be one or must match the size of the |
8035 | // vector. If a single value is specified in the initializer then it will |
8036 | // be replicated to all the components of the vector |
8037 | if (numExprs == 1) { |
8038 | QualType ElemTy = VTy->getElementType(); |
8039 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
8040 | if (Literal.isInvalid()) |
8041 | return ExprError(); |
8042 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
8043 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
8044 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
8045 | } |
8046 | else if (numExprs < numElems) { |
8047 | Diag(E->getExprLoc(), |
8048 | diag::err_incorrect_number_of_vector_initializers); |
8049 | return ExprError(); |
8050 | } |
8051 | else |
8052 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
8053 | } |
8054 | else { |
8055 | // For OpenCL, when the number of initializers is a single value, |
8056 | // it will be replicated to all components of the vector. |
8057 | if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic && |
8058 | numExprs == 1) { |
8059 | QualType ElemTy = VTy->getElementType(); |
8060 | ExprResult Literal = DefaultLvalueConversion(E: exprs[0]); |
8061 | if (Literal.isInvalid()) |
8062 | return ExprError(); |
8063 | Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy, |
8064 | CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy)); |
8065 | return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get()); |
8066 | } |
8067 | |
8068 | initExprs.append(in_start: exprs, in_end: exprs + numExprs); |
8069 | } |
8070 | // FIXME: This means that pretty-printing the final AST will produce curly |
8071 | // braces instead of the original commas. |
8072 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, |
8073 | initExprs, LiteralRParenLoc); |
8074 | initE->setType(Ty); |
8075 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); |
8076 | } |
8077 | |
8078 | ExprResult |
8079 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { |
8080 | ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr); |
8081 | if (!E) |
8082 | return OrigExpr; |
8083 | |
8084 | ExprResult Result(E->getExpr(Init: 0)); |
8085 | |
8086 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) |
8087 | Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(), |
8088 | RHSExpr: E->getExpr(Init: i)); |
8089 | |
8090 | if (Result.isInvalid()) return ExprError(); |
8091 | |
8092 | return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get()); |
8093 | } |
8094 | |
8095 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, |
8096 | SourceLocation R, |
8097 | MultiExprArg Val) { |
8098 | return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: R); |
8099 | } |
8100 | |
8101 | ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T, |
8102 | unsigned NumUserSpecifiedExprs, |
8103 | SourceLocation InitLoc, |
8104 | SourceLocation LParenLoc, |
8105 | SourceLocation RParenLoc) { |
8106 | return CXXParenListInitExpr::Create(C&: Context, Args, T, NumUserSpecifiedExprs, |
8107 | InitLoc, LParenLoc, RParenLoc); |
8108 | } |
8109 | |
8110 | bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, |
8111 | SourceLocation QuestionLoc) { |
8112 | const Expr *NullExpr = LHSExpr; |
8113 | const Expr *NonPointerExpr = RHSExpr; |
8114 | Expr::NullPointerConstantKind NullKind = |
8115 | NullExpr->isNullPointerConstant(Ctx&: Context, |
8116 | NPC: Expr::NPC_ValueDependentIsNotNull); |
8117 | |
8118 | if (NullKind == Expr::NPCK_NotNull) { |
8119 | NullExpr = RHSExpr; |
8120 | NonPointerExpr = LHSExpr; |
8121 | NullKind = |
8122 | NullExpr->isNullPointerConstant(Ctx&: Context, |
8123 | NPC: Expr::NPC_ValueDependentIsNotNull); |
8124 | } |
8125 | |
8126 | if (NullKind == Expr::NPCK_NotNull) |
8127 | return false; |
8128 | |
8129 | if (NullKind == Expr::NPCK_ZeroExpression) |
8130 | return false; |
8131 | |
8132 | if (NullKind == Expr::NPCK_ZeroLiteral) { |
8133 | // In this case, check to make sure that we got here from a "NULL" |
8134 | // string in the source code. |
8135 | NullExpr = NullExpr->IgnoreParenImpCasts(); |
8136 | SourceLocation loc = NullExpr->getExprLoc(); |
8137 | if (!findMacroSpelling(loc, name: "NULL")) |
8138 | return false; |
8139 | } |
8140 | |
8141 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); |
8142 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) |
8143 | << NonPointerExpr->getType() << DiagType |
8144 | << NonPointerExpr->getSourceRange(); |
8145 | return true; |
8146 | } |
8147 | |
8148 | /// Return false if the condition expression is valid, true otherwise. |
8149 | static bool checkCondition(Sema &S, const Expr *Cond, |
8150 | SourceLocation QuestionLoc) { |
8151 | QualType CondTy = Cond->getType(); |
8152 | |
8153 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. |
8154 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { |
8155 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) |
8156 | << CondTy << Cond->getSourceRange(); |
8157 | return true; |
8158 | } |
8159 | |
8160 | // C99 6.5.15p2 |
8161 | if (CondTy->isScalarType()) return false; |
8162 | |
8163 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) |
8164 | << CondTy << Cond->getSourceRange(); |
8165 | return true; |
8166 | } |
8167 | |
8168 | /// Return false if the NullExpr can be promoted to PointerTy, |
8169 | /// true otherwise. |
8170 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, |
8171 | QualType PointerTy) { |
8172 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || |
8173 | !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context, |
8174 | NPC: Expr::NPC_ValueDependentIsNull)) |
8175 | return true; |
8176 | |
8177 | NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer); |
8178 | return false; |
8179 | } |
8180 | |
8181 | /// Checks compatibility between two pointers and return the resulting |
8182 | /// type. |
8183 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, |
8184 | ExprResult &RHS, |
8185 | SourceLocation Loc) { |
8186 | QualType LHSTy = LHS.get()->getType(); |
8187 | QualType RHSTy = RHS.get()->getType(); |
8188 | |
8189 | if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) { |
8190 | // Two identical pointers types are always compatible. |
8191 | return S.Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
8192 | } |
8193 | |
8194 | QualType lhptee, rhptee; |
8195 | |
8196 | // Get the pointee types. |
8197 | bool IsBlockPointer = false; |
8198 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { |
8199 | lhptee = LHSBTy->getPointeeType(); |
8200 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); |
8201 | IsBlockPointer = true; |
8202 | } else { |
8203 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
8204 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
8205 | } |
8206 | |
8207 | // C99 6.5.15p6: If both operands are pointers to compatible types or to |
8208 | // differently qualified versions of compatible types, the result type is |
8209 | // a pointer to an appropriately qualified version of the composite |
8210 | // type. |
8211 | |
8212 | // Only CVR-qualifiers exist in the standard, and the differently-qualified |
8213 | // clause doesn't make sense for our extensions. E.g. address space 2 should |
8214 | // be incompatible with address space 3: they may live on different devices or |
8215 | // anything. |
8216 | Qualifiers lhQual = lhptee.getQualifiers(); |
8217 | Qualifiers rhQual = rhptee.getQualifiers(); |
8218 | |
8219 | LangAS ResultAddrSpace = LangAS::Default; |
8220 | LangAS LAddrSpace = lhQual.getAddressSpace(); |
8221 | LangAS RAddrSpace = rhQual.getAddressSpace(); |
8222 | |
8223 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address |
8224 | // spaces is disallowed. |
8225 | if (lhQual.isAddressSpaceSupersetOf(other: rhQual, Ctx: S.getASTContext())) |
8226 | ResultAddrSpace = LAddrSpace; |
8227 | else if (rhQual.isAddressSpaceSupersetOf(other: lhQual, Ctx: S.getASTContext())) |
8228 | ResultAddrSpace = RAddrSpace; |
8229 | else { |
8230 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
8231 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() |
8232 | << RHS.get()->getSourceRange(); |
8233 | return QualType(); |
8234 | } |
8235 | |
8236 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); |
8237 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; |
8238 | lhQual.removeCVRQualifiers(); |
8239 | rhQual.removeCVRQualifiers(); |
8240 | |
8241 | if (!lhQual.getPointerAuth().isEquivalent(Other: rhQual.getPointerAuth())) { |
8242 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth) |
8243 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8244 | << RHS.get()->getSourceRange(); |
8245 | return QualType(); |
8246 | } |
8247 | |
8248 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers |
8249 | // (C99 6.7.3) for address spaces. We assume that the check should behave in |
8250 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two |
8251 | // qual types are compatible iff |
8252 | // * corresponded types are compatible |
8253 | // * CVR qualifiers are equal |
8254 | // * address spaces are equal |
8255 | // Thus for conditional operator we merge CVR and address space unqualified |
8256 | // pointees and if there is a composite type we return a pointer to it with |
8257 | // merged qualifiers. |
8258 | LHSCastKind = |
8259 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
8260 | RHSCastKind = |
8261 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
8262 | lhQual.removeAddressSpace(); |
8263 | rhQual.removeAddressSpace(); |
8264 | |
8265 | lhptee = S.Context.getQualifiedType(T: lhptee.getUnqualifiedType(), Qs: lhQual); |
8266 | rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: rhQual); |
8267 | |
8268 | QualType CompositeTy = S.Context.mergeTypes( |
8269 | lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, |
8270 | /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); |
8271 | |
8272 | if (CompositeTy.isNull()) { |
8273 | // In this situation, we assume void* type. No especially good |
8274 | // reason, but this is what gcc does, and we do have to pick |
8275 | // to get a consistent AST. |
8276 | QualType incompatTy; |
8277 | incompatTy = S.Context.getPointerType( |
8278 | S.Context.getAddrSpaceQualType(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace)); |
8279 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind); |
8280 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: RHSCastKind); |
8281 | |
8282 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room |
8283 | // for casts between types with incompatible address space qualifiers. |
8284 | // For the following code the compiler produces casts between global and |
8285 | // local address spaces of the corresponded innermost pointees: |
8286 | // local int *global *a; |
8287 | // global int *global *b; |
8288 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. |
8289 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) |
8290 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8291 | << RHS.get()->getSourceRange(); |
8292 | |
8293 | return incompatTy; |
8294 | } |
8295 | |
8296 | // The pointer types are compatible. |
8297 | // In case of OpenCL ResultTy should have the address space qualifier |
8298 | // which is a superset of address spaces of both the 2nd and the 3rd |
8299 | // operands of the conditional operator. |
8300 | QualType ResultTy = [&, ResultAddrSpace]() { |
8301 | if (S.getLangOpts().OpenCL) { |
8302 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); |
8303 | CompositeQuals.setAddressSpace(ResultAddrSpace); |
8304 | return S.Context |
8305 | .getQualifiedType(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals) |
8306 | .withCVRQualifiers(CVR: MergedCVRQual); |
8307 | } |
8308 | return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual); |
8309 | }(); |
8310 | if (IsBlockPointer) |
8311 | ResultTy = S.Context.getBlockPointerType(T: ResultTy); |
8312 | else |
8313 | ResultTy = S.Context.getPointerType(T: ResultTy); |
8314 | |
8315 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind); |
8316 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind); |
8317 | return ResultTy; |
8318 | } |
8319 | |
8320 | /// Return the resulting type when the operands are both block pointers. |
8321 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, |
8322 | ExprResult &LHS, |
8323 | ExprResult &RHS, |
8324 | SourceLocation Loc) { |
8325 | QualType LHSTy = LHS.get()->getType(); |
8326 | QualType RHSTy = RHS.get()->getType(); |
8327 | |
8328 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { |
8329 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { |
8330 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); |
8331 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
8332 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
8333 | return destType; |
8334 | } |
8335 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) |
8336 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8337 | << RHS.get()->getSourceRange(); |
8338 | return QualType(); |
8339 | } |
8340 | |
8341 | // We have 2 block pointer types. |
8342 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
8343 | } |
8344 | |
8345 | /// Return the resulting type when the operands are both pointers. |
8346 | static QualType |
8347 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, |
8348 | ExprResult &RHS, |
8349 | SourceLocation Loc) { |
8350 | // get the pointer types |
8351 | QualType LHSTy = LHS.get()->getType(); |
8352 | QualType RHSTy = RHS.get()->getType(); |
8353 | |
8354 | // get the "pointed to" types |
8355 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
8356 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
8357 | |
8358 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) |
8359 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { |
8360 | // Figure out necessary qualifiers (C99 6.5.15p6) |
8361 | QualType destPointee |
8362 | = S.Context.getQualifiedType(T: lhptee, Qs: rhptee.getQualifiers()); |
8363 | QualType destType = S.Context.getPointerType(T: destPointee); |
8364 | // Add qualifiers if necessary. |
8365 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp); |
8366 | // Promote to void*. |
8367 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast); |
8368 | return destType; |
8369 | } |
8370 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { |
8371 | QualType destPointee |
8372 | = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers()); |
8373 | QualType destType = S.Context.getPointerType(T: destPointee); |
8374 | // Add qualifiers if necessary. |
8375 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp); |
8376 | // Promote to void*. |
8377 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast); |
8378 | return destType; |
8379 | } |
8380 | |
8381 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
8382 | } |
8383 | |
8384 | /// Return false if the first expression is not an integer and the second |
8385 | /// expression is not a pointer, true otherwise. |
8386 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, |
8387 | Expr* PointerExpr, SourceLocation Loc, |
8388 | bool IsIntFirstExpr) { |
8389 | if (!PointerExpr->getType()->isPointerType() || |
8390 | !Int.get()->getType()->isIntegerType()) |
8391 | return false; |
8392 | |
8393 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; |
8394 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); |
8395 | |
8396 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) |
8397 | << Expr1->getType() << Expr2->getType() |
8398 | << Expr1->getSourceRange() << Expr2->getSourceRange(); |
8399 | Int = S.ImpCastExprToType(E: Int.get(), Type: PointerExpr->getType(), |
8400 | CK: CK_IntegralToPointer); |
8401 | return true; |
8402 | } |
8403 | |
8404 | /// Simple conversion between integer and floating point types. |
8405 | /// |
8406 | /// Used when handling the OpenCL conditional operator where the |
8407 | /// condition is a vector while the other operands are scalar. |
8408 | /// |
8409 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar |
8410 | /// types are either integer or floating type. Between the two |
8411 | /// operands, the type with the higher rank is defined as the "result |
8412 | /// type". The other operand needs to be promoted to the same type. No |
8413 | /// other type promotion is allowed. We cannot use |
8414 | /// UsualArithmeticConversions() for this purpose, since it always |
8415 | /// promotes promotable types. |
8416 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, |
8417 | ExprResult &RHS, |
8418 | SourceLocation QuestionLoc) { |
8419 | LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
8420 | if (LHS.isInvalid()) |
8421 | return QualType(); |
8422 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
8423 | if (RHS.isInvalid()) |
8424 | return QualType(); |
8425 | |
8426 | // For conversion purposes, we ignore any qualifiers. |
8427 | // For example, "const float" and "float" are equivalent. |
8428 | QualType LHSType = |
8429 | S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType(); |
8430 | QualType RHSType = |
8431 | S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType(); |
8432 | |
8433 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { |
8434 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) |
8435 | << LHSType << LHS.get()->getSourceRange(); |
8436 | return QualType(); |
8437 | } |
8438 | |
8439 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { |
8440 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) |
8441 | << RHSType << RHS.get()->getSourceRange(); |
8442 | return QualType(); |
8443 | } |
8444 | |
8445 | // If both types are identical, no conversion is needed. |
8446 | if (LHSType == RHSType) |
8447 | return LHSType; |
8448 | |
8449 | // Now handle "real" floating types (i.e. float, double, long double). |
8450 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
8451 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, |
8452 | /*IsCompAssign = */ false); |
8453 | |
8454 | // Finally, we have two differing integer types. |
8455 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
8456 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); |
8457 | } |
8458 | |
8459 | /// Convert scalar operands to a vector that matches the |
8460 | /// condition in length. |
8461 | /// |
8462 | /// Used when handling the OpenCL conditional operator where the |
8463 | /// condition is a vector while the other operands are scalar. |
8464 | /// |
8465 | /// We first compute the "result type" for the scalar operands |
8466 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted |
8467 | /// into a vector of that type where the length matches the condition |
8468 | /// vector type. s6.11.6 requires that the element types of the result |
8469 | /// and the condition must have the same number of bits. |
8470 | static QualType |
8471 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, |
8472 | QualType CondTy, SourceLocation QuestionLoc) { |
8473 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); |
8474 | if (ResTy.isNull()) return QualType(); |
8475 | |
8476 | const VectorType *CV = CondTy->getAs<VectorType>(); |
8477 | assert(CV); |
8478 | |
8479 | // Determine the vector result type |
8480 | unsigned NumElements = CV->getNumElements(); |
8481 | QualType VectorTy = S.Context.getExtVectorType(VectorType: ResTy, NumElts: NumElements); |
8482 | |
8483 | // Ensure that all types have the same number of bits |
8484 | if (S.Context.getTypeSize(T: CV->getElementType()) |
8485 | != S.Context.getTypeSize(T: ResTy)) { |
8486 | // Since VectorTy is created internally, it does not pretty print |
8487 | // with an OpenCL name. Instead, we just print a description. |
8488 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); |
8489 | SmallString<64> Str; |
8490 | llvm::raw_svector_ostream OS(Str); |
8491 | OS << "(vector of "<< NumElements << " '"<< EleTyName << "' values)"; |
8492 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
8493 | << CondTy << OS.str(); |
8494 | return QualType(); |
8495 | } |
8496 | |
8497 | // Convert operands to the vector result type |
8498 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
8499 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat); |
8500 | |
8501 | return VectorTy; |
8502 | } |
8503 | |
8504 | /// Return false if this is a valid OpenCL condition vector |
8505 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, |
8506 | SourceLocation QuestionLoc) { |
8507 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of |
8508 | // integral type. |
8509 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); |
8510 | assert(CondTy); |
8511 | QualType EleTy = CondTy->getElementType(); |
8512 | if (EleTy->isIntegerType()) return false; |
8513 | |
8514 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) |
8515 | << Cond->getType() << Cond->getSourceRange(); |
8516 | return true; |
8517 | } |
8518 | |
8519 | /// Return false if the vector condition type and the vector |
8520 | /// result type are compatible. |
8521 | /// |
8522 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same |
8523 | /// number of elements, and their element types have the same number |
8524 | /// of bits. |
8525 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, |
8526 | SourceLocation QuestionLoc) { |
8527 | const VectorType *CV = CondTy->getAs<VectorType>(); |
8528 | const VectorType *RV = VecResTy->getAs<VectorType>(); |
8529 | assert(CV && RV); |
8530 | |
8531 | if (CV->getNumElements() != RV->getNumElements()) { |
8532 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) |
8533 | << CondTy << VecResTy; |
8534 | return true; |
8535 | } |
8536 | |
8537 | QualType CVE = CV->getElementType(); |
8538 | QualType RVE = RV->getElementType(); |
8539 | |
8540 | if (S.Context.getTypeSize(T: CVE) != S.Context.getTypeSize(T: RVE)) { |
8541 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
8542 | << CondTy << VecResTy; |
8543 | return true; |
8544 | } |
8545 | |
8546 | return false; |
8547 | } |
8548 | |
8549 | /// Return the resulting type for the conditional operator in |
8550 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 |
8551 | /// s6.3.i) when the condition is a vector type. |
8552 | static QualType |
8553 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, |
8554 | ExprResult &LHS, ExprResult &RHS, |
8555 | SourceLocation QuestionLoc) { |
8556 | Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get()); |
8557 | if (Cond.isInvalid()) |
8558 | return QualType(); |
8559 | QualType CondTy = Cond.get()->getType(); |
8560 | |
8561 | if (checkOpenCLConditionVector(S, Cond: Cond.get(), QuestionLoc)) |
8562 | return QualType(); |
8563 | |
8564 | // If either operand is a vector then find the vector type of the |
8565 | // result as specified in OpenCL v1.1 s6.3.i. |
8566 | if (LHS.get()->getType()->isVectorType() || |
8567 | RHS.get()->getType()->isVectorType()) { |
8568 | bool IsBoolVecLang = |
8569 | !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; |
8570 | QualType VecResTy = |
8571 | S.CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, |
8572 | /*isCompAssign*/ IsCompAssign: false, |
8573 | /*AllowBothBool*/ true, |
8574 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
8575 | /*AllowBooleanOperation*/ AllowBoolOperation: IsBoolVecLang, |
8576 | /*ReportInvalid*/ true); |
8577 | if (VecResTy.isNull()) |
8578 | return QualType(); |
8579 | // The result type must match the condition type as specified in |
8580 | // OpenCL v1.1 s6.11.6. |
8581 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) |
8582 | return QualType(); |
8583 | return VecResTy; |
8584 | } |
8585 | |
8586 | // Both operands are scalar. |
8587 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); |
8588 | } |
8589 | |
8590 | /// Return true if the Expr is block type |
8591 | static bool checkBlockType(Sema &S, const Expr *E) { |
8592 | if (E->getType()->isBlockPointerType()) { |
8593 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); |
8594 | return true; |
8595 | } |
8596 | |
8597 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
8598 | QualType Ty = CE->getCallee()->getType(); |
8599 | if (Ty->isBlockPointerType()) { |
8600 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); |
8601 | return true; |
8602 | } |
8603 | } |
8604 | return false; |
8605 | } |
8606 | |
8607 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. |
8608 | /// In that case, LHS = cond. |
8609 | /// C99 6.5.15 |
8610 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
8611 | ExprResult &RHS, ExprValueKind &VK, |
8612 | ExprObjectKind &OK, |
8613 | SourceLocation QuestionLoc) { |
8614 | |
8615 | ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get()); |
8616 | if (!LHSResult.isUsable()) return QualType(); |
8617 | LHS = LHSResult; |
8618 | |
8619 | ExprResult RHSResult = CheckPlaceholderExpr(E: RHS.get()); |
8620 | if (!RHSResult.isUsable()) return QualType(); |
8621 | RHS = RHSResult; |
8622 | |
8623 | // C++ is sufficiently different to merit its own checker. |
8624 | if (getLangOpts().CPlusPlus) |
8625 | return CXXCheckConditionalOperands(cond&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc); |
8626 | |
8627 | VK = VK_PRValue; |
8628 | OK = OK_Ordinary; |
8629 | |
8630 | if (Context.isDependenceAllowed() && |
8631 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || |
8632 | RHS.get()->isTypeDependent())) { |
8633 | assert(!getLangOpts().CPlusPlus); |
8634 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || |
8635 | RHS.get()->containsErrors()) && |
8636 | "should only occur in error-recovery path."); |
8637 | return Context.DependentTy; |
8638 | } |
8639 | |
8640 | // The OpenCL operator with a vector condition is sufficiently |
8641 | // different to merit its own checker. |
8642 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || |
8643 | Cond.get()->getType()->isExtVectorType()) |
8644 | return OpenCLCheckVectorConditional(S&: *this, Cond, LHS, RHS, QuestionLoc); |
8645 | |
8646 | // First, check the condition. |
8647 | Cond = UsualUnaryConversions(E: Cond.get()); |
8648 | if (Cond.isInvalid()) |
8649 | return QualType(); |
8650 | if (checkCondition(S&: *this, Cond: Cond.get(), QuestionLoc)) |
8651 | return QualType(); |
8652 | |
8653 | // Handle vectors. |
8654 | if (LHS.get()->getType()->isVectorType() || |
8655 | RHS.get()->getType()->isVectorType()) |
8656 | return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, |
8657 | /*AllowBothBool*/ true, |
8658 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
8659 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
8660 | /*ReportInvalid*/ true); |
8661 | |
8662 | QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
8663 | ACK: ArithConvKind::Conditional); |
8664 | if (LHS.isInvalid() || RHS.isInvalid()) |
8665 | return QualType(); |
8666 | |
8667 | // WebAssembly tables are not allowed as conditional LHS or RHS. |
8668 | QualType LHSTy = LHS.get()->getType(); |
8669 | QualType RHSTy = RHS.get()->getType(); |
8670 | if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) { |
8671 | Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) |
8672 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
8673 | return QualType(); |
8674 | } |
8675 | |
8676 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
8677 | // where such conversions currently can't be handled. |
8678 | if (unsupportedTypeConversion(S: *this, LHSType: LHSTy, RHSType: RHSTy)) { |
8679 | Diag(QuestionLoc, |
8680 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy |
8681 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
8682 | return QualType(); |
8683 | } |
8684 | |
8685 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary |
8686 | // selection operator (?:). |
8687 | if (getLangOpts().OpenCL && |
8688 | ((int)checkBlockType(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: RHS.get()))) { |
8689 | return QualType(); |
8690 | } |
8691 | |
8692 | // If both operands have arithmetic type, do the usual arithmetic conversions |
8693 | // to find a common type: C99 6.5.15p3,5. |
8694 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { |
8695 | // Disallow invalid arithmetic conversions, such as those between bit- |
8696 | // precise integers types of different sizes, or between a bit-precise |
8697 | // integer and another type. |
8698 | if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { |
8699 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
8700 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8701 | << RHS.get()->getSourceRange(); |
8702 | return QualType(); |
8703 | } |
8704 | |
8705 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy)); |
8706 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: ResTy)); |
8707 | |
8708 | return ResTy; |
8709 | } |
8710 | |
8711 | // If both operands are the same structure or union type, the result is that |
8712 | // type. |
8713 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 |
8714 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) |
8715 | if (LHSRT->getDecl() == RHSRT->getDecl()) |
8716 | // "If both the operands have structure or union type, the result has |
8717 | // that type." This implies that CV qualifiers are dropped. |
8718 | return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(), |
8719 | Y: RHSTy.getUnqualifiedType()); |
8720 | // FIXME: Type of conditional expression must be complete in C mode. |
8721 | } |
8722 | |
8723 | // C99 6.5.15p5: "If both operands have void type, the result has void type." |
8724 | // The following || allows only one side to be void (a GCC-ism). |
8725 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { |
8726 | QualType ResTy; |
8727 | if (LHSTy->isVoidType() && RHSTy->isVoidType()) { |
8728 | ResTy = Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
8729 | } else if (RHSTy->isVoidType()) { |
8730 | ResTy = RHSTy; |
8731 | Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) |
8732 | << RHS.get()->getSourceRange(); |
8733 | } else { |
8734 | ResTy = LHSTy; |
8735 | Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) |
8736 | << LHS.get()->getSourceRange(); |
8737 | } |
8738 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: CK_ToVoid); |
8739 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: CK_ToVoid); |
8740 | return ResTy; |
8741 | } |
8742 | |
8743 | // C23 6.5.15p7: |
8744 | // ... if both the second and third operands have nullptr_t type, the |
8745 | // result also has that type. |
8746 | if (LHSTy->isNullPtrType() && Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
8747 | return ResTy; |
8748 | |
8749 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has |
8750 | // the type of the other operand." |
8751 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy; |
8752 | if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: RHSTy)) return RHSTy; |
8753 | |
8754 | // All objective-c pointer type analysis is done here. |
8755 | QualType compositeType = |
8756 | ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
8757 | if (LHS.isInvalid() || RHS.isInvalid()) |
8758 | return QualType(); |
8759 | if (!compositeType.isNull()) |
8760 | return compositeType; |
8761 | |
8762 | |
8763 | // Handle block pointer types. |
8764 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) |
8765 | return checkConditionalBlockPointerCompatibility(S&: *this, LHS, RHS, |
8766 | Loc: QuestionLoc); |
8767 | |
8768 | // Check constraints for C object pointers types (C99 6.5.15p3,6). |
8769 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) |
8770 | return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS, |
8771 | Loc: QuestionLoc); |
8772 | |
8773 | // GCC compatibility: soften pointer/integer mismatch. Note that |
8774 | // null pointers have been filtered out by this point. |
8775 | if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc, |
8776 | /*IsIntFirstExpr=*/true)) |
8777 | return RHSTy; |
8778 | if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: QuestionLoc, |
8779 | /*IsIntFirstExpr=*/false)) |
8780 | return LHSTy; |
8781 | |
8782 | // Emit a better diagnostic if one of the expressions is a null pointer |
8783 | // constant and the other is not a pointer type. In this case, the user most |
8784 | // likely forgot to take the address of the other expression. |
8785 | if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
8786 | return QualType(); |
8787 | |
8788 | // Finally, if the LHS and RHS types are canonically the same type, we can |
8789 | // use the common sugared type. |
8790 | if (Context.hasSameType(T1: LHSTy, T2: RHSTy)) |
8791 | return Context.getCommonSugaredType(X: LHSTy, Y: RHSTy); |
8792 | |
8793 | // Otherwise, the operands are not compatible. |
8794 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
8795 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
8796 | << RHS.get()->getSourceRange(); |
8797 | return QualType(); |
8798 | } |
8799 | |
8800 | /// SuggestParentheses - Emit a note with a fixit hint that wraps |
8801 | /// ParenRange in parentheses. |
8802 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, |
8803 | const PartialDiagnostic &Note, |
8804 | SourceRange ParenRange) { |
8805 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd()); |
8806 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && |
8807 | EndLoc.isValid()) { |
8808 | Self.Diag(Loc, Note) |
8809 | << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(") |
8810 | << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")"); |
8811 | } else { |
8812 | // We can't display the parentheses, so just show the bare note. |
8813 | Self.Diag(Loc, Note) << ParenRange; |
8814 | } |
8815 | } |
8816 | |
8817 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { |
8818 | return BinaryOperator::isAdditiveOp(Opc) || |
8819 | BinaryOperator::isMultiplicativeOp(Opc) || |
8820 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; |
8821 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and |
8822 | // not any of the logical operators. Bitwise-xor is commonly used as a |
8823 | // logical-xor because there is no logical-xor operator. The logical |
8824 | // operators, including uses of xor, have a high false positive rate for |
8825 | // precedence warnings. |
8826 | } |
8827 | |
8828 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary |
8829 | /// expression, either using a built-in or overloaded operator, |
8830 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side |
8831 | /// expression. |
8832 | static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, |
8833 | const Expr **RHSExprs) { |
8834 | // Don't strip parenthesis: we should not warn if E is in parenthesis. |
8835 | E = E->IgnoreImpCasts(); |
8836 | E = E->IgnoreConversionOperatorSingleStep(); |
8837 | E = E->IgnoreImpCasts(); |
8838 | if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) { |
8839 | E = MTE->getSubExpr(); |
8840 | E = E->IgnoreImpCasts(); |
8841 | } |
8842 | |
8843 | // Built-in binary operator. |
8844 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E); |
8845 | OP && IsArithmeticOp(Opc: OP->getOpcode())) { |
8846 | *Opcode = OP->getOpcode(); |
8847 | *RHSExprs = OP->getRHS(); |
8848 | return true; |
8849 | } |
8850 | |
8851 | // Overloaded operator. |
8852 | if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
8853 | if (Call->getNumArgs() != 2) |
8854 | return false; |
8855 | |
8856 | // Make sure this is really a binary operator that is safe to pass into |
8857 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. |
8858 | OverloadedOperatorKind OO = Call->getOperator(); |
8859 | if (OO < OO_Plus || OO > OO_Arrow || |
8860 | OO == OO_PlusPlus || OO == OO_MinusMinus) |
8861 | return false; |
8862 | |
8863 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); |
8864 | if (IsArithmeticOp(Opc: OpKind)) { |
8865 | *Opcode = OpKind; |
8866 | *RHSExprs = Call->getArg(1); |
8867 | return true; |
8868 | } |
8869 | } |
8870 | |
8871 | return false; |
8872 | } |
8873 | |
8874 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type |
8875 | /// or is a logical expression such as (x==y) which has int type, but is |
8876 | /// commonly interpreted as boolean. |
8877 | static bool ExprLooksBoolean(const Expr *E) { |
8878 | E = E->IgnoreParenImpCasts(); |
8879 | |
8880 | if (E->getType()->isBooleanType()) |
8881 | return true; |
8882 | if (const auto *OP = dyn_cast<BinaryOperator>(Val: E)) |
8883 | return OP->isComparisonOp() || OP->isLogicalOp(); |
8884 | if (const auto *OP = dyn_cast<UnaryOperator>(Val: E)) |
8885 | return OP->getOpcode() == UO_LNot; |
8886 | if (E->getType()->isPointerType()) |
8887 | return true; |
8888 | // FIXME: What about overloaded operator calls returning "unspecified boolean |
8889 | // type"s (commonly pointer-to-members)? |
8890 | |
8891 | return false; |
8892 | } |
8893 | |
8894 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator |
8895 | /// and binary operator are mixed in a way that suggests the programmer assumed |
8896 | /// the conditional operator has higher precedence, for example: |
8897 | /// "int x = a + someBinaryCondition ? 1 : 2". |
8898 | static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, |
8899 | Expr *Condition, const Expr *LHSExpr, |
8900 | const Expr *RHSExpr) { |
8901 | BinaryOperatorKind CondOpcode; |
8902 | const Expr *CondRHS; |
8903 | |
8904 | if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS)) |
8905 | return; |
8906 | if (!ExprLooksBoolean(E: CondRHS)) |
8907 | return; |
8908 | |
8909 | // The condition is an arithmetic binary expression, with a right- |
8910 | // hand side that looks boolean, so warn. |
8911 | |
8912 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) |
8913 | ? diag::warn_precedence_bitwise_conditional |
8914 | : diag::warn_precedence_conditional; |
8915 | |
8916 | Self.Diag(OpLoc, DiagID) |
8917 | << Condition->getSourceRange() |
8918 | << BinaryOperator::getOpcodeStr(Op: CondOpcode); |
8919 | |
8920 | SuggestParentheses( |
8921 | Self, OpLoc, |
8922 | Self.PDiag(diag::note_precedence_silence) |
8923 | << BinaryOperator::getOpcodeStr(CondOpcode), |
8924 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); |
8925 | |
8926 | SuggestParentheses(Self, OpLoc, |
8927 | Self.PDiag(diag::note_precedence_conditional_first), |
8928 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); |
8929 | } |
8930 | |
8931 | /// Compute the nullability of a conditional expression. |
8932 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, |
8933 | QualType LHSTy, QualType RHSTy, |
8934 | ASTContext &Ctx) { |
8935 | if (!ResTy->isAnyPointerType()) |
8936 | return ResTy; |
8937 | |
8938 | auto GetNullability = [](QualType Ty) { |
8939 | std::optional<NullabilityKind> Kind = Ty->getNullability(); |
8940 | if (Kind) { |
8941 | // For our purposes, treat _Nullable_result as _Nullable. |
8942 | if (*Kind == NullabilityKind::NullableResult) |
8943 | return NullabilityKind::Nullable; |
8944 | return *Kind; |
8945 | } |
8946 | return NullabilityKind::Unspecified; |
8947 | }; |
8948 | |
8949 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); |
8950 | NullabilityKind MergedKind; |
8951 | |
8952 | // Compute nullability of a binary conditional expression. |
8953 | if (IsBin) { |
8954 | if (LHSKind == NullabilityKind::NonNull) |
8955 | MergedKind = NullabilityKind::NonNull; |
8956 | else |
8957 | MergedKind = RHSKind; |
8958 | // Compute nullability of a normal conditional expression. |
8959 | } else { |
8960 | if (LHSKind == NullabilityKind::Nullable || |
8961 | RHSKind == NullabilityKind::Nullable) |
8962 | MergedKind = NullabilityKind::Nullable; |
8963 | else if (LHSKind == NullabilityKind::NonNull) |
8964 | MergedKind = RHSKind; |
8965 | else if (RHSKind == NullabilityKind::NonNull) |
8966 | MergedKind = LHSKind; |
8967 | else |
8968 | MergedKind = NullabilityKind::Unspecified; |
8969 | } |
8970 | |
8971 | // Return if ResTy already has the correct nullability. |
8972 | if (GetNullability(ResTy) == MergedKind) |
8973 | return ResTy; |
8974 | |
8975 | // Strip all nullability from ResTy. |
8976 | while (ResTy->getNullability()) |
8977 | ResTy = ResTy.getSingleStepDesugaredType(Context: Ctx); |
8978 | |
8979 | // Create a new AttributedType with the new nullability kind. |
8980 | return Ctx.getAttributedType(nullability: MergedKind, modifiedType: ResTy, equivalentType: ResTy); |
8981 | } |
8982 | |
8983 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, |
8984 | SourceLocation ColonLoc, |
8985 | Expr *CondExpr, Expr *LHSExpr, |
8986 | Expr *RHSExpr) { |
8987 | if (!Context.isDependenceAllowed()) { |
8988 | // C cannot handle TypoExpr nodes in the condition because it |
8989 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
8990 | // been dealt with before checking the operands. |
8991 | ExprResult CondResult = CorrectDelayedTyposInExpr(E: CondExpr); |
8992 | ExprResult LHSResult = CorrectDelayedTyposInExpr(E: LHSExpr); |
8993 | ExprResult RHSResult = CorrectDelayedTyposInExpr(E: RHSExpr); |
8994 | |
8995 | if (!CondResult.isUsable()) |
8996 | return ExprError(); |
8997 | |
8998 | if (LHSExpr) { |
8999 | if (!LHSResult.isUsable()) |
9000 | return ExprError(); |
9001 | } |
9002 | |
9003 | if (!RHSResult.isUsable()) |
9004 | return ExprError(); |
9005 | |
9006 | CondExpr = CondResult.get(); |
9007 | LHSExpr = LHSResult.get(); |
9008 | RHSExpr = RHSResult.get(); |
9009 | } |
9010 | |
9011 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS |
9012 | // was the condition. |
9013 | OpaqueValueExpr *opaqueValue = nullptr; |
9014 | Expr *commonExpr = nullptr; |
9015 | if (!LHSExpr) { |
9016 | commonExpr = CondExpr; |
9017 | // Lower out placeholder types first. This is important so that we don't |
9018 | // try to capture a placeholder. This happens in few cases in C++; such |
9019 | // as Objective-C++'s dictionary subscripting syntax. |
9020 | if (commonExpr->hasPlaceholderType()) { |
9021 | ExprResult result = CheckPlaceholderExpr(E: commonExpr); |
9022 | if (!result.isUsable()) return ExprError(); |
9023 | commonExpr = result.get(); |
9024 | } |
9025 | // We usually want to apply unary conversions *before* saving, except |
9026 | // in the special case of a C++ l-value conditional. |
9027 | if (!(getLangOpts().CPlusPlus |
9028 | && !commonExpr->isTypeDependent() |
9029 | && commonExpr->getValueKind() == RHSExpr->getValueKind() |
9030 | && commonExpr->isGLValue() |
9031 | && commonExpr->isOrdinaryOrBitFieldObject() |
9032 | && RHSExpr->isOrdinaryOrBitFieldObject() |
9033 | && Context.hasSameType(T1: commonExpr->getType(), T2: RHSExpr->getType()))) { |
9034 | ExprResult commonRes = UsualUnaryConversions(E: commonExpr); |
9035 | if (commonRes.isInvalid()) |
9036 | return ExprError(); |
9037 | commonExpr = commonRes.get(); |
9038 | } |
9039 | |
9040 | // If the common expression is a class or array prvalue, materialize it |
9041 | // so that we can safely refer to it multiple times. |
9042 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || |
9043 | commonExpr->getType()->isArrayType())) { |
9044 | ExprResult MatExpr = TemporaryMaterializationConversion(E: commonExpr); |
9045 | if (MatExpr.isInvalid()) |
9046 | return ExprError(); |
9047 | commonExpr = MatExpr.get(); |
9048 | } |
9049 | |
9050 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), |
9051 | commonExpr->getType(), |
9052 | commonExpr->getValueKind(), |
9053 | commonExpr->getObjectKind(), |
9054 | commonExpr); |
9055 | LHSExpr = CondExpr = opaqueValue; |
9056 | } |
9057 | |
9058 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); |
9059 | ExprValueKind VK = VK_PRValue; |
9060 | ExprObjectKind OK = OK_Ordinary; |
9061 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; |
9062 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, |
9063 | VK, OK, QuestionLoc); |
9064 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || |
9065 | RHS.isInvalid()) |
9066 | return ExprError(); |
9067 | |
9068 | DiagnoseConditionalPrecedence(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(), |
9069 | RHSExpr: RHS.get()); |
9070 | |
9071 | CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc); |
9072 | |
9073 | result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy, |
9074 | Ctx&: Context); |
9075 | |
9076 | if (!commonExpr) |
9077 | return new (Context) |
9078 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, |
9079 | RHS.get(), result, VK, OK); |
9080 | |
9081 | return new (Context) BinaryConditionalOperator( |
9082 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, |
9083 | ColonLoc, result, VK, OK); |
9084 | } |
9085 | |
9086 | bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) { |
9087 | unsigned FromAttributes = 0, ToAttributes = 0; |
9088 | if (const auto *FromFn = |
9089 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType))) |
9090 | FromAttributes = |
9091 | FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
9092 | if (const auto *ToFn = |
9093 | dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: ToType))) |
9094 | ToAttributes = |
9095 | ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; |
9096 | |
9097 | return FromAttributes != ToAttributes; |
9098 | } |
9099 | |
9100 | // Check if we have a conversion between incompatible cmse function pointer |
9101 | // types, that is, a conversion between a function pointer with the |
9102 | // cmse_nonsecure_call attribute and one without. |
9103 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, |
9104 | QualType ToType) { |
9105 | if (const auto *ToFn = |
9106 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: ToType))) { |
9107 | if (const auto *FromFn = |
9108 | dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: FromType))) { |
9109 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
9110 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
9111 | |
9112 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); |
9113 | } |
9114 | } |
9115 | return false; |
9116 | } |
9117 | |
9118 | // checkPointerTypesForAssignment - This is a very tricky routine (despite |
9119 | // being closely modeled after the C99 spec:-). The odd characteristic of this |
9120 | // routine is it effectively iqnores the qualifiers on the top level pointee. |
9121 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. |
9122 | // FIXME: add a couple examples in this comment. |
9123 | static AssignConvertType checkPointerTypesForAssignment(Sema &S, |
9124 | QualType LHSType, |
9125 | QualType RHSType, |
9126 | SourceLocation Loc) { |
9127 | assert(LHSType.isCanonical() && "LHS not canonicalized!"); |
9128 | assert(RHSType.isCanonical() && "RHS not canonicalized!"); |
9129 | |
9130 | // get the "pointed to" type (ignoring qualifiers at the top level) |
9131 | const Type *lhptee, *rhptee; |
9132 | Qualifiers lhq, rhq; |
9133 | std::tie(args&: lhptee, args&: lhq) = |
9134 | cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair(); |
9135 | std::tie(args&: rhptee, args&: rhq) = |
9136 | cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair(); |
9137 | |
9138 | AssignConvertType ConvTy = AssignConvertType::Compatible; |
9139 | |
9140 | // C99 6.5.16.1p1: This following citation is common to constraints |
9141 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the |
9142 | // qualifiers of the type *pointed to* by the right; |
9143 | |
9144 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. |
9145 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && |
9146 | lhq.compatiblyIncludesObjCLifetime(other: rhq)) { |
9147 | // Ignore lifetime for further calculation. |
9148 | lhq.removeObjCLifetime(); |
9149 | rhq.removeObjCLifetime(); |
9150 | } |
9151 | |
9152 | if (!lhq.compatiblyIncludes(other: rhq, Ctx: S.getASTContext())) { |
9153 | // Treat address-space mismatches as fatal. |
9154 | if (!lhq.isAddressSpaceSupersetOf(other: rhq, Ctx: S.getASTContext())) |
9155 | return AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
9156 | |
9157 | // It's okay to add or remove GC or lifetime qualifiers when converting to |
9158 | // and from void*. |
9159 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes( |
9160 | other: rhq.withoutObjCGCAttr().withoutObjCLifetime(), |
9161 | Ctx: S.getASTContext()) && |
9162 | (lhptee->isVoidType() || rhptee->isVoidType())) |
9163 | ; // keep old |
9164 | |
9165 | // Treat lifetime mismatches as fatal. |
9166 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) |
9167 | ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
9168 | |
9169 | // Treat pointer-auth mismatches as fatal. |
9170 | else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) |
9171 | ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers; |
9172 | |
9173 | // For GCC/MS compatibility, other qualifier mismatches are treated |
9174 | // as still compatible in C. |
9175 | else |
9176 | ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers; |
9177 | } |
9178 | |
9179 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or |
9180 | // incomplete type and the other is a pointer to a qualified or unqualified |
9181 | // version of void... |
9182 | if (lhptee->isVoidType()) { |
9183 | if (rhptee->isIncompleteOrObjectType()) |
9184 | return ConvTy; |
9185 | |
9186 | // As an extension, we allow cast to/from void* to function pointer. |
9187 | assert(rhptee->isFunctionType()); |
9188 | return AssignConvertType::FunctionVoidPointer; |
9189 | } |
9190 | |
9191 | if (rhptee->isVoidType()) { |
9192 | // In C, void * to another pointer type is compatible, but we want to note |
9193 | // that there will be an implicit conversion happening here. |
9194 | if (lhptee->isIncompleteOrObjectType()) |
9195 | return ConvTy == AssignConvertType::Compatible && |
9196 | !S.getLangOpts().CPlusPlus |
9197 | ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr |
9198 | : ConvTy; |
9199 | |
9200 | // As an extension, we allow cast to/from void* to function pointer. |
9201 | assert(lhptee->isFunctionType()); |
9202 | return AssignConvertType::FunctionVoidPointer; |
9203 | } |
9204 | |
9205 | if (!S.Diags.isIgnored( |
9206 | diag::warn_typecheck_convert_incompatible_function_pointer_strict, |
9207 | Loc) && |
9208 | RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && |
9209 | !S.TryFunctionConversion(RHSType, LHSType, RHSType)) |
9210 | return AssignConvertType::IncompatibleFunctionPointerStrict; |
9211 | |
9212 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or |
9213 | // unqualified versions of compatible types, ... |
9214 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); |
9215 | if (!S.Context.typesAreCompatible(T1: ltrans, T2: rtrans)) { |
9216 | // Check if the pointee types are compatible ignoring the sign. |
9217 | // We explicitly check for char so that we catch "char" vs |
9218 | // "unsigned char" on systems where "char" is unsigned. |
9219 | if (lhptee->isCharType()) |
9220 | ltrans = S.Context.UnsignedCharTy; |
9221 | else if (lhptee->hasSignedIntegerRepresentation()) |
9222 | ltrans = S.Context.getCorrespondingUnsignedType(T: ltrans); |
9223 | |
9224 | if (rhptee->isCharType()) |
9225 | rtrans = S.Context.UnsignedCharTy; |
9226 | else if (rhptee->hasSignedIntegerRepresentation()) |
9227 | rtrans = S.Context.getCorrespondingUnsignedType(T: rtrans); |
9228 | |
9229 | if (ltrans == rtrans) { |
9230 | // Types are compatible ignoring the sign. Qualifier incompatibility |
9231 | // takes priority over sign incompatibility because the sign |
9232 | // warning can be disabled. |
9233 | if (!S.IsAssignConvertCompatible(ConvTy)) |
9234 | return ConvTy; |
9235 | |
9236 | return AssignConvertType::IncompatiblePointerSign; |
9237 | } |
9238 | |
9239 | // If we are a multi-level pointer, it's possible that our issue is simply |
9240 | // one of qualification - e.g. char ** -> const char ** is not allowed. If |
9241 | // the eventual target type is the same and the pointers have the same |
9242 | // level of indirection, this must be the issue. |
9243 | if (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)) { |
9244 | do { |
9245 | std::tie(args&: lhptee, args&: lhq) = |
9246 | cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair(); |
9247 | std::tie(args&: rhptee, args&: rhq) = |
9248 | cast<PointerType>(Val: rhptee)->getPointeeType().split().asPair(); |
9249 | |
9250 | // Inconsistent address spaces at this point is invalid, even if the |
9251 | // address spaces would be compatible. |
9252 | // FIXME: This doesn't catch address space mismatches for pointers of |
9253 | // different nesting levels, like: |
9254 | // __local int *** a; |
9255 | // int ** b = a; |
9256 | // It's not clear how to actually determine when such pointers are |
9257 | // invalidly incompatible. |
9258 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) |
9259 | return AssignConvertType:: |
9260 | IncompatibleNestedPointerAddressSpaceMismatch; |
9261 | |
9262 | } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee)); |
9263 | |
9264 | if (lhptee == rhptee) |
9265 | return AssignConvertType::IncompatibleNestedPointerQualifiers; |
9266 | } |
9267 | |
9268 | // General pointer incompatibility takes priority over qualifiers. |
9269 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) |
9270 | return AssignConvertType::IncompatibleFunctionPointer; |
9271 | return AssignConvertType::IncompatiblePointer; |
9272 | } |
9273 | bool DiscardingCFIUncheckedCallee, AddingCFIUncheckedCallee; |
9274 | if (!S.getLangOpts().CPlusPlus && |
9275 | S.IsFunctionConversion(FromType: ltrans, ToType: rtrans, DiscardingCFIUncheckedCallee: &DiscardingCFIUncheckedCallee, |
9276 | AddingCFIUncheckedCallee: &AddingCFIUncheckedCallee)) { |
9277 | // Allow conversions between CFIUncheckedCallee-ness. |
9278 | if (!DiscardingCFIUncheckedCallee && !AddingCFIUncheckedCallee) |
9279 | return AssignConvertType::IncompatibleFunctionPointer; |
9280 | } |
9281 | if (IsInvalidCmseNSCallConversion(S, FromType: ltrans, ToType: rtrans)) |
9282 | return AssignConvertType::IncompatibleFunctionPointer; |
9283 | if (S.IsInvalidSMECallConversion(FromType: rtrans, ToType: ltrans)) |
9284 | return AssignConvertType::IncompatibleFunctionPointer; |
9285 | return ConvTy; |
9286 | } |
9287 | |
9288 | /// checkBlockPointerTypesForAssignment - This routine determines whether two |
9289 | /// block pointer types are compatible or whether a block and normal pointer |
9290 | /// are compatible. It is more restrict than comparing two function pointer |
9291 | // types. |
9292 | static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, |
9293 | QualType LHSType, |
9294 | QualType RHSType) { |
9295 | assert(LHSType.isCanonical() && "LHS not canonicalized!"); |
9296 | assert(RHSType.isCanonical() && "RHS not canonicalized!"); |
9297 | |
9298 | QualType lhptee, rhptee; |
9299 | |
9300 | // get the "pointed to" type (ignoring qualifiers at the top level) |
9301 | lhptee = cast<BlockPointerType>(Val&: LHSType)->getPointeeType(); |
9302 | rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType(); |
9303 | |
9304 | // In C++, the types have to match exactly. |
9305 | if (S.getLangOpts().CPlusPlus) |
9306 | return AssignConvertType::IncompatibleBlockPointer; |
9307 | |
9308 | AssignConvertType ConvTy = AssignConvertType::Compatible; |
9309 | |
9310 | // For blocks we enforce that qualifiers are identical. |
9311 | Qualifiers LQuals = lhptee.getLocalQualifiers(); |
9312 | Qualifiers RQuals = rhptee.getLocalQualifiers(); |
9313 | if (S.getLangOpts().OpenCL) { |
9314 | LQuals.removeAddressSpace(); |
9315 | RQuals.removeAddressSpace(); |
9316 | } |
9317 | if (LQuals != RQuals) |
9318 | ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers; |
9319 | |
9320 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block |
9321 | // assignment. |
9322 | // The current behavior is similar to C++ lambdas. A block might be |
9323 | // assigned to a variable iff its return type and parameters are compatible |
9324 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of |
9325 | // an assignment. Presumably it should behave in way that a function pointer |
9326 | // assignment does in C, so for each parameter and return type: |
9327 | // * CVR and address space of LHS should be a superset of CVR and address |
9328 | // space of RHS. |
9329 | // * unqualified types should be compatible. |
9330 | if (S.getLangOpts().OpenCL) { |
9331 | if (!S.Context.typesAreBlockPointerCompatible( |
9332 | S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals), |
9333 | S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals))) |
9334 | return AssignConvertType::IncompatibleBlockPointer; |
9335 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) |
9336 | return AssignConvertType::IncompatibleBlockPointer; |
9337 | |
9338 | return ConvTy; |
9339 | } |
9340 | |
9341 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types |
9342 | /// for assignment compatibility. |
9343 | static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, |
9344 | QualType LHSType, |
9345 | QualType RHSType) { |
9346 | assert(LHSType.isCanonical() && "LHS was not canonicalized!"); |
9347 | assert(RHSType.isCanonical() && "RHS was not canonicalized!"); |
9348 | |
9349 | if (LHSType->isObjCBuiltinType()) { |
9350 | // Class is not compatible with ObjC object pointers. |
9351 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && |
9352 | !RHSType->isObjCQualifiedClassType()) |
9353 | return AssignConvertType::IncompatiblePointer; |
9354 | return AssignConvertType::Compatible; |
9355 | } |
9356 | if (RHSType->isObjCBuiltinType()) { |
9357 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && |
9358 | !LHSType->isObjCQualifiedClassType()) |
9359 | return AssignConvertType::IncompatiblePointer; |
9360 | return AssignConvertType::Compatible; |
9361 | } |
9362 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
9363 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); |
9364 | |
9365 | if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee, Ctx: S.getASTContext()) && |
9366 | // make an exception for id<P> |
9367 | !LHSType->isObjCQualifiedIdType()) |
9368 | return AssignConvertType::CompatiblePointerDiscardsQualifiers; |
9369 | |
9370 | if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType)) |
9371 | return AssignConvertType::Compatible; |
9372 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) |
9373 | return AssignConvertType::IncompatibleObjCQualifiedId; |
9374 | return AssignConvertType::IncompatiblePointer; |
9375 | } |
9376 | |
9377 | AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc, |
9378 | QualType LHSType, |
9379 | QualType RHSType) { |
9380 | // Fake up an opaque expression. We don't actually care about what |
9381 | // cast operations are required, so if CheckAssignmentConstraints |
9382 | // adds casts to this they'll be wasted, but fortunately that doesn't |
9383 | // usually happen on valid code. |
9384 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); |
9385 | ExprResult RHSPtr = &RHSExpr; |
9386 | CastKind K; |
9387 | |
9388 | return CheckAssignmentConstraints(LHSType, RHS&: RHSPtr, Kind&: K, /*ConvertRHS=*/false); |
9389 | } |
9390 | |
9391 | /// This helper function returns true if QT is a vector type that has element |
9392 | /// type ElementType. |
9393 | static bool isVector(QualType QT, QualType ElementType) { |
9394 | if (const VectorType *VT = QT->getAs<VectorType>()) |
9395 | return VT->getElementType().getCanonicalType() == ElementType; |
9396 | return false; |
9397 | } |
9398 | |
9399 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently |
9400 | /// has code to accommodate several GCC extensions when type checking |
9401 | /// pointers. Here are some objectionable examples that GCC considers warnings: |
9402 | /// |
9403 | /// int a, *pint; |
9404 | /// short *pshort; |
9405 | /// struct foo *pfoo; |
9406 | /// |
9407 | /// pint = pshort; // warning: assignment from incompatible pointer type |
9408 | /// a = pint; // warning: assignment makes integer from pointer without a cast |
9409 | /// pint = a; // warning: assignment makes pointer from integer without a cast |
9410 | /// pint = pfoo; // warning: assignment from incompatible pointer type |
9411 | /// |
9412 | /// As a result, the code for dealing with pointers is more complex than the |
9413 | /// C99 spec dictates. |
9414 | /// |
9415 | /// Sets 'Kind' for any result kind except Incompatible. |
9416 | AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType, |
9417 | ExprResult &RHS, |
9418 | CastKind &Kind, |
9419 | bool ConvertRHS) { |
9420 | QualType RHSType = RHS.get()->getType(); |
9421 | QualType OrigLHSType = LHSType; |
9422 | |
9423 | // Get canonical types. We're not formatting these types, just comparing |
9424 | // them. |
9425 | LHSType = Context.getCanonicalType(T: LHSType).getUnqualifiedType(); |
9426 | RHSType = Context.getCanonicalType(T: RHSType).getUnqualifiedType(); |
9427 | |
9428 | // Common case: no conversion required. |
9429 | if (LHSType == RHSType) { |
9430 | Kind = CK_NoOp; |
9431 | return AssignConvertType::Compatible; |
9432 | } |
9433 | |
9434 | // If the LHS has an __auto_type, there are no additional type constraints |
9435 | // to be worried about. |
9436 | if (const auto *AT = dyn_cast<AutoType>(Val&: LHSType)) { |
9437 | if (AT->isGNUAutoType()) { |
9438 | Kind = CK_NoOp; |
9439 | return AssignConvertType::Compatible; |
9440 | } |
9441 | } |
9442 | |
9443 | // If we have an atomic type, try a non-atomic assignment, then just add an |
9444 | // atomic qualification step. |
9445 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(Val&: LHSType)) { |
9446 | AssignConvertType result = |
9447 | CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind); |
9448 | if (result != AssignConvertType::Compatible) |
9449 | return result; |
9450 | if (Kind != CK_NoOp && ConvertRHS) |
9451 | RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: Kind); |
9452 | Kind = CK_NonAtomicToAtomic; |
9453 | return AssignConvertType::Compatible; |
9454 | } |
9455 | |
9456 | // If the left-hand side is a reference type, then we are in a |
9457 | // (rare!) case where we've allowed the use of references in C, |
9458 | // e.g., as a parameter type in a built-in function. In this case, |
9459 | // just make sure that the type referenced is compatible with the |
9460 | // right-hand side type. The caller is responsible for adjusting |
9461 | // LHSType so that the resulting expression does not have reference |
9462 | // type. |
9463 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { |
9464 | if (Context.typesAreCompatible(T1: LHSTypeRef->getPointeeType(), T2: RHSType)) { |
9465 | Kind = CK_LValueBitCast; |
9466 | return AssignConvertType::Compatible; |
9467 | } |
9468 | return AssignConvertType::Incompatible; |
9469 | } |
9470 | |
9471 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type |
9472 | // to the same ExtVector type. |
9473 | if (LHSType->isExtVectorType()) { |
9474 | if (RHSType->isExtVectorType()) |
9475 | return AssignConvertType::Incompatible; |
9476 | if (RHSType->isArithmeticType()) { |
9477 | // CK_VectorSplat does T -> vector T, so first cast to the element type. |
9478 | if (ConvertRHS) |
9479 | RHS = prepareVectorSplat(VectorTy: LHSType, SplattedExpr: RHS.get()); |
9480 | Kind = CK_VectorSplat; |
9481 | return AssignConvertType::Compatible; |
9482 | } |
9483 | } |
9484 | |
9485 | // Conversions to or from vector type. |
9486 | if (LHSType->isVectorType() || RHSType->isVectorType()) { |
9487 | if (LHSType->isVectorType() && RHSType->isVectorType()) { |
9488 | // Allow assignments of an AltiVec vector type to an equivalent GCC |
9489 | // vector type and vice versa |
9490 | if (Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
9491 | Kind = CK_BitCast; |
9492 | return AssignConvertType::Compatible; |
9493 | } |
9494 | |
9495 | // If we are allowing lax vector conversions, and LHS and RHS are both |
9496 | // vectors, the total size only needs to be the same. This is a bitcast; |
9497 | // no bits are changed but the result type is different. |
9498 | if (isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
9499 | // The default for lax vector conversions with Altivec vectors will |
9500 | // change, so if we are converting between vector types where |
9501 | // at least one is an Altivec vector, emit a warning. |
9502 | if (Context.getTargetInfo().getTriple().isPPC() && |
9503 | anyAltivecTypes(RHSType, LHSType) && |
9504 | !Context.areCompatibleVectorTypes(RHSType, LHSType)) |
9505 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) |
9506 | << RHSType << LHSType; |
9507 | Kind = CK_BitCast; |
9508 | return AssignConvertType::IncompatibleVectors; |
9509 | } |
9510 | } |
9511 | |
9512 | // When the RHS comes from another lax conversion (e.g. binops between |
9513 | // scalars and vectors) the result is canonicalized as a vector. When the |
9514 | // LHS is also a vector, the lax is allowed by the condition above. Handle |
9515 | // the case where LHS is a scalar. |
9516 | if (LHSType->isScalarType()) { |
9517 | const VectorType *VecType = RHSType->getAs<VectorType>(); |
9518 | if (VecType && VecType->getNumElements() == 1 && |
9519 | isLaxVectorConversion(srcTy: RHSType, destTy: LHSType)) { |
9520 | if (Context.getTargetInfo().getTriple().isPPC() && |
9521 | (VecType->getVectorKind() == VectorKind::AltiVecVector || |
9522 | VecType->getVectorKind() == VectorKind::AltiVecBool || |
9523 | VecType->getVectorKind() == VectorKind::AltiVecPixel)) |
9524 | Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) |
9525 | << RHSType << LHSType; |
9526 | ExprResult *VecExpr = &RHS; |
9527 | *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: CK_BitCast); |
9528 | Kind = CK_BitCast; |
9529 | return AssignConvertType::Compatible; |
9530 | } |
9531 | } |
9532 | |
9533 | // Allow assignments between fixed-length and sizeless SVE vectors. |
9534 | if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) || |
9535 | (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType())) |
9536 | if (Context.areCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType) || |
9537 | Context.areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: RHSType)) { |
9538 | Kind = CK_BitCast; |
9539 | return AssignConvertType::Compatible; |
9540 | } |
9541 | |
9542 | // Allow assignments between fixed-length and sizeless RVV vectors. |
9543 | if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) || |
9544 | (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) { |
9545 | if (Context.areCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType) || |
9546 | Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: RHSType)) { |
9547 | Kind = CK_BitCast; |
9548 | return AssignConvertType::Compatible; |
9549 | } |
9550 | } |
9551 | |
9552 | return AssignConvertType::Incompatible; |
9553 | } |
9554 | |
9555 | // Diagnose attempts to convert between __ibm128, __float128 and long double |
9556 | // where such conversions currently can't be handled. |
9557 | if (unsupportedTypeConversion(S: *this, LHSType, RHSType)) |
9558 | return AssignConvertType::Incompatible; |
9559 | |
9560 | // Disallow assigning a _Complex to a real type in C++ mode since it simply |
9561 | // discards the imaginary part. |
9562 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && |
9563 | !LHSType->getAs<ComplexType>()) |
9564 | return AssignConvertType::Incompatible; |
9565 | |
9566 | // Arithmetic conversions. |
9567 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && |
9568 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { |
9569 | if (ConvertRHS) |
9570 | Kind = PrepareScalarCast(Src&: RHS, DestTy: LHSType); |
9571 | return AssignConvertType::Compatible; |
9572 | } |
9573 | |
9574 | // Conversions to normal pointers. |
9575 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) { |
9576 | // U* -> T* |
9577 | if (isa<PointerType>(Val: RHSType)) { |
9578 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
9579 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); |
9580 | if (AddrSpaceL != AddrSpaceR) |
9581 | Kind = CK_AddressSpaceConversion; |
9582 | else if (Context.hasCvrSimilarType(T1: RHSType, T2: LHSType)) |
9583 | Kind = CK_NoOp; |
9584 | else |
9585 | Kind = CK_BitCast; |
9586 | return checkPointerTypesForAssignment(*this, LHSType, RHSType, |
9587 | RHS.get()->getBeginLoc()); |
9588 | } |
9589 | |
9590 | // int -> T* |
9591 | if (RHSType->isIntegerType()) { |
9592 | Kind = CK_IntegralToPointer; // FIXME: null? |
9593 | return AssignConvertType::IntToPointer; |
9594 | } |
9595 | |
9596 | // C pointers are not compatible with ObjC object pointers, |
9597 | // with two exceptions: |
9598 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
9599 | // - conversions to void* |
9600 | if (LHSPointer->getPointeeType()->isVoidType()) { |
9601 | Kind = CK_BitCast; |
9602 | return AssignConvertType::Compatible; |
9603 | } |
9604 | |
9605 | // - conversions from 'Class' to the redefinition type |
9606 | if (RHSType->isObjCClassType() && |
9607 | Context.hasSameType(T1: LHSType, |
9608 | T2: Context.getObjCClassRedefinitionType())) { |
9609 | Kind = CK_BitCast; |
9610 | return AssignConvertType::Compatible; |
9611 | } |
9612 | |
9613 | Kind = CK_BitCast; |
9614 | return AssignConvertType::IncompatiblePointer; |
9615 | } |
9616 | |
9617 | // U^ -> void* |
9618 | if (RHSType->getAs<BlockPointerType>()) { |
9619 | if (LHSPointer->getPointeeType()->isVoidType()) { |
9620 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
9621 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
9622 | ->getPointeeType() |
9623 | .getAddressSpace(); |
9624 | Kind = |
9625 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
9626 | return AssignConvertType::Compatible; |
9627 | } |
9628 | } |
9629 | |
9630 | return AssignConvertType::Incompatible; |
9631 | } |
9632 | |
9633 | // Conversions to block pointers. |
9634 | if (isa<BlockPointerType>(Val: LHSType)) { |
9635 | // U^ -> T^ |
9636 | if (RHSType->isBlockPointerType()) { |
9637 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() |
9638 | ->getPointeeType() |
9639 | .getAddressSpace(); |
9640 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
9641 | ->getPointeeType() |
9642 | .getAddressSpace(); |
9643 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
9644 | return checkBlockPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
9645 | } |
9646 | |
9647 | // int or null -> T^ |
9648 | if (RHSType->isIntegerType()) { |
9649 | Kind = CK_IntegralToPointer; // FIXME: null |
9650 | return AssignConvertType::IntToBlockPointer; |
9651 | } |
9652 | |
9653 | // id -> T^ |
9654 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { |
9655 | Kind = CK_AnyPointerToBlockPointerCast; |
9656 | return AssignConvertType::Compatible; |
9657 | } |
9658 | |
9659 | // void* -> T^ |
9660 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) |
9661 | if (RHSPT->getPointeeType()->isVoidType()) { |
9662 | Kind = CK_AnyPointerToBlockPointerCast; |
9663 | return AssignConvertType::Compatible; |
9664 | } |
9665 | |
9666 | return AssignConvertType::Incompatible; |
9667 | } |
9668 | |
9669 | // Conversions to Objective-C pointers. |
9670 | if (isa<ObjCObjectPointerType>(Val: LHSType)) { |
9671 | // A* -> B* |
9672 | if (RHSType->isObjCObjectPointerType()) { |
9673 | Kind = CK_BitCast; |
9674 | AssignConvertType result = |
9675 | checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType); |
9676 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
9677 | result == AssignConvertType::Compatible && |
9678 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: RHSType)) |
9679 | result = AssignConvertType::IncompatibleObjCWeakRef; |
9680 | return result; |
9681 | } |
9682 | |
9683 | // int or null -> A* |
9684 | if (RHSType->isIntegerType()) { |
9685 | Kind = CK_IntegralToPointer; // FIXME: null |
9686 | return AssignConvertType::IntToPointer; |
9687 | } |
9688 | |
9689 | // In general, C pointers are not compatible with ObjC object pointers, |
9690 | // with two exceptions: |
9691 | if (isa<PointerType>(Val: RHSType)) { |
9692 | Kind = CK_CPointerToObjCPointerCast; |
9693 | |
9694 | // - conversions from 'void*' |
9695 | if (RHSType->isVoidPointerType()) { |
9696 | return AssignConvertType::Compatible; |
9697 | } |
9698 | |
9699 | // - conversions to 'Class' from its redefinition type |
9700 | if (LHSType->isObjCClassType() && |
9701 | Context.hasSameType(T1: RHSType, |
9702 | T2: Context.getObjCClassRedefinitionType())) { |
9703 | return AssignConvertType::Compatible; |
9704 | } |
9705 | |
9706 | return AssignConvertType::IncompatiblePointer; |
9707 | } |
9708 | |
9709 | // Only under strict condition T^ is compatible with an Objective-C pointer. |
9710 | if (RHSType->isBlockPointerType() && |
9711 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
9712 | if (ConvertRHS) |
9713 | maybeExtendBlockObject(E&: RHS); |
9714 | Kind = CK_BlockPointerToObjCPointerCast; |
9715 | return AssignConvertType::Compatible; |
9716 | } |
9717 | |
9718 | return AssignConvertType::Incompatible; |
9719 | } |
9720 | |
9721 | // Conversion to nullptr_t (C23 only) |
9722 | if (getLangOpts().C23 && LHSType->isNullPtrType() && |
9723 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
9724 | NPC: Expr::NPC_ValueDependentIsNull)) { |
9725 | // null -> nullptr_t |
9726 | Kind = CK_NullToPointer; |
9727 | return AssignConvertType::Compatible; |
9728 | } |
9729 | |
9730 | // Conversions from pointers that are not covered by the above. |
9731 | if (isa<PointerType>(Val: RHSType)) { |
9732 | // T* -> _Bool |
9733 | if (LHSType == Context.BoolTy) { |
9734 | Kind = CK_PointerToBoolean; |
9735 | return AssignConvertType::Compatible; |
9736 | } |
9737 | |
9738 | // T* -> int |
9739 | if (LHSType->isIntegerType()) { |
9740 | Kind = CK_PointerToIntegral; |
9741 | return AssignConvertType::PointerToInt; |
9742 | } |
9743 | |
9744 | return AssignConvertType::Incompatible; |
9745 | } |
9746 | |
9747 | // Conversions from Objective-C pointers that are not covered by the above. |
9748 | if (isa<ObjCObjectPointerType>(Val: RHSType)) { |
9749 | // T* -> _Bool |
9750 | if (LHSType == Context.BoolTy) { |
9751 | Kind = CK_PointerToBoolean; |
9752 | return AssignConvertType::Compatible; |
9753 | } |
9754 | |
9755 | // T* -> int |
9756 | if (LHSType->isIntegerType()) { |
9757 | Kind = CK_PointerToIntegral; |
9758 | return AssignConvertType::PointerToInt; |
9759 | } |
9760 | |
9761 | return AssignConvertType::Incompatible; |
9762 | } |
9763 | |
9764 | // struct A -> struct B |
9765 | if (isa<TagType>(Val: LHSType) && isa<TagType>(Val: RHSType)) { |
9766 | if (Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
9767 | Kind = CK_NoOp; |
9768 | return AssignConvertType::Compatible; |
9769 | } |
9770 | } |
9771 | |
9772 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { |
9773 | Kind = CK_IntToOCLSampler; |
9774 | return AssignConvertType::Compatible; |
9775 | } |
9776 | |
9777 | return AssignConvertType::Incompatible; |
9778 | } |
9779 | |
9780 | /// Constructs a transparent union from an expression that is |
9781 | /// used to initialize the transparent union. |
9782 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, |
9783 | ExprResult &EResult, QualType UnionType, |
9784 | FieldDecl *Field) { |
9785 | // Build an initializer list that designates the appropriate member |
9786 | // of the transparent union. |
9787 | Expr *E = EResult.get(); |
9788 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), |
9789 | E, SourceLocation()); |
9790 | Initializer->setType(UnionType); |
9791 | Initializer->setInitializedFieldInUnion(Field); |
9792 | |
9793 | // Build a compound literal constructing a value of the transparent |
9794 | // union type from this initializer list. |
9795 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(T: UnionType); |
9796 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, |
9797 | VK_PRValue, Initializer, false); |
9798 | } |
9799 | |
9800 | AssignConvertType |
9801 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, |
9802 | ExprResult &RHS) { |
9803 | QualType RHSType = RHS.get()->getType(); |
9804 | |
9805 | // If the ArgType is a Union type, we want to handle a potential |
9806 | // transparent_union GCC extension. |
9807 | const RecordType *UT = ArgType->getAsUnionType(); |
9808 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
9809 | return AssignConvertType::Incompatible; |
9810 | |
9811 | // The field to initialize within the transparent union. |
9812 | RecordDecl *UD = UT->getDecl(); |
9813 | FieldDecl *InitField = nullptr; |
9814 | // It's compatible if the expression matches any of the fields. |
9815 | for (auto *it : UD->fields()) { |
9816 | if (it->getType()->isPointerType()) { |
9817 | // If the transparent union contains a pointer type, we allow: |
9818 | // 1) void pointer |
9819 | // 2) null pointer constant |
9820 | if (RHSType->isPointerType()) |
9821 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
9822 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); |
9823 | InitField = it; |
9824 | break; |
9825 | } |
9826 | |
9827 | if (RHS.get()->isNullPointerConstant(Context, |
9828 | Expr::NPC_ValueDependentIsNull)) { |
9829 | RHS = ImpCastExprToType(RHS.get(), it->getType(), |
9830 | CK_NullToPointer); |
9831 | InitField = it; |
9832 | break; |
9833 | } |
9834 | } |
9835 | |
9836 | CastKind Kind; |
9837 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) == |
9838 | AssignConvertType::Compatible) { |
9839 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); |
9840 | InitField = it; |
9841 | break; |
9842 | } |
9843 | } |
9844 | |
9845 | if (!InitField) |
9846 | return AssignConvertType::Incompatible; |
9847 | |
9848 | ConstructTransparentUnion(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField); |
9849 | return AssignConvertType::Compatible; |
9850 | } |
9851 | |
9852 | AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType, |
9853 | ExprResult &CallerRHS, |
9854 | bool Diagnose, |
9855 | bool DiagnoseCFAudited, |
9856 | bool ConvertRHS) { |
9857 | // We need to be able to tell the caller whether we diagnosed a problem, if |
9858 | // they ask us to issue diagnostics. |
9859 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); |
9860 | |
9861 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, |
9862 | // we can't avoid *all* modifications at the moment, so we need some somewhere |
9863 | // to put the updated value. |
9864 | ExprResult LocalRHS = CallerRHS; |
9865 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; |
9866 | |
9867 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { |
9868 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { |
9869 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && |
9870 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { |
9871 | Diag(RHS.get()->getExprLoc(), |
9872 | diag::warn_noderef_to_dereferenceable_pointer) |
9873 | << RHS.get()->getSourceRange(); |
9874 | } |
9875 | } |
9876 | } |
9877 | |
9878 | if (getLangOpts().CPlusPlus) { |
9879 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { |
9880 | // C++ 5.17p3: If the left operand is not of class type, the |
9881 | // expression is implicitly converted (C++ 4) to the |
9882 | // cv-unqualified type of the left operand. |
9883 | QualType RHSType = RHS.get()->getType(); |
9884 | if (Diagnose) { |
9885 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9886 | Action: AssignmentAction::Assigning); |
9887 | } else { |
9888 | ImplicitConversionSequence ICS = |
9889 | TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9890 | /*SuppressUserConversions=*/false, |
9891 | AllowExplicit: AllowedExplicit::None, |
9892 | /*InOverloadResolution=*/false, |
9893 | /*CStyle=*/false, |
9894 | /*AllowObjCWritebackConversion=*/false); |
9895 | if (ICS.isFailure()) |
9896 | return AssignConvertType::Incompatible; |
9897 | RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(), |
9898 | ICS, Action: AssignmentAction::Assigning); |
9899 | } |
9900 | if (RHS.isInvalid()) |
9901 | return AssignConvertType::Incompatible; |
9902 | AssignConvertType result = AssignConvertType::Compatible; |
9903 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
9904 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: RHSType)) |
9905 | result = AssignConvertType::IncompatibleObjCWeakRef; |
9906 | return result; |
9907 | } |
9908 | |
9909 | // FIXME: Currently, we fall through and treat C++ classes like C |
9910 | // structures. |
9911 | // FIXME: We also fall through for atomics; not sure what should |
9912 | // happen there, though. |
9913 | } else if (RHS.get()->getType() == Context.OverloadTy) { |
9914 | // As a set of extensions to C, we support overloading on functions. These |
9915 | // functions need to be resolved here. |
9916 | DeclAccessPair DAP; |
9917 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( |
9918 | AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP)) |
9919 | RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: FD); |
9920 | else |
9921 | return AssignConvertType::Incompatible; |
9922 | } |
9923 | |
9924 | // This check seems unnatural, however it is necessary to ensure the proper |
9925 | // conversion of functions/arrays. If the conversion were done for all |
9926 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary |
9927 | // expressions that suppress this implicit conversion (&, sizeof). This needs |
9928 | // to happen before we check for null pointer conversions because C does not |
9929 | // undergo the same implicit conversions as C++ does above (by the calls to |
9930 | // TryImplicitConversion() and PerformImplicitConversion()) which insert the |
9931 | // lvalue to rvalue cast before checking for null pointer constraints. This |
9932 | // addresses code like: nullptr_t val; int *ptr; ptr = val; |
9933 | // |
9934 | // Suppress this for references: C++ 8.5.3p5. |
9935 | if (!LHSType->isReferenceType()) { |
9936 | // FIXME: We potentially allocate here even if ConvertRHS is false. |
9937 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose); |
9938 | if (RHS.isInvalid()) |
9939 | return AssignConvertType::Incompatible; |
9940 | } |
9941 | |
9942 | // The constraints are expressed in terms of the atomic, qualified, or |
9943 | // unqualified type of the LHS. |
9944 | QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType(); |
9945 | |
9946 | // C99 6.5.16.1p1: the left operand is a pointer and the right is |
9947 | // a null pointer constant <C23>or its type is nullptr_t;</C23>. |
9948 | if ((LHSTypeAfterConversion->isPointerType() || |
9949 | LHSTypeAfterConversion->isObjCObjectPointerType() || |
9950 | LHSTypeAfterConversion->isBlockPointerType()) && |
9951 | ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) || |
9952 | RHS.get()->isNullPointerConstant(Ctx&: Context, |
9953 | NPC: Expr::NPC_ValueDependentIsNull))) { |
9954 | AssignConvertType Ret = AssignConvertType::Compatible; |
9955 | if (Diagnose || ConvertRHS) { |
9956 | CastKind Kind; |
9957 | CXXCastPath Path; |
9958 | CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path, |
9959 | /*IgnoreBaseAccess=*/false, Diagnose); |
9960 | |
9961 | // If there is a conversion of some kind, check to see what kind of |
9962 | // pointer conversion happened so we can diagnose a C++ compatibility |
9963 | // diagnostic if the conversion is invalid. This only matters if the RHS |
9964 | // is some kind of void pointer. We have a carve-out when the RHS is from |
9965 | // a macro expansion because the use of a macro may indicate different |
9966 | // code between C and C++. Consider: char *s = NULL; where NULL is |
9967 | // defined as (void *)0 in C (which would be invalid in C++), but 0 in |
9968 | // C++, which is valid in C++. |
9969 | if (Kind != CK_NoOp && !getLangOpts().CPlusPlus && |
9970 | !RHS.get()->getBeginLoc().isMacroID()) { |
9971 | QualType CanRHS = |
9972 | RHS.get()->getType().getCanonicalType().getUnqualifiedType(); |
9973 | QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType(); |
9974 | if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) { |
9975 | Ret = checkPointerTypesForAssignment(S&: *this, LHSType: CanLHS, RHSType: CanRHS, |
9976 | Loc: RHS.get()->getExprLoc()); |
9977 | // Anything that's not considered perfectly compatible would be |
9978 | // incompatible in C++. |
9979 | if (Ret != AssignConvertType::Compatible) |
9980 | Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr; |
9981 | } |
9982 | } |
9983 | |
9984 | if (ConvertRHS) |
9985 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &Path); |
9986 | } |
9987 | return Ret; |
9988 | } |
9989 | // C23 6.5.16.1p1: the left operand has type atomic, qualified, or |
9990 | // unqualified bool, and the right operand is a pointer or its type is |
9991 | // nullptr_t. |
9992 | if (getLangOpts().C23 && LHSType->isBooleanType() && |
9993 | RHS.get()->getType()->isNullPtrType()) { |
9994 | // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only |
9995 | // only handles nullptr -> _Bool due to needing an extra conversion |
9996 | // step. |
9997 | // We model this by converting from nullptr -> void * and then let the |
9998 | // conversion from void * -> _Bool happen naturally. |
9999 | if (Diagnose || ConvertRHS) { |
10000 | CastKind Kind; |
10001 | CXXCastPath Path; |
10002 | CheckPointerConversion(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path, |
10003 | /*IgnoreBaseAccess=*/false, Diagnose); |
10004 | if (ConvertRHS) |
10005 | RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue, |
10006 | BasePath: &Path); |
10007 | } |
10008 | } |
10009 | |
10010 | // OpenCL queue_t type assignment. |
10011 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( |
10012 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
10013 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
10014 | return AssignConvertType::Compatible; |
10015 | } |
10016 | |
10017 | CastKind Kind; |
10018 | AssignConvertType result = |
10019 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); |
10020 | |
10021 | // C99 6.5.16.1p2: The value of the right operand is converted to the |
10022 | // type of the assignment expression. |
10023 | // CheckAssignmentConstraints allows the left-hand side to be a reference, |
10024 | // so that we can use references in built-in functions even in C. |
10025 | // The getNonReferenceType() call makes sure that the resulting expression |
10026 | // does not have reference type. |
10027 | if (result != AssignConvertType::Incompatible && |
10028 | RHS.get()->getType() != LHSType) { |
10029 | QualType Ty = LHSType.getNonLValueExprType(Context); |
10030 | Expr *E = RHS.get(); |
10031 | |
10032 | // Check for various Objective-C errors. If we are not reporting |
10033 | // diagnostics and just checking for errors, e.g., during overload |
10034 | // resolution, return Incompatible to indicate the failure. |
10035 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
10036 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E, |
10037 | CCK: CheckedConversionKind::Implicit, Diagnose, |
10038 | DiagnoseCFAudited) != SemaObjC::ACR_okay) { |
10039 | if (!Diagnose) |
10040 | return AssignConvertType::Incompatible; |
10041 | } |
10042 | if (getLangOpts().ObjC && |
10043 | (ObjC().CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType, |
10044 | SrcType: E->getType(), SrcExpr&: E, Diagnose) || |
10045 | ObjC().CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: E, Diagnose))) { |
10046 | if (!Diagnose) |
10047 | return AssignConvertType::Incompatible; |
10048 | // Replace the expression with a corrected version and continue so we |
10049 | // can find further errors. |
10050 | RHS = E; |
10051 | return AssignConvertType::Compatible; |
10052 | } |
10053 | |
10054 | if (ConvertRHS) |
10055 | RHS = ImpCastExprToType(E, Type: Ty, CK: Kind); |
10056 | } |
10057 | |
10058 | return result; |
10059 | } |
10060 | |
10061 | namespace { |
10062 | /// The original operand to an operator, prior to the application of the usual |
10063 | /// arithmetic conversions and converting the arguments of a builtin operator |
10064 | /// candidate. |
10065 | struct OriginalOperand { |
10066 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { |
10067 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Op)) |
10068 | Op = MTE->getSubExpr(); |
10069 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op)) |
10070 | Op = BTE->getSubExpr(); |
10071 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Op)) { |
10072 | Orig = ICE->getSubExprAsWritten(); |
10073 | Conversion = ICE->getConversionFunction(); |
10074 | } |
10075 | } |
10076 | |
10077 | QualType getType() const { return Orig->getType(); } |
10078 | |
10079 | Expr *Orig; |
10080 | NamedDecl *Conversion; |
10081 | }; |
10082 | } |
10083 | |
10084 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
10085 | ExprResult &RHS) { |
10086 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); |
10087 | |
10088 | Diag(Loc, diag::err_typecheck_invalid_operands) |
10089 | << OrigLHS.getType() << OrigRHS.getType() |
10090 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10091 | |
10092 | // If a user-defined conversion was applied to either of the operands prior |
10093 | // to applying the built-in operator rules, tell the user about it. |
10094 | if (OrigLHS.Conversion) { |
10095 | Diag(OrigLHS.Conversion->getLocation(), |
10096 | diag::note_typecheck_invalid_operands_converted) |
10097 | << 0 << LHS.get()->getType(); |
10098 | } |
10099 | if (OrigRHS.Conversion) { |
10100 | Diag(OrigRHS.Conversion->getLocation(), |
10101 | diag::note_typecheck_invalid_operands_converted) |
10102 | << 1 << RHS.get()->getType(); |
10103 | } |
10104 | |
10105 | return QualType(); |
10106 | } |
10107 | |
10108 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
10109 | ExprResult &RHS) { |
10110 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); |
10111 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); |
10112 | |
10113 | bool LHSNatVec = LHSType->isVectorType(); |
10114 | bool RHSNatVec = RHSType->isVectorType(); |
10115 | |
10116 | if (!(LHSNatVec && RHSNatVec)) { |
10117 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); |
10118 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); |
10119 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
10120 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() |
10121 | << Vector->getSourceRange(); |
10122 | return QualType(); |
10123 | } |
10124 | |
10125 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
10126 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() |
10127 | << RHS.get()->getSourceRange(); |
10128 | |
10129 | return QualType(); |
10130 | } |
10131 | |
10132 | /// Try to convert a value of non-vector type to a vector type by converting |
10133 | /// the type to the element type of the vector and then performing a splat. |
10134 | /// If the language is OpenCL, we only use conversions that promote scalar |
10135 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except |
10136 | /// for float->int. |
10137 | /// |
10138 | /// OpenCL V2.0 6.2.6.p2: |
10139 | /// An error shall occur if any scalar operand type has greater rank |
10140 | /// than the type of the vector element. |
10141 | /// |
10142 | /// \param scalar - if non-null, actually perform the conversions |
10143 | /// \return true if the operation fails (but without diagnosing the failure) |
10144 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, |
10145 | QualType scalarTy, |
10146 | QualType vectorEltTy, |
10147 | QualType vectorTy, |
10148 | unsigned &DiagID) { |
10149 | // The conversion to apply to the scalar before splatting it, |
10150 | // if necessary. |
10151 | CastKind scalarCast = CK_NoOp; |
10152 | |
10153 | if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(Ctx: S.Context)) { |
10154 | scalarCast = CK_IntegralToBoolean; |
10155 | } else if (vectorEltTy->isIntegralType(Ctx: S.Context)) { |
10156 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || |
10157 | (scalarTy->isIntegerType() && |
10158 | S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) { |
10159 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
10160 | return true; |
10161 | } |
10162 | if (!scalarTy->isIntegralType(Ctx: S.Context)) |
10163 | return true; |
10164 | scalarCast = CK_IntegralCast; |
10165 | } else if (vectorEltTy->isRealFloatingType()) { |
10166 | if (scalarTy->isRealFloatingType()) { |
10167 | if (S.getLangOpts().OpenCL && |
10168 | S.Context.getFloatingTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0) { |
10169 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
10170 | return true; |
10171 | } |
10172 | scalarCast = CK_FloatingCast; |
10173 | } |
10174 | else if (scalarTy->isIntegralType(Ctx: S.Context)) |
10175 | scalarCast = CK_IntegralToFloating; |
10176 | else |
10177 | return true; |
10178 | } else { |
10179 | return true; |
10180 | } |
10181 | |
10182 | // Adjust scalar if desired. |
10183 | if (scalar) { |
10184 | if (scalarCast != CK_NoOp) |
10185 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorEltTy, CK: scalarCast); |
10186 | *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: CK_VectorSplat); |
10187 | } |
10188 | return false; |
10189 | } |
10190 | |
10191 | /// Convert vector E to a vector with the same number of elements but different |
10192 | /// element type. |
10193 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { |
10194 | const auto *VecTy = E->getType()->getAs<VectorType>(); |
10195 | assert(VecTy && "Expression E must be a vector"); |
10196 | QualType NewVecTy = |
10197 | VecTy->isExtVectorType() |
10198 | ? S.Context.getExtVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements()) |
10199 | : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(), |
10200 | VecKind: VecTy->getVectorKind()); |
10201 | |
10202 | // Look through the implicit cast. Return the subexpression if its type is |
10203 | // NewVecTy. |
10204 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
10205 | if (ICE->getSubExpr()->getType() == NewVecTy) |
10206 | return ICE->getSubExpr(); |
10207 | |
10208 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; |
10209 | return S.ImpCastExprToType(E, Type: NewVecTy, CK: Cast); |
10210 | } |
10211 | |
10212 | /// Test if a (constant) integer Int can be casted to another integer type |
10213 | /// IntTy without losing precision. |
10214 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, |
10215 | QualType OtherIntTy) { |
10216 | if (Int->get()->containsErrors()) |
10217 | return false; |
10218 | |
10219 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
10220 | |
10221 | // Reject cases where the value of the Int is unknown as that would |
10222 | // possibly cause truncation, but accept cases where the scalar can be |
10223 | // demoted without loss of precision. |
10224 | Expr::EvalResult EVResult; |
10225 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
10226 | int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: IntTy); |
10227 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); |
10228 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); |
10229 | |
10230 | if (CstInt) { |
10231 | // If the scalar is constant and is of a higher order and has more active |
10232 | // bits that the vector element type, reject it. |
10233 | llvm::APSInt Result = EVResult.Val.getInt(); |
10234 | unsigned NumBits = IntSigned |
10235 | ? (Result.isNegative() ? Result.getSignificantBits() |
10236 | : Result.getActiveBits()) |
10237 | : Result.getActiveBits(); |
10238 | if (Order < 0 && S.Context.getIntWidth(T: OtherIntTy) < NumBits) |
10239 | return true; |
10240 | |
10241 | // If the signedness of the scalar type and the vector element type |
10242 | // differs and the number of bits is greater than that of the vector |
10243 | // element reject it. |
10244 | return (IntSigned != OtherIntSigned && |
10245 | NumBits > S.Context.getIntWidth(T: OtherIntTy)); |
10246 | } |
10247 | |
10248 | // Reject cases where the value of the scalar is not constant and it's |
10249 | // order is greater than that of the vector element type. |
10250 | return (Order < 0); |
10251 | } |
10252 | |
10253 | /// Test if a (constant) integer Int can be casted to floating point type |
10254 | /// FloatTy without losing precision. |
10255 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, |
10256 | QualType FloatTy) { |
10257 | if (Int->get()->containsErrors()) |
10258 | return false; |
10259 | |
10260 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
10261 | |
10262 | // Determine if the integer constant can be expressed as a floating point |
10263 | // number of the appropriate type. |
10264 | Expr::EvalResult EVResult; |
10265 | bool CstInt = Int->get()->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
10266 | |
10267 | uint64_t Bits = 0; |
10268 | if (CstInt) { |
10269 | // Reject constants that would be truncated if they were converted to |
10270 | // the floating point type. Test by simple to/from conversion. |
10271 | // FIXME: Ideally the conversion to an APFloat and from an APFloat |
10272 | // could be avoided if there was a convertFromAPInt method |
10273 | // which could signal back if implicit truncation occurred. |
10274 | llvm::APSInt Result = EVResult.Val.getInt(); |
10275 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(T: FloatTy)); |
10276 | Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(), |
10277 | RM: llvm::APFloat::rmTowardZero); |
10278 | llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy), |
10279 | !IntTy->hasSignedIntegerRepresentation()); |
10280 | bool Ignored = false; |
10281 | Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven, |
10282 | IsExact: &Ignored); |
10283 | if (Result != ConvertBack) |
10284 | return true; |
10285 | } else { |
10286 | // Reject types that cannot be fully encoded into the mantissa of |
10287 | // the float. |
10288 | Bits = S.Context.getTypeSize(T: IntTy); |
10289 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( |
10290 | S.Context.getFloatTypeSemantics(T: FloatTy)); |
10291 | if (Bits > FloatPrec) |
10292 | return true; |
10293 | } |
10294 | |
10295 | return false; |
10296 | } |
10297 | |
10298 | /// Attempt to convert and splat Scalar into a vector whose types matches |
10299 | /// Vector following GCC conversion rules. The rule is that implicit |
10300 | /// conversion can occur when Scalar can be casted to match Vector's element |
10301 | /// type without causing truncation of Scalar. |
10302 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, |
10303 | ExprResult *Vector) { |
10304 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); |
10305 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); |
10306 | QualType VectorEltTy; |
10307 | |
10308 | if (const auto *VT = VectorTy->getAs<VectorType>()) { |
10309 | assert(!isa<ExtVectorType>(VT) && |
10310 | "ExtVectorTypes should not be handled here!"); |
10311 | VectorEltTy = VT->getElementType(); |
10312 | } else if (VectorTy->isSveVLSBuiltinType()) { |
10313 | VectorEltTy = |
10314 | VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext()); |
10315 | } else { |
10316 | llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here"); |
10317 | } |
10318 | |
10319 | // Reject cases where the vector element type or the scalar element type are |
10320 | // not integral or floating point types. |
10321 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) |
10322 | return true; |
10323 | |
10324 | // The conversion to apply to the scalar before splatting it, |
10325 | // if necessary. |
10326 | CastKind ScalarCast = CK_NoOp; |
10327 | |
10328 | // Accept cases where the vector elements are integers and the scalar is |
10329 | // an integer. |
10330 | // FIXME: Notionally if the scalar was a floating point value with a precise |
10331 | // integral representation, we could cast it to an appropriate integer |
10332 | // type and then perform the rest of the checks here. GCC will perform |
10333 | // this conversion in some cases as determined by the input language. |
10334 | // We should accept it on a language independent basis. |
10335 | if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
10336 | ScalarTy->isIntegralType(Ctx: S.Context) && |
10337 | S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) { |
10338 | |
10339 | if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy)) |
10340 | return true; |
10341 | |
10342 | ScalarCast = CK_IntegralCast; |
10343 | } else if (VectorEltTy->isIntegralType(Ctx: S.Context) && |
10344 | ScalarTy->isRealFloatingType()) { |
10345 | if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: ScalarTy)) |
10346 | ScalarCast = CK_FloatingToIntegral; |
10347 | else |
10348 | return true; |
10349 | } else if (VectorEltTy->isRealFloatingType()) { |
10350 | if (ScalarTy->isRealFloatingType()) { |
10351 | |
10352 | // Reject cases where the scalar type is not a constant and has a higher |
10353 | // Order than the vector element type. |
10354 | llvm::APFloat Result(0.0); |
10355 | |
10356 | // Determine whether this is a constant scalar. In the event that the |
10357 | // value is dependent (and thus cannot be evaluated by the constant |
10358 | // evaluator), skip the evaluation. This will then diagnose once the |
10359 | // expression is instantiated. |
10360 | bool CstScalar = Scalar->get()->isValueDependent() || |
10361 | Scalar->get()->EvaluateAsFloat(Result, Ctx: S.Context); |
10362 | int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: ScalarTy); |
10363 | if (!CstScalar && Order < 0) |
10364 | return true; |
10365 | |
10366 | // If the scalar cannot be safely casted to the vector element type, |
10367 | // reject it. |
10368 | if (CstScalar) { |
10369 | bool Truncated = false; |
10370 | Result.convert(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy), |
10371 | RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated); |
10372 | if (Truncated) |
10373 | return true; |
10374 | } |
10375 | |
10376 | ScalarCast = CK_FloatingCast; |
10377 | } else if (ScalarTy->isIntegralType(Ctx: S.Context)) { |
10378 | if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: VectorEltTy)) |
10379 | return true; |
10380 | |
10381 | ScalarCast = CK_IntegralToFloating; |
10382 | } else |
10383 | return true; |
10384 | } else if (ScalarTy->isEnumeralType()) |
10385 | return true; |
10386 | |
10387 | // Adjust scalar if desired. |
10388 | if (ScalarCast != CK_NoOp) |
10389 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast); |
10390 | *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat); |
10391 | return false; |
10392 | } |
10393 | |
10394 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
10395 | SourceLocation Loc, bool IsCompAssign, |
10396 | bool AllowBothBool, |
10397 | bool AllowBoolConversions, |
10398 | bool AllowBoolOperation, |
10399 | bool ReportInvalid) { |
10400 | if (!IsCompAssign) { |
10401 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
10402 | if (LHS.isInvalid()) |
10403 | return QualType(); |
10404 | } |
10405 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
10406 | if (RHS.isInvalid()) |
10407 | return QualType(); |
10408 | |
10409 | // For conversion purposes, we ignore any qualifiers. |
10410 | // For example, "const float" and "float" are equivalent. |
10411 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
10412 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
10413 | |
10414 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); |
10415 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); |
10416 | assert(LHSVecType || RHSVecType); |
10417 | |
10418 | if (getLangOpts().HLSL) |
10419 | return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType, |
10420 | IsCompAssign); |
10421 | |
10422 | // Any operation with MFloat8 type is only possible with C intrinsics |
10423 | if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) || |
10424 | (RHSVecType && RHSVecType->getElementType()->isMFloat8Type())) |
10425 | return InvalidOperands(Loc, LHS, RHS); |
10426 | |
10427 | // AltiVec-style "vector bool op vector bool" combinations are allowed |
10428 | // for some operators but not others. |
10429 | if (!AllowBothBool && LHSVecType && |
10430 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType && |
10431 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
10432 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
10433 | |
10434 | // This operation may not be performed on boolean vectors. |
10435 | if (!AllowBoolOperation && |
10436 | (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) |
10437 | return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); |
10438 | |
10439 | // If the vector types are identical, return. |
10440 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
10441 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
10442 | |
10443 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. |
10444 | if (LHSVecType && RHSVecType && |
10445 | Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) { |
10446 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
10447 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
10448 | return LHSType; |
10449 | } |
10450 | |
10451 | if (!IsCompAssign) |
10452 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
10453 | return RHSType; |
10454 | } |
10455 | |
10456 | // AllowBoolConversions says that bool and non-bool AltiVec vectors |
10457 | // can be mixed, with the result being the non-bool type. The non-bool |
10458 | // operand must have integer element type. |
10459 | if (AllowBoolConversions && LHSVecType && RHSVecType && |
10460 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && |
10461 | (Context.getTypeSize(T: LHSVecType->getElementType()) == |
10462 | Context.getTypeSize(T: RHSVecType->getElementType()))) { |
10463 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
10464 | LHSVecType->getElementType()->isIntegerType() && |
10465 | RHSVecType->getVectorKind() == VectorKind::AltiVecBool) { |
10466 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
10467 | return LHSType; |
10468 | } |
10469 | if (!IsCompAssign && |
10470 | LHSVecType->getVectorKind() == VectorKind::AltiVecBool && |
10471 | RHSVecType->getVectorKind() == VectorKind::AltiVecVector && |
10472 | RHSVecType->getElementType()->isIntegerType()) { |
10473 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
10474 | return RHSType; |
10475 | } |
10476 | } |
10477 | |
10478 | // Expressions containing fixed-length and sizeless SVE/RVV vectors are |
10479 | // invalid since the ambiguity can affect the ABI. |
10480 | auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType, |
10481 | unsigned &SVEorRVV) { |
10482 | const VectorType *VecType = SecondType->getAs<VectorType>(); |
10483 | SVEorRVV = 0; |
10484 | if (FirstType->isSizelessBuiltinType() && VecType) { |
10485 | if (VecType->getVectorKind() == VectorKind::SveFixedLengthData || |
10486 | VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate) |
10487 | return true; |
10488 | if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
10489 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask || |
10490 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 || |
10491 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 || |
10492 | VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) { |
10493 | SVEorRVV = 1; |
10494 | return true; |
10495 | } |
10496 | } |
10497 | |
10498 | return false; |
10499 | }; |
10500 | |
10501 | unsigned SVEorRVV; |
10502 | if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) || |
10503 | IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) { |
10504 | Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous) |
10505 | << SVEorRVV << LHSType << RHSType; |
10506 | return QualType(); |
10507 | } |
10508 | |
10509 | // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are |
10510 | // invalid since the ambiguity can affect the ABI. |
10511 | auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType, |
10512 | unsigned &SVEorRVV) { |
10513 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); |
10514 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); |
10515 | |
10516 | SVEorRVV = 0; |
10517 | if (FirstVecType && SecondVecType) { |
10518 | if (FirstVecType->getVectorKind() == VectorKind::Generic) { |
10519 | if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData || |
10520 | SecondVecType->getVectorKind() == |
10521 | VectorKind::SveFixedLengthPredicate) |
10522 | return true; |
10523 | if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData || |
10524 | SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask || |
10525 | SecondVecType->getVectorKind() == |
10526 | VectorKind::RVVFixedLengthMask_1 || |
10527 | SecondVecType->getVectorKind() == |
10528 | VectorKind::RVVFixedLengthMask_2 || |
10529 | SecondVecType->getVectorKind() == |
10530 | VectorKind::RVVFixedLengthMask_4) { |
10531 | SVEorRVV = 1; |
10532 | return true; |
10533 | } |
10534 | } |
10535 | return false; |
10536 | } |
10537 | |
10538 | if (SecondVecType && |
10539 | SecondVecType->getVectorKind() == VectorKind::Generic) { |
10540 | if (FirstType->isSVESizelessBuiltinType()) |
10541 | return true; |
10542 | if (FirstType->isRVVSizelessBuiltinType()) { |
10543 | SVEorRVV = 1; |
10544 | return true; |
10545 | } |
10546 | } |
10547 | |
10548 | return false; |
10549 | }; |
10550 | |
10551 | if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) || |
10552 | IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) { |
10553 | Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous) |
10554 | << SVEorRVV << LHSType << RHSType; |
10555 | return QualType(); |
10556 | } |
10557 | |
10558 | // If there's a vector type and a scalar, try to convert the scalar to |
10559 | // the vector element type and splat. |
10560 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; |
10561 | if (!RHSVecType) { |
10562 | if (isa<ExtVectorType>(Val: LHSVecType)) { |
10563 | if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType, |
10564 | vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType, |
10565 | DiagID)) |
10566 | return LHSType; |
10567 | } else { |
10568 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
10569 | return LHSType; |
10570 | } |
10571 | } |
10572 | if (!LHSVecType) { |
10573 | if (isa<ExtVectorType>(Val: RHSVecType)) { |
10574 | if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS), |
10575 | scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(), |
10576 | vectorTy: RHSType, DiagID)) |
10577 | return RHSType; |
10578 | } else { |
10579 | if (LHS.get()->isLValue() || |
10580 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
10581 | return RHSType; |
10582 | } |
10583 | } |
10584 | |
10585 | // FIXME: The code below also handles conversion between vectors and |
10586 | // non-scalars, we should break this down into fine grained specific checks |
10587 | // and emit proper diagnostics. |
10588 | QualType VecType = LHSVecType ? LHSType : RHSType; |
10589 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; |
10590 | QualType OtherType = LHSVecType ? RHSType : LHSType; |
10591 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; |
10592 | if (isLaxVectorConversion(srcTy: OtherType, destTy: VecType)) { |
10593 | if (Context.getTargetInfo().getTriple().isPPC() && |
10594 | anyAltivecTypes(RHSType, LHSType) && |
10595 | !Context.areCompatibleVectorTypes(RHSType, LHSType)) |
10596 | Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; |
10597 | // If we're allowing lax vector conversions, only the total (data) size |
10598 | // needs to be the same. For non compound assignment, if one of the types is |
10599 | // scalar, the result is always the vector type. |
10600 | if (!IsCompAssign) { |
10601 | *OtherExpr = ImpCastExprToType(E: OtherExpr->get(), Type: VecType, CK: CK_BitCast); |
10602 | return VecType; |
10603 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding |
10604 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' |
10605 | // type. Note that this is already done by non-compound assignments in |
10606 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for |
10607 | // <1 x T> -> T. The result is also a vector type. |
10608 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || |
10609 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { |
10610 | ExprResult *RHSExpr = &RHS; |
10611 | *RHSExpr = ImpCastExprToType(E: RHSExpr->get(), Type: LHSType, CK: CK_BitCast); |
10612 | return VecType; |
10613 | } |
10614 | } |
10615 | |
10616 | // Okay, the expression is invalid. |
10617 | |
10618 | // If there's a non-vector, non-real operand, diagnose that. |
10619 | if ((!RHSVecType && !RHSType->isRealType()) || |
10620 | (!LHSVecType && !LHSType->isRealType())) { |
10621 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) |
10622 | << LHSType << RHSType |
10623 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10624 | return QualType(); |
10625 | } |
10626 | |
10627 | // OpenCL V1.1 6.2.6.p1: |
10628 | // If the operands are of more than one vector type, then an error shall |
10629 | // occur. Implicit conversions between vector types are not permitted, per |
10630 | // section 6.2.1. |
10631 | if (getLangOpts().OpenCL && |
10632 | RHSVecType && isa<ExtVectorType>(Val: RHSVecType) && |
10633 | LHSVecType && isa<ExtVectorType>(Val: LHSVecType)) { |
10634 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType |
10635 | << RHSType; |
10636 | return QualType(); |
10637 | } |
10638 | |
10639 | |
10640 | // If there is a vector type that is not a ExtVector and a scalar, we reach |
10641 | // this point if scalar could not be converted to the vector's element type |
10642 | // without truncation. |
10643 | if ((RHSVecType && !isa<ExtVectorType>(Val: RHSVecType)) || |
10644 | (LHSVecType && !isa<ExtVectorType>(Val: LHSVecType))) { |
10645 | QualType Scalar = LHSVecType ? RHSType : LHSType; |
10646 | QualType Vector = LHSVecType ? LHSType : RHSType; |
10647 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; |
10648 | Diag(Loc, |
10649 | diag::err_typecheck_vector_not_convertable_implict_truncation) |
10650 | << ScalarOrVector << Scalar << Vector; |
10651 | |
10652 | return QualType(); |
10653 | } |
10654 | |
10655 | // Otherwise, use the generic diagnostic. |
10656 | Diag(Loc, DiagID) |
10657 | << LHSType << RHSType |
10658 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10659 | return QualType(); |
10660 | } |
10661 | |
10662 | QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, |
10663 | SourceLocation Loc, |
10664 | bool IsCompAssign, |
10665 | ArithConvKind OperationKind) { |
10666 | if (!IsCompAssign) { |
10667 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
10668 | if (LHS.isInvalid()) |
10669 | return QualType(); |
10670 | } |
10671 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
10672 | if (RHS.isInvalid()) |
10673 | return QualType(); |
10674 | |
10675 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
10676 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
10677 | |
10678 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
10679 | const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); |
10680 | |
10681 | unsigned DiagID = diag::err_typecheck_invalid_operands; |
10682 | if ((OperationKind == ArithConvKind::Arithmetic) && |
10683 | ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
10684 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { |
10685 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
10686 | << RHS.get()->getSourceRange(); |
10687 | return QualType(); |
10688 | } |
10689 | |
10690 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
10691 | return LHSType; |
10692 | |
10693 | if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) { |
10694 | if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS)) |
10695 | return LHSType; |
10696 | } |
10697 | if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) { |
10698 | if (LHS.get()->isLValue() || |
10699 | !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &RHS)) |
10700 | return RHSType; |
10701 | } |
10702 | |
10703 | if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) || |
10704 | (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) { |
10705 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) |
10706 | << LHSType << RHSType << LHS.get()->getSourceRange() |
10707 | << RHS.get()->getSourceRange(); |
10708 | return QualType(); |
10709 | } |
10710 | |
10711 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
10712 | Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
10713 | Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC) { |
10714 | Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) |
10715 | << LHSType << RHSType << LHS.get()->getSourceRange() |
10716 | << RHS.get()->getSourceRange(); |
10717 | return QualType(); |
10718 | } |
10719 | |
10720 | if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) { |
10721 | QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType; |
10722 | QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType; |
10723 | bool ScalarOrVector = |
10724 | LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType(); |
10725 | |
10726 | Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) |
10727 | << ScalarOrVector << Scalar << Vector; |
10728 | |
10729 | return QualType(); |
10730 | } |
10731 | |
10732 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
10733 | << RHS.get()->getSourceRange(); |
10734 | return QualType(); |
10735 | } |
10736 | |
10737 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an |
10738 | // expression. These are mainly cases where the null pointer is used as an |
10739 | // integer instead of a pointer. |
10740 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, |
10741 | SourceLocation Loc, bool IsCompare) { |
10742 | // The canonical way to check for a GNU null is with isNullPointerConstant, |
10743 | // but we use a bit of a hack here for speed; this is a relatively |
10744 | // hot path, and isNullPointerConstant is slow. |
10745 | bool LHSNull = isa<GNUNullExpr>(Val: LHS.get()->IgnoreParenImpCasts()); |
10746 | bool RHSNull = isa<GNUNullExpr>(Val: RHS.get()->IgnoreParenImpCasts()); |
10747 | |
10748 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); |
10749 | |
10750 | // Avoid analyzing cases where the result will either be invalid (and |
10751 | // diagnosed as such) or entirely valid and not something to warn about. |
10752 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || |
10753 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) |
10754 | return; |
10755 | |
10756 | // Comparison operations would not make sense with a null pointer no matter |
10757 | // what the other expression is. |
10758 | if (!IsCompare) { |
10759 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) |
10760 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) |
10761 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); |
10762 | return; |
10763 | } |
10764 | |
10765 | // The rest of the operations only make sense with a null pointer |
10766 | // if the other expression is a pointer. |
10767 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || |
10768 | NonNullType->canDecayToPointerType()) |
10769 | return; |
10770 | |
10771 | S.Diag(Loc, diag::warn_null_in_comparison_operation) |
10772 | << LHSNull /* LHS is NULL */ << NonNullType |
10773 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
10774 | } |
10775 | |
10776 | static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, |
10777 | SourceLocation OpLoc) { |
10778 | // If the divisor is real, then this is real/real or complex/real division. |
10779 | // Either way there can be no precision loss. |
10780 | auto *CT = DivisorTy->getAs<ComplexType>(); |
10781 | if (!CT) |
10782 | return; |
10783 | |
10784 | QualType ElementType = CT->getElementType(); |
10785 | bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() == |
10786 | LangOptions::ComplexRangeKind::CX_Promoted; |
10787 | if (!ElementType->isFloatingType() || !IsComplexRangePromoted) |
10788 | return; |
10789 | |
10790 | ASTContext &Ctx = S.getASTContext(); |
10791 | QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType); |
10792 | const llvm::fltSemantics &ElementTypeSemantics = |
10793 | Ctx.getFloatTypeSemantics(T: ElementType); |
10794 | const llvm::fltSemantics &HigherElementTypeSemantics = |
10795 | Ctx.getFloatTypeSemantics(T: HigherElementType); |
10796 | |
10797 | if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 > |
10798 | llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) || |
10799 | (HigherElementType == Ctx.LongDoubleTy && |
10800 | !Ctx.getTargetInfo().hasLongDoubleType())) { |
10801 | // Retain the location of the first use of higher precision type. |
10802 | if (!S.LocationOfExcessPrecisionNotSatisfied.isValid()) |
10803 | S.LocationOfExcessPrecisionNotSatisfied = OpLoc; |
10804 | for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) { |
10805 | if (Type == HigherElementType) { |
10806 | Num++; |
10807 | return; |
10808 | } |
10809 | } |
10810 | S.ExcessPrecisionNotSatisfied.push_back(std::make_pair( |
10811 | x&: HigherElementType, y: S.ExcessPrecisionNotSatisfied.size())); |
10812 | } |
10813 | } |
10814 | |
10815 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, |
10816 | SourceLocation Loc) { |
10817 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS); |
10818 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: RHS); |
10819 | if (!LUE || !RUE) |
10820 | return; |
10821 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || |
10822 | RUE->getKind() != UETT_SizeOf) |
10823 | return; |
10824 | |
10825 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); |
10826 | QualType LHSTy = LHSArg->getType(); |
10827 | QualType RHSTy; |
10828 | |
10829 | if (RUE->isArgumentType()) |
10830 | RHSTy = RUE->getArgumentType().getNonReferenceType(); |
10831 | else |
10832 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); |
10833 | |
10834 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { |
10835 | if (!S.Context.hasSameUnqualifiedType(T1: LHSTy->getPointeeType(), T2: RHSTy)) |
10836 | return; |
10837 | |
10838 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); |
10839 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
10840 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
10841 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) |
10842 | << LHSArgDecl; |
10843 | } |
10844 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(T: LHSTy)) { |
10845 | QualType ArrayElemTy = ArrayTy->getElementType(); |
10846 | if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) || |
10847 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || |
10848 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || |
10849 | S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: RHSTy)) |
10850 | return; |
10851 | S.Diag(Loc, diag::warn_division_sizeof_array) |
10852 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; |
10853 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHSArg)) { |
10854 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) |
10855 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) |
10856 | << LHSArgDecl; |
10857 | } |
10858 | |
10859 | S.Diag(Loc, diag::note_precedence_silence) << RHS; |
10860 | } |
10861 | } |
10862 | |
10863 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, |
10864 | ExprResult &RHS, |
10865 | SourceLocation Loc, bool IsDiv) { |
10866 | // Check for division/remainder by zero. |
10867 | Expr::EvalResult RHSValue; |
10868 | if (!RHS.get()->isValueDependent() && |
10869 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && |
10870 | RHSValue.Val.getInt() == 0) |
10871 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
10872 | S.PDiag(diag::warn_remainder_division_by_zero) |
10873 | << IsDiv << RHS.get()->getSourceRange()); |
10874 | } |
10875 | |
10876 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, |
10877 | SourceLocation Loc, |
10878 | bool IsCompAssign, bool IsDiv) { |
10879 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10880 | |
10881 | QualType LHSTy = LHS.get()->getType(); |
10882 | QualType RHSTy = RHS.get()->getType(); |
10883 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) |
10884 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10885 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10886 | /*AllowBoolConversions*/ false, |
10887 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10888 | /*ReportInvalid*/ true); |
10889 | if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType()) |
10890 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10891 | OperationKind: ArithConvKind::Arithmetic); |
10892 | if (!IsDiv && |
10893 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) |
10894 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); |
10895 | // For division, only matrix-by-scalar is supported. Other combinations with |
10896 | // matrix types are invalid. |
10897 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) |
10898 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
10899 | |
10900 | QualType compType = UsualArithmeticConversions( |
10901 | LHS, RHS, Loc, |
10902 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
10903 | if (LHS.isInvalid() || RHS.isInvalid()) |
10904 | return QualType(); |
10905 | |
10906 | |
10907 | if (compType.isNull() || !compType->isArithmeticType()) |
10908 | return InvalidOperands(Loc, LHS, RHS); |
10909 | if (IsDiv) { |
10910 | DetectPrecisionLossInComplexDivision(S&: *this, DivisorTy: RHS.get()->getType(), OpLoc: Loc); |
10911 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv); |
10912 | DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc); |
10913 | } |
10914 | return compType; |
10915 | } |
10916 | |
10917 | QualType Sema::CheckRemainderOperands( |
10918 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { |
10919 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
10920 | |
10921 | // Note: This check is here to simplify the double exclusions of |
10922 | // scalar and vector HLSL checks. No getLangOpts().HLSL |
10923 | // is needed since all languages exlcude doubles. |
10924 | if (LHS.get()->getType()->isDoubleType() || |
10925 | RHS.get()->getType()->isDoubleType() || |
10926 | (LHS.get()->getType()->isVectorType() && LHS.get() |
10927 | ->getType() |
10928 | ->getAs<VectorType>() |
10929 | ->getElementType() |
10930 | ->isDoubleType()) || |
10931 | (RHS.get()->getType()->isVectorType() && RHS.get() |
10932 | ->getType() |
10933 | ->getAs<VectorType>() |
10934 | ->getElementType() |
10935 | ->isDoubleType())) |
10936 | return InvalidOperands(Loc, LHS, RHS); |
10937 | |
10938 | if (LHS.get()->getType()->isVectorType() || |
10939 | RHS.get()->getType()->isVectorType()) { |
10940 | if ((LHS.get()->getType()->hasIntegerRepresentation() && |
10941 | RHS.get()->getType()->hasIntegerRepresentation()) || |
10942 | (getLangOpts().HLSL && |
10943 | (LHS.get()->getType()->hasFloatingRepresentation() || |
10944 | RHS.get()->getType()->hasFloatingRepresentation()))) |
10945 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10946 | /*AllowBothBool*/ getLangOpts().AltiVec, |
10947 | /*AllowBoolConversions*/ false, |
10948 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
10949 | /*ReportInvalid*/ true); |
10950 | return InvalidOperands(Loc, LHS, RHS); |
10951 | } |
10952 | |
10953 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
10954 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
10955 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
10956 | RHS.get()->getType()->hasIntegerRepresentation()) |
10957 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
10958 | OperationKind: ArithConvKind::Arithmetic); |
10959 | |
10960 | return InvalidOperands(Loc, LHS, RHS); |
10961 | } |
10962 | |
10963 | QualType compType = UsualArithmeticConversions( |
10964 | LHS, RHS, Loc, |
10965 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
10966 | if (LHS.isInvalid() || RHS.isInvalid()) |
10967 | return QualType(); |
10968 | |
10969 | if (compType.isNull() || |
10970 | (!compType->isIntegerType() && |
10971 | !(getLangOpts().HLSL && compType->isFloatingType()))) |
10972 | return InvalidOperands(Loc, LHS, RHS); |
10973 | DiagnoseBadDivideOrRemainderValues(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */); |
10974 | return compType; |
10975 | } |
10976 | |
10977 | /// Diagnose invalid arithmetic on two void pointers. |
10978 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, |
10979 | Expr *LHSExpr, Expr *RHSExpr) { |
10980 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
10981 | ? diag::err_typecheck_pointer_arith_void_type |
10982 | : diag::ext_gnu_void_ptr) |
10983 | << 1 /* two pointers */ << LHSExpr->getSourceRange() |
10984 | << RHSExpr->getSourceRange(); |
10985 | } |
10986 | |
10987 | /// Diagnose invalid arithmetic on a void pointer. |
10988 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, |
10989 | Expr *Pointer) { |
10990 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
10991 | ? diag::err_typecheck_pointer_arith_void_type |
10992 | : diag::ext_gnu_void_ptr) |
10993 | << 0 /* one pointer */ << Pointer->getSourceRange(); |
10994 | } |
10995 | |
10996 | /// Diagnose invalid arithmetic on a null pointer. |
10997 | /// |
10998 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' |
10999 | /// idiom, which we recognize as a GNU extension. |
11000 | /// |
11001 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, |
11002 | Expr *Pointer, bool IsGNUIdiom) { |
11003 | if (IsGNUIdiom) |
11004 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) |
11005 | << Pointer->getSourceRange(); |
11006 | else |
11007 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) |
11008 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); |
11009 | } |
11010 | |
11011 | /// Diagnose invalid subraction on a null pointer. |
11012 | /// |
11013 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, |
11014 | Expr *Pointer, bool BothNull) { |
11015 | // Null - null is valid in C++ [expr.add]p7 |
11016 | if (BothNull && S.getLangOpts().CPlusPlus) |
11017 | return; |
11018 | |
11019 | // Is this s a macro from a system header? |
11020 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc)) |
11021 | return; |
11022 | |
11023 | S.DiagRuntimeBehavior(Loc, Pointer, |
11024 | S.PDiag(diag::warn_pointer_sub_null_ptr) |
11025 | << S.getLangOpts().CPlusPlus |
11026 | << Pointer->getSourceRange()); |
11027 | } |
11028 | |
11029 | /// Diagnose invalid arithmetic on two function pointers. |
11030 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, |
11031 | Expr *LHS, Expr *RHS) { |
11032 | assert(LHS->getType()->isAnyPointerType()); |
11033 | assert(RHS->getType()->isAnyPointerType()); |
11034 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
11035 | ? diag::err_typecheck_pointer_arith_function_type |
11036 | : diag::ext_gnu_ptr_func_arith) |
11037 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() |
11038 | // We only show the second type if it differs from the first. |
11039 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), |
11040 | RHS->getType()) |
11041 | << RHS->getType()->getPointeeType() |
11042 | << LHS->getSourceRange() << RHS->getSourceRange(); |
11043 | } |
11044 | |
11045 | /// Diagnose invalid arithmetic on a function pointer. |
11046 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, |
11047 | Expr *Pointer) { |
11048 | assert(Pointer->getType()->isAnyPointerType()); |
11049 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
11050 | ? diag::err_typecheck_pointer_arith_function_type |
11051 | : diag::ext_gnu_ptr_func_arith) |
11052 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() |
11053 | << 0 /* one pointer, so only one type */ |
11054 | << Pointer->getSourceRange(); |
11055 | } |
11056 | |
11057 | /// Emit error if Operand is incomplete pointer type |
11058 | /// |
11059 | /// \returns True if pointer has incomplete type |
11060 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, |
11061 | Expr *Operand) { |
11062 | QualType ResType = Operand->getType(); |
11063 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
11064 | ResType = ResAtomicType->getValueType(); |
11065 | |
11066 | assert(ResType->isAnyPointerType()); |
11067 | QualType PointeeTy = ResType->getPointeeType(); |
11068 | return S.RequireCompleteSizedType( |
11069 | Loc, PointeeTy, |
11070 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, |
11071 | Operand->getSourceRange()); |
11072 | } |
11073 | |
11074 | /// Check the validity of an arithmetic pointer operand. |
11075 | /// |
11076 | /// If the operand has pointer type, this code will check for pointer types |
11077 | /// which are invalid in arithmetic operations. These will be diagnosed |
11078 | /// appropriately, including whether or not the use is supported as an |
11079 | /// extension. |
11080 | /// |
11081 | /// \returns True when the operand is valid to use (even if as an extension). |
11082 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, |
11083 | Expr *Operand) { |
11084 | QualType ResType = Operand->getType(); |
11085 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
11086 | ResType = ResAtomicType->getValueType(); |
11087 | |
11088 | if (!ResType->isAnyPointerType()) return true; |
11089 | |
11090 | QualType PointeeTy = ResType->getPointeeType(); |
11091 | if (PointeeTy->isVoidType()) { |
11092 | diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: Operand); |
11093 | return !S.getLangOpts().CPlusPlus; |
11094 | } |
11095 | if (PointeeTy->isFunctionType()) { |
11096 | diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: Operand); |
11097 | return !S.getLangOpts().CPlusPlus; |
11098 | } |
11099 | |
11100 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; |
11101 | |
11102 | return true; |
11103 | } |
11104 | |
11105 | /// Check the validity of a binary arithmetic operation w.r.t. pointer |
11106 | /// operands. |
11107 | /// |
11108 | /// This routine will diagnose any invalid arithmetic on pointer operands much |
11109 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic |
11110 | /// for emitting a single diagnostic even for operations where both LHS and RHS |
11111 | /// are (potentially problematic) pointers. |
11112 | /// |
11113 | /// \returns True when the operand is valid to use (even if as an extension). |
11114 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, |
11115 | Expr *LHSExpr, Expr *RHSExpr) { |
11116 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); |
11117 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); |
11118 | if (!isLHSPointer && !isRHSPointer) return true; |
11119 | |
11120 | QualType LHSPointeeTy, RHSPointeeTy; |
11121 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); |
11122 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); |
11123 | |
11124 | // if both are pointers check if operation is valid wrt address spaces |
11125 | if (isLHSPointer && isRHSPointer) { |
11126 | if (!LHSPointeeTy.isAddressSpaceOverlapping(T: RHSPointeeTy, |
11127 | Ctx: S.getASTContext())) { |
11128 | S.Diag(Loc, |
11129 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
11130 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ |
11131 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); |
11132 | return false; |
11133 | } |
11134 | } |
11135 | |
11136 | // Check for arithmetic on pointers to incomplete types. |
11137 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); |
11138 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); |
11139 | if (isLHSVoidPtr || isRHSVoidPtr) { |
11140 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: LHSExpr); |
11141 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: RHSExpr); |
11142 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); |
11143 | |
11144 | return !S.getLangOpts().CPlusPlus; |
11145 | } |
11146 | |
11147 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); |
11148 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); |
11149 | if (isLHSFuncPtr || isRHSFuncPtr) { |
11150 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: LHSExpr); |
11151 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, |
11152 | Pointer: RHSExpr); |
11153 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr); |
11154 | |
11155 | return !S.getLangOpts().CPlusPlus; |
11156 | } |
11157 | |
11158 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr)) |
11159 | return false; |
11160 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr)) |
11161 | return false; |
11162 | |
11163 | return true; |
11164 | } |
11165 | |
11166 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string |
11167 | /// literal. |
11168 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, |
11169 | Expr *LHSExpr, Expr *RHSExpr) { |
11170 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
11171 | Expr* IndexExpr = RHSExpr; |
11172 | if (!StrExpr) { |
11173 | StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
11174 | IndexExpr = LHSExpr; |
11175 | } |
11176 | |
11177 | bool IsStringPlusInt = StrExpr && |
11178 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); |
11179 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) |
11180 | return; |
11181 | |
11182 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
11183 | Self.Diag(OpLoc, diag::warn_string_plus_int) |
11184 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); |
11185 | |
11186 | // Only print a fixit for "str" + int, not for int + "str". |
11187 | if (IndexExpr == RHSExpr) { |
11188 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
11189 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) |
11190 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") |
11191 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") |
11192 | << FixItHint::CreateInsertion(EndLoc, "]"); |
11193 | } else |
11194 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); |
11195 | } |
11196 | |
11197 | /// Emit a warning when adding a char literal to a string. |
11198 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, |
11199 | Expr *LHSExpr, Expr *RHSExpr) { |
11200 | const Expr *StringRefExpr = LHSExpr; |
11201 | const CharacterLiteral *CharExpr = |
11202 | dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts()); |
11203 | |
11204 | if (!CharExpr) { |
11205 | CharExpr = dyn_cast<CharacterLiteral>(Val: LHSExpr->IgnoreImpCasts()); |
11206 | StringRefExpr = RHSExpr; |
11207 | } |
11208 | |
11209 | if (!CharExpr || !StringRefExpr) |
11210 | return; |
11211 | |
11212 | const QualType StringType = StringRefExpr->getType(); |
11213 | |
11214 | // Return if not a PointerType. |
11215 | if (!StringType->isAnyPointerType()) |
11216 | return; |
11217 | |
11218 | // Return if not a CharacterType. |
11219 | if (!StringType->getPointeeType()->isAnyCharacterType()) |
11220 | return; |
11221 | |
11222 | ASTContext &Ctx = Self.getASTContext(); |
11223 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
11224 | |
11225 | const QualType CharType = CharExpr->getType(); |
11226 | if (!CharType->isAnyCharacterType() && |
11227 | CharType->isIntegerType() && |
11228 | llvm::isUIntN(N: Ctx.getCharWidth(), x: CharExpr->getValue())) { |
11229 | Self.Diag(OpLoc, diag::warn_string_plus_char) |
11230 | << DiagRange << Ctx.CharTy; |
11231 | } else { |
11232 | Self.Diag(OpLoc, diag::warn_string_plus_char) |
11233 | << DiagRange << CharExpr->getType(); |
11234 | } |
11235 | |
11236 | // Only print a fixit for str + char, not for char + str. |
11237 | if (isa<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts())) { |
11238 | SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc()); |
11239 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) |
11240 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") |
11241 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") |
11242 | << FixItHint::CreateInsertion(EndLoc, "]"); |
11243 | } else { |
11244 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); |
11245 | } |
11246 | } |
11247 | |
11248 | /// Emit error when two pointers are incompatible. |
11249 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, |
11250 | Expr *LHSExpr, Expr *RHSExpr) { |
11251 | assert(LHSExpr->getType()->isAnyPointerType()); |
11252 | assert(RHSExpr->getType()->isAnyPointerType()); |
11253 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) |
11254 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() |
11255 | << RHSExpr->getSourceRange(); |
11256 | } |
11257 | |
11258 | // C99 6.5.6 |
11259 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, |
11260 | SourceLocation Loc, BinaryOperatorKind Opc, |
11261 | QualType* CompLHSTy) { |
11262 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
11263 | |
11264 | if (LHS.get()->getType()->isVectorType() || |
11265 | RHS.get()->getType()->isVectorType()) { |
11266 | QualType compType = |
11267 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
11268 | /*AllowBothBool*/ getLangOpts().AltiVec, |
11269 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
11270 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
11271 | /*ReportInvalid*/ true); |
11272 | if (CompLHSTy) *CompLHSTy = compType; |
11273 | return compType; |
11274 | } |
11275 | |
11276 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
11277 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
11278 | QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
11279 | OperationKind: ArithConvKind::Arithmetic); |
11280 | if (CompLHSTy) |
11281 | *CompLHSTy = compType; |
11282 | return compType; |
11283 | } |
11284 | |
11285 | if (LHS.get()->getType()->isConstantMatrixType() || |
11286 | RHS.get()->getType()->isConstantMatrixType()) { |
11287 | QualType compType = |
11288 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
11289 | if (CompLHSTy) |
11290 | *CompLHSTy = compType; |
11291 | return compType; |
11292 | } |
11293 | |
11294 | QualType compType = UsualArithmeticConversions( |
11295 | LHS, RHS, Loc, |
11296 | ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
11297 | if (LHS.isInvalid() || RHS.isInvalid()) |
11298 | return QualType(); |
11299 | |
11300 | // Diagnose "string literal" '+' int and string '+' "char literal". |
11301 | if (Opc == BO_Add) { |
11302 | diagnoseStringPlusInt(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11303 | diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11304 | } |
11305 | |
11306 | // handle the common case first (both operands are arithmetic). |
11307 | if (!compType.isNull() && compType->isArithmeticType()) { |
11308 | if (CompLHSTy) *CompLHSTy = compType; |
11309 | return compType; |
11310 | } |
11311 | |
11312 | // Type-checking. Ultimately the pointer's going to be in PExp; |
11313 | // note that we bias towards the LHS being the pointer. |
11314 | Expr *PExp = LHS.get(), *IExp = RHS.get(); |
11315 | |
11316 | bool isObjCPointer; |
11317 | if (PExp->getType()->isPointerType()) { |
11318 | isObjCPointer = false; |
11319 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
11320 | isObjCPointer = true; |
11321 | } else { |
11322 | std::swap(a&: PExp, b&: IExp); |
11323 | if (PExp->getType()->isPointerType()) { |
11324 | isObjCPointer = false; |
11325 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
11326 | isObjCPointer = true; |
11327 | } else { |
11328 | return InvalidOperands(Loc, LHS, RHS); |
11329 | } |
11330 | } |
11331 | assert(PExp->getType()->isAnyPointerType()); |
11332 | |
11333 | if (!IExp->getType()->isIntegerType()) |
11334 | return InvalidOperands(Loc, LHS, RHS); |
11335 | |
11336 | // Adding to a null pointer results in undefined behavior. |
11337 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( |
11338 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
11339 | // In C++ adding zero to a null pointer is defined. |
11340 | Expr::EvalResult KnownVal; |
11341 | if (!getLangOpts().CPlusPlus || |
11342 | (!IExp->isValueDependent() && |
11343 | (!IExp->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
11344 | KnownVal.Val.getInt() != 0))) { |
11345 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. |
11346 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( |
11347 | Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp); |
11348 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom); |
11349 | } |
11350 | } |
11351 | |
11352 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp)) |
11353 | return QualType(); |
11354 | |
11355 | if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp)) |
11356 | return QualType(); |
11357 | |
11358 | // Arithmetic on label addresses is normally allowed, except when we add |
11359 | // a ptrauth signature to the addresses. |
11360 | if (isa<AddrLabelExpr>(Val: PExp) && getLangOpts().PointerAuthIndirectGotos) { |
11361 | Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
11362 | << /*addition*/ 1; |
11363 | return QualType(); |
11364 | } |
11365 | |
11366 | // Check array bounds for pointer arithemtic |
11367 | CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp); |
11368 | |
11369 | if (CompLHSTy) { |
11370 | QualType LHSTy = Context.isPromotableBitField(E: LHS.get()); |
11371 | if (LHSTy.isNull()) { |
11372 | LHSTy = LHS.get()->getType(); |
11373 | if (Context.isPromotableIntegerType(T: LHSTy)) |
11374 | LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy); |
11375 | } |
11376 | *CompLHSTy = LHSTy; |
11377 | } |
11378 | |
11379 | return PExp->getType(); |
11380 | } |
11381 | |
11382 | // C99 6.5.6 |
11383 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, |
11384 | SourceLocation Loc, |
11385 | QualType* CompLHSTy) { |
11386 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
11387 | |
11388 | if (LHS.get()->getType()->isVectorType() || |
11389 | RHS.get()->getType()->isVectorType()) { |
11390 | QualType compType = |
11391 | CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
11392 | /*AllowBothBool*/ getLangOpts().AltiVec, |
11393 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
11394 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
11395 | /*ReportInvalid*/ true); |
11396 | if (CompLHSTy) *CompLHSTy = compType; |
11397 | return compType; |
11398 | } |
11399 | |
11400 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
11401 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
11402 | QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy, |
11403 | OperationKind: ArithConvKind::Arithmetic); |
11404 | if (CompLHSTy) |
11405 | *CompLHSTy = compType; |
11406 | return compType; |
11407 | } |
11408 | |
11409 | if (LHS.get()->getType()->isConstantMatrixType() || |
11410 | RHS.get()->getType()->isConstantMatrixType()) { |
11411 | QualType compType = |
11412 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign: CompLHSTy); |
11413 | if (CompLHSTy) |
11414 | *CompLHSTy = compType; |
11415 | return compType; |
11416 | } |
11417 | |
11418 | QualType compType = UsualArithmeticConversions( |
11419 | LHS, RHS, Loc, |
11420 | ACK: CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic); |
11421 | if (LHS.isInvalid() || RHS.isInvalid()) |
11422 | return QualType(); |
11423 | |
11424 | // Enforce type constraints: C99 6.5.6p3. |
11425 | |
11426 | // Handle the common case first (both operands are arithmetic). |
11427 | if (!compType.isNull() && compType->isArithmeticType()) { |
11428 | if (CompLHSTy) *CompLHSTy = compType; |
11429 | return compType; |
11430 | } |
11431 | |
11432 | // Either ptr - int or ptr - ptr. |
11433 | if (LHS.get()->getType()->isAnyPointerType()) { |
11434 | QualType lpointee = LHS.get()->getType()->getPointeeType(); |
11435 | |
11436 | // Diagnose bad cases where we step over interface counts. |
11437 | if (LHS.get()->getType()->isObjCObjectPointerType() && |
11438 | checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: LHS.get())) |
11439 | return QualType(); |
11440 | |
11441 | // Arithmetic on label addresses is normally allowed, except when we add |
11442 | // a ptrauth signature to the addresses. |
11443 | if (isa<AddrLabelExpr>(Val: LHS.get()) && |
11444 | getLangOpts().PointerAuthIndirectGotos) { |
11445 | Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic) |
11446 | << /*subtraction*/ 0; |
11447 | return QualType(); |
11448 | } |
11449 | |
11450 | // The result type of a pointer-int computation is the pointer type. |
11451 | if (RHS.get()->getType()->isIntegerType()) { |
11452 | // Subtracting from a null pointer should produce a warning. |
11453 | // The last argument to the diagnose call says this doesn't match the |
11454 | // GNU int-to-pointer idiom. |
11455 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context, |
11456 | NPC: Expr::NPC_ValueDependentIsNotNull)) { |
11457 | // In C++ adding zero to a null pointer is defined. |
11458 | Expr::EvalResult KnownVal; |
11459 | if (!getLangOpts().CPlusPlus || |
11460 | (!RHS.get()->isValueDependent() && |
11461 | (!RHS.get()->EvaluateAsInt(Result&: KnownVal, Ctx: Context) || |
11462 | KnownVal.Val.getInt() != 0))) { |
11463 | diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false); |
11464 | } |
11465 | } |
11466 | |
11467 | if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get())) |
11468 | return QualType(); |
11469 | |
11470 | // Check array bounds for pointer arithemtic |
11471 | CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: nullptr, |
11472 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); |
11473 | |
11474 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
11475 | return LHS.get()->getType(); |
11476 | } |
11477 | |
11478 | // Handle pointer-pointer subtractions. |
11479 | if (const PointerType *RHSPTy |
11480 | = RHS.get()->getType()->getAs<PointerType>()) { |
11481 | QualType rpointee = RHSPTy->getPointeeType(); |
11482 | |
11483 | if (getLangOpts().CPlusPlus) { |
11484 | // Pointee types must be the same: C++ [expr.add] |
11485 | if (!Context.hasSameUnqualifiedType(T1: lpointee, T2: rpointee)) { |
11486 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11487 | } |
11488 | } else { |
11489 | // Pointee types must be compatible C99 6.5.6p3 |
11490 | if (!Context.typesAreCompatible( |
11491 | T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(), |
11492 | T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) { |
11493 | diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
11494 | return QualType(); |
11495 | } |
11496 | } |
11497 | |
11498 | if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc, |
11499 | LHSExpr: LHS.get(), RHSExpr: RHS.get())) |
11500 | return QualType(); |
11501 | |
11502 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
11503 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
11504 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( |
11505 | Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull); |
11506 | |
11507 | // Subtracting nullptr or from nullptr is suspect |
11508 | if (LHSIsNullPtr) |
11509 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr); |
11510 | if (RHSIsNullPtr) |
11511 | diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: LHSIsNullPtr); |
11512 | |
11513 | // The pointee type may have zero size. As an extension, a structure or |
11514 | // union may have zero size or an array may have zero length. In this |
11515 | // case subtraction does not make sense. |
11516 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { |
11517 | CharUnits ElementSize = Context.getTypeSizeInChars(T: rpointee); |
11518 | if (ElementSize.isZero()) { |
11519 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) |
11520 | << rpointee.getUnqualifiedType() |
11521 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11522 | } |
11523 | } |
11524 | |
11525 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
11526 | return Context.getPointerDiffType(); |
11527 | } |
11528 | } |
11529 | |
11530 | return InvalidOperands(Loc, LHS, RHS); |
11531 | } |
11532 | |
11533 | static bool isScopedEnumerationType(QualType T) { |
11534 | if (const EnumType *ET = T->getAs<EnumType>()) |
11535 | return ET->getDecl()->isScoped(); |
11536 | return false; |
11537 | } |
11538 | |
11539 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, |
11540 | SourceLocation Loc, BinaryOperatorKind Opc, |
11541 | QualType LHSType) { |
11542 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), |
11543 | // so skip remaining warnings as we don't want to modify values within Sema. |
11544 | if (S.getLangOpts().OpenCL) |
11545 | return; |
11546 | |
11547 | if (Opc == BO_Shr && |
11548 | LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType()) |
11549 | S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange(); |
11550 | |
11551 | // Check right/shifter operand |
11552 | Expr::EvalResult RHSResult; |
11553 | if (RHS.get()->isValueDependent() || |
11554 | !RHS.get()->EvaluateAsInt(Result&: RHSResult, Ctx: S.Context)) |
11555 | return; |
11556 | llvm::APSInt Right = RHSResult.Val.getInt(); |
11557 | |
11558 | if (Right.isNegative()) { |
11559 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
11560 | S.PDiag(diag::warn_shift_negative) |
11561 | << RHS.get()->getSourceRange()); |
11562 | return; |
11563 | } |
11564 | |
11565 | QualType LHSExprType = LHS.get()->getType(); |
11566 | uint64_t LeftSize = S.Context.getTypeSize(T: LHSExprType); |
11567 | if (LHSExprType->isBitIntType()) |
11568 | LeftSize = S.Context.getIntWidth(T: LHSExprType); |
11569 | else if (LHSExprType->isFixedPointType()) { |
11570 | auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType); |
11571 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); |
11572 | } |
11573 | if (Right.uge(RHS: LeftSize)) { |
11574 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
11575 | S.PDiag(diag::warn_shift_gt_typewidth) |
11576 | << RHS.get()->getSourceRange()); |
11577 | return; |
11578 | } |
11579 | |
11580 | // FIXME: We probably need to handle fixed point types specially here. |
11581 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) |
11582 | return; |
11583 | |
11584 | // When left shifting an ICE which is signed, we can check for overflow which |
11585 | // according to C++ standards prior to C++2a has undefined behavior |
11586 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one |
11587 | // more than the maximum value representable in the result type, so never |
11588 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant |
11589 | // expression is still probably a bug.) |
11590 | Expr::EvalResult LHSResult; |
11591 | if (LHS.get()->isValueDependent() || |
11592 | LHSType->hasUnsignedIntegerRepresentation() || |
11593 | !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: S.Context)) |
11594 | return; |
11595 | llvm::APSInt Left = LHSResult.Val.getInt(); |
11596 | |
11597 | // Don't warn if signed overflow is defined, then all the rest of the |
11598 | // diagnostics will not be triggered because the behavior is defined. |
11599 | // Also don't warn in C++20 mode (and newer), as signed left shifts |
11600 | // always wrap and never overflow. |
11601 | if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) |
11602 | return; |
11603 | |
11604 | // If LHS does not have a non-negative value then, the |
11605 | // behavior is undefined before C++2a. Warn about it. |
11606 | if (Left.isNegative()) { |
11607 | S.DiagRuntimeBehavior(Loc, LHS.get(), |
11608 | S.PDiag(diag::warn_shift_lhs_negative) |
11609 | << LHS.get()->getSourceRange()); |
11610 | return; |
11611 | } |
11612 | |
11613 | llvm::APInt ResultBits = |
11614 | static_cast<llvm::APInt &>(Right) + Left.getSignificantBits(); |
11615 | if (ResultBits.ule(RHS: LeftSize)) |
11616 | return; |
11617 | llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue()); |
11618 | Result = Result.shl(ShiftAmt: Right); |
11619 | |
11620 | // Print the bit representation of the signed integer as an unsigned |
11621 | // hexadecimal number. |
11622 | SmallString<40> HexResult; |
11623 | Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: true); |
11624 | |
11625 | // If we are only missing a sign bit, this is less likely to result in actual |
11626 | // bugs -- if the result is cast back to an unsigned type, it will have the |
11627 | // expected value. Thus we place this behind a different warning that can be |
11628 | // turned off separately if needed. |
11629 | if (ResultBits - 1 == LeftSize) { |
11630 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) |
11631 | << HexResult << LHSType |
11632 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11633 | return; |
11634 | } |
11635 | |
11636 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) |
11637 | << HexResult.str() << Result.getSignificantBits() << LHSType |
11638 | << Left.getBitWidth() << LHS.get()->getSourceRange() |
11639 | << RHS.get()->getSourceRange(); |
11640 | } |
11641 | |
11642 | /// Return the resulting type when a vector is shifted |
11643 | /// by a scalar or vector shift amount. |
11644 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, |
11645 | SourceLocation Loc, bool IsCompAssign) { |
11646 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. |
11647 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && |
11648 | !LHS.get()->getType()->isVectorType()) { |
11649 | S.Diag(Loc, diag::err_shift_rhs_only_vector) |
11650 | << RHS.get()->getType() << LHS.get()->getType() |
11651 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11652 | return QualType(); |
11653 | } |
11654 | |
11655 | if (!IsCompAssign) { |
11656 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
11657 | if (LHS.isInvalid()) return QualType(); |
11658 | } |
11659 | |
11660 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
11661 | if (RHS.isInvalid()) return QualType(); |
11662 | |
11663 | QualType LHSType = LHS.get()->getType(); |
11664 | // Note that LHS might be a scalar because the routine calls not only in |
11665 | // OpenCL case. |
11666 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); |
11667 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; |
11668 | |
11669 | // Note that RHS might not be a vector. |
11670 | QualType RHSType = RHS.get()->getType(); |
11671 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); |
11672 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; |
11673 | |
11674 | // Do not allow shifts for boolean vectors. |
11675 | if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || |
11676 | (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { |
11677 | S.Diag(Loc, diag::err_typecheck_invalid_operands) |
11678 | << LHS.get()->getType() << RHS.get()->getType() |
11679 | << LHS.get()->getSourceRange(); |
11680 | return QualType(); |
11681 | } |
11682 | |
11683 | // The operands need to be integers. |
11684 | if (!LHSEleType->isIntegerType()) { |
11685 | S.Diag(Loc, diag::err_typecheck_expect_int) |
11686 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
11687 | return QualType(); |
11688 | } |
11689 | |
11690 | if (!RHSEleType->isIntegerType()) { |
11691 | S.Diag(Loc, diag::err_typecheck_expect_int) |
11692 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
11693 | return QualType(); |
11694 | } |
11695 | |
11696 | if (!LHSVecTy) { |
11697 | assert(RHSVecTy); |
11698 | if (IsCompAssign) |
11699 | return RHSType; |
11700 | if (LHSEleType != RHSEleType) { |
11701 | LHS = S.ImpCastExprToType(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast); |
11702 | LHSEleType = RHSEleType; |
11703 | } |
11704 | QualType VecTy = |
11705 | S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements()); |
11706 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11707 | LHSType = VecTy; |
11708 | } else if (RHSVecTy) { |
11709 | // OpenCL v1.1 s6.3.j says that for vector types, the operators |
11710 | // are applied component-wise. So if RHS is a vector, then ensure |
11711 | // that the number of elements is the same as LHS... |
11712 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { |
11713 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) |
11714 | << LHS.get()->getType() << RHS.get()->getType() |
11715 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11716 | return QualType(); |
11717 | } |
11718 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { |
11719 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); |
11720 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); |
11721 | if (LHSBT != RHSBT && |
11722 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { |
11723 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) |
11724 | << LHS.get()->getType() << RHS.get()->getType() |
11725 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11726 | } |
11727 | } |
11728 | } else { |
11729 | // ...else expand RHS to match the number of elements in LHS. |
11730 | QualType VecTy = |
11731 | S.Context.getExtVectorType(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements()); |
11732 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11733 | } |
11734 | |
11735 | return LHSType; |
11736 | } |
11737 | |
11738 | static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, |
11739 | ExprResult &RHS, SourceLocation Loc, |
11740 | bool IsCompAssign) { |
11741 | if (!IsCompAssign) { |
11742 | LHS = S.UsualUnaryConversions(E: LHS.get()); |
11743 | if (LHS.isInvalid()) |
11744 | return QualType(); |
11745 | } |
11746 | |
11747 | RHS = S.UsualUnaryConversions(E: RHS.get()); |
11748 | if (RHS.isInvalid()) |
11749 | return QualType(); |
11750 | |
11751 | QualType LHSType = LHS.get()->getType(); |
11752 | const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>(); |
11753 | QualType LHSEleType = LHSType->isSveVLSBuiltinType() |
11754 | ? LHSBuiltinTy->getSveEltType(S.getASTContext()) |
11755 | : LHSType; |
11756 | |
11757 | // Note that RHS might not be a vector |
11758 | QualType RHSType = RHS.get()->getType(); |
11759 | const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>(); |
11760 | QualType RHSEleType = RHSType->isSveVLSBuiltinType() |
11761 | ? RHSBuiltinTy->getSveEltType(S.getASTContext()) |
11762 | : RHSType; |
11763 | |
11764 | if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || |
11765 | (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { |
11766 | S.Diag(Loc, diag::err_typecheck_invalid_operands) |
11767 | << LHSType << RHSType << LHS.get()->getSourceRange(); |
11768 | return QualType(); |
11769 | } |
11770 | |
11771 | if (!LHSEleType->isIntegerType()) { |
11772 | S.Diag(Loc, diag::err_typecheck_expect_int) |
11773 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
11774 | return QualType(); |
11775 | } |
11776 | |
11777 | if (!RHSEleType->isIntegerType()) { |
11778 | S.Diag(Loc, diag::err_typecheck_expect_int) |
11779 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
11780 | return QualType(); |
11781 | } |
11782 | |
11783 | if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && |
11784 | (S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC != |
11785 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC)) { |
11786 | S.Diag(Loc, diag::err_typecheck_invalid_operands) |
11787 | << LHSType << RHSType << LHS.get()->getSourceRange() |
11788 | << RHS.get()->getSourceRange(); |
11789 | return QualType(); |
11790 | } |
11791 | |
11792 | if (!LHSType->isSveVLSBuiltinType()) { |
11793 | assert(RHSType->isSveVLSBuiltinType()); |
11794 | if (IsCompAssign) |
11795 | return RHSType; |
11796 | if (LHSEleType != RHSEleType) { |
11797 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast); |
11798 | LHSEleType = RHSEleType; |
11799 | } |
11800 | const llvm::ElementCount VecSize = |
11801 | S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC; |
11802 | QualType VecTy = |
11803 | S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue()); |
11804 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: clang::CK_VectorSplat); |
11805 | LHSType = VecTy; |
11806 | } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) { |
11807 | if (S.Context.getTypeSize(RHSBuiltinTy) != |
11808 | S.Context.getTypeSize(LHSBuiltinTy)) { |
11809 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) |
11810 | << LHSType << RHSType << LHS.get()->getSourceRange() |
11811 | << RHS.get()->getSourceRange(); |
11812 | return QualType(); |
11813 | } |
11814 | } else { |
11815 | const llvm::ElementCount VecSize = |
11816 | S.Context.getBuiltinVectorTypeInfo(VecTy: LHSBuiltinTy).EC; |
11817 | if (LHSEleType != RHSEleType) { |
11818 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast); |
11819 | RHSEleType = LHSEleType; |
11820 | } |
11821 | QualType VecTy = |
11822 | S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue()); |
11823 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat); |
11824 | } |
11825 | |
11826 | return LHSType; |
11827 | } |
11828 | |
11829 | // C99 6.5.7 |
11830 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, |
11831 | SourceLocation Loc, BinaryOperatorKind Opc, |
11832 | bool IsCompAssign) { |
11833 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
11834 | |
11835 | // Vector shifts promote their scalar inputs to vector type. |
11836 | if (LHS.get()->getType()->isVectorType() || |
11837 | RHS.get()->getType()->isVectorType()) { |
11838 | if (LangOpts.ZVector) { |
11839 | // The shift operators for the z vector extensions work basically |
11840 | // like general shifts, except that neither the LHS nor the RHS is |
11841 | // allowed to be a "vector bool". |
11842 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) |
11843 | if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
11844 | return InvalidOperands(Loc, LHS, RHS); |
11845 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) |
11846 | if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool) |
11847 | return InvalidOperands(Loc, LHS, RHS); |
11848 | } |
11849 | return checkVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
11850 | } |
11851 | |
11852 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
11853 | RHS.get()->getType()->isSveVLSBuiltinType()) |
11854 | return checkSizelessVectorShift(S&: *this, LHS, RHS, Loc, IsCompAssign); |
11855 | |
11856 | // Shifts don't perform usual arithmetic conversions, they just do integer |
11857 | // promotions on each operand. C99 6.5.7p3 |
11858 | |
11859 | // For the LHS, do usual unary conversions, but then reset them away |
11860 | // if this is a compound assignment. |
11861 | ExprResult OldLHS = LHS; |
11862 | LHS = UsualUnaryConversions(E: LHS.get()); |
11863 | if (LHS.isInvalid()) |
11864 | return QualType(); |
11865 | QualType LHSType = LHS.get()->getType(); |
11866 | if (IsCompAssign) LHS = OldLHS; |
11867 | |
11868 | // The RHS is simpler. |
11869 | RHS = UsualUnaryConversions(E: RHS.get()); |
11870 | if (RHS.isInvalid()) |
11871 | return QualType(); |
11872 | QualType RHSType = RHS.get()->getType(); |
11873 | |
11874 | // C99 6.5.7p2: Each of the operands shall have integer type. |
11875 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. |
11876 | if ((!LHSType->isFixedPointOrIntegerType() && |
11877 | !LHSType->hasIntegerRepresentation()) || |
11878 | !RHSType->hasIntegerRepresentation()) |
11879 | return InvalidOperands(Loc, LHS, RHS); |
11880 | |
11881 | // C++0x: Don't allow scoped enums. FIXME: Use something better than |
11882 | // hasIntegerRepresentation() above instead of this. |
11883 | if (isScopedEnumerationType(T: LHSType) || |
11884 | isScopedEnumerationType(T: RHSType)) { |
11885 | return InvalidOperands(Loc, LHS, RHS); |
11886 | } |
11887 | DiagnoseBadShiftValues(S&: *this, LHS, RHS, Loc, Opc, LHSType); |
11888 | |
11889 | // "The type of the result is that of the promoted left operand." |
11890 | return LHSType; |
11891 | } |
11892 | |
11893 | /// Diagnose bad pointer comparisons. |
11894 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, |
11895 | ExprResult &LHS, ExprResult &RHS, |
11896 | bool IsError) { |
11897 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers |
11898 | : diag::ext_typecheck_comparison_of_distinct_pointers) |
11899 | << LHS.get()->getType() << RHS.get()->getType() |
11900 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11901 | } |
11902 | |
11903 | /// Returns false if the pointers are converted to a composite type, |
11904 | /// true otherwise. |
11905 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, |
11906 | ExprResult &LHS, ExprResult &RHS) { |
11907 | // C++ [expr.rel]p2: |
11908 | // [...] Pointer conversions (4.10) and qualification |
11909 | // conversions (4.4) are performed on pointer operands (or on |
11910 | // a pointer operand and a null pointer constant) to bring |
11911 | // them to their composite pointer type. [...] |
11912 | // |
11913 | // C++ [expr.eq]p1 uses the same notion for (in)equality |
11914 | // comparisons of pointers. |
11915 | |
11916 | QualType LHSType = LHS.get()->getType(); |
11917 | QualType RHSType = RHS.get()->getType(); |
11918 | assert(LHSType->isPointerType() || RHSType->isPointerType() || |
11919 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); |
11920 | |
11921 | QualType T = S.FindCompositePointerType(Loc, E1&: LHS, E2&: RHS); |
11922 | if (T.isNull()) { |
11923 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && |
11924 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) |
11925 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true); |
11926 | else |
11927 | S.InvalidOperands(Loc, LHS, RHS); |
11928 | return true; |
11929 | } |
11930 | |
11931 | return false; |
11932 | } |
11933 | |
11934 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, |
11935 | ExprResult &LHS, |
11936 | ExprResult &RHS, |
11937 | bool IsError) { |
11938 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void |
11939 | : diag::ext_typecheck_comparison_of_fptr_to_void) |
11940 | << LHS.get()->getType() << RHS.get()->getType() |
11941 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
11942 | } |
11943 | |
11944 | static bool isObjCObjectLiteral(ExprResult &E) { |
11945 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { |
11946 | case Stmt::ObjCArrayLiteralClass: |
11947 | case Stmt::ObjCDictionaryLiteralClass: |
11948 | case Stmt::ObjCStringLiteralClass: |
11949 | case Stmt::ObjCBoxedExprClass: |
11950 | return true; |
11951 | default: |
11952 | // Note that ObjCBoolLiteral is NOT an object literal! |
11953 | return false; |
11954 | } |
11955 | } |
11956 | |
11957 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { |
11958 | const ObjCObjectPointerType *Type = |
11959 | LHS->getType()->getAs<ObjCObjectPointerType>(); |
11960 | |
11961 | // If this is not actually an Objective-C object, bail out. |
11962 | if (!Type) |
11963 | return false; |
11964 | |
11965 | // Get the LHS object's interface type. |
11966 | QualType InterfaceType = Type->getPointeeType(); |
11967 | |
11968 | // If the RHS isn't an Objective-C object, bail out. |
11969 | if (!RHS->getType()->isObjCObjectPointerType()) |
11970 | return false; |
11971 | |
11972 | // Try to find the -isEqual: method. |
11973 | Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector(); |
11974 | ObjCMethodDecl *Method = |
11975 | S.ObjC().LookupMethodInObjectType(Sel: IsEqualSel, Ty: InterfaceType, |
11976 | /*IsInstance=*/true); |
11977 | if (!Method) { |
11978 | if (Type->isObjCIdType()) { |
11979 | // For 'id', just check the global pool. |
11980 | Method = |
11981 | S.ObjC().LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(), |
11982 | /*receiverId=*/receiverIdOrClass: true); |
11983 | } else { |
11984 | // Check protocols. |
11985 | Method = S.ObjC().LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: Type, |
11986 | /*IsInstance=*/true); |
11987 | } |
11988 | } |
11989 | |
11990 | if (!Method) |
11991 | return false; |
11992 | |
11993 | QualType T = Method->parameters()[0]->getType(); |
11994 | if (!T->isObjCObjectPointerType()) |
11995 | return false; |
11996 | |
11997 | QualType R = Method->getReturnType(); |
11998 | if (!R->isScalarType()) |
11999 | return false; |
12000 | |
12001 | return true; |
12002 | } |
12003 | |
12004 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, |
12005 | ExprResult &LHS, ExprResult &RHS, |
12006 | BinaryOperator::Opcode Opc){ |
12007 | Expr *Literal; |
12008 | Expr *Other; |
12009 | if (isObjCObjectLiteral(E&: LHS)) { |
12010 | Literal = LHS.get(); |
12011 | Other = RHS.get(); |
12012 | } else { |
12013 | Literal = RHS.get(); |
12014 | Other = LHS.get(); |
12015 | } |
12016 | |
12017 | // Don't warn on comparisons against nil. |
12018 | Other = Other->IgnoreParenCasts(); |
12019 | if (Other->isNullPointerConstant(Ctx&: S.getASTContext(), |
12020 | NPC: Expr::NPC_ValueDependentIsNotNull)) |
12021 | return; |
12022 | |
12023 | // This should be kept in sync with warn_objc_literal_comparison. |
12024 | // LK_String should always be after the other literals, since it has its own |
12025 | // warning flag. |
12026 | SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(FromE: Literal); |
12027 | assert(LiteralKind != SemaObjC::LK_Block); |
12028 | if (LiteralKind == SemaObjC::LK_None) { |
12029 | llvm_unreachable("Unknown Objective-C object literal kind"); |
12030 | } |
12031 | |
12032 | if (LiteralKind == SemaObjC::LK_String) |
12033 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) |
12034 | << Literal->getSourceRange(); |
12035 | else |
12036 | S.Diag(Loc, diag::warn_objc_literal_comparison) |
12037 | << LiteralKind << Literal->getSourceRange(); |
12038 | |
12039 | if (BinaryOperator::isEqualityOp(Opc) && |
12040 | hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) { |
12041 | SourceLocation Start = LHS.get()->getBeginLoc(); |
12042 | SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
12043 | CharSourceRange OpRange = |
12044 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
12045 | |
12046 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) |
12047 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[": "![") |
12048 | << FixItHint::CreateReplacement(OpRange, " isEqual:") |
12049 | << FixItHint::CreateInsertion(End, "]"); |
12050 | } |
12051 | } |
12052 | |
12053 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. |
12054 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, |
12055 | ExprResult &RHS, SourceLocation Loc, |
12056 | BinaryOperatorKind Opc) { |
12057 | // Check that left hand side is !something. |
12058 | UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: LHS.get()->IgnoreImpCasts()); |
12059 | if (!UO || UO->getOpcode() != UO_LNot) return; |
12060 | |
12061 | // Only check if the right hand side is non-bool arithmetic type. |
12062 | if (RHS.get()->isKnownToHaveBooleanValue()) return; |
12063 | |
12064 | // Make sure that the something in !something is not bool. |
12065 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); |
12066 | if (SubExpr->isKnownToHaveBooleanValue()) return; |
12067 | |
12068 | // Emit warning. |
12069 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; |
12070 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) |
12071 | << Loc << IsBitwiseOp; |
12072 | |
12073 | // First note suggest !(x < y) |
12074 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); |
12075 | SourceLocation FirstClose = RHS.get()->getEndLoc(); |
12076 | FirstClose = S.getLocForEndOfToken(Loc: FirstClose); |
12077 | if (FirstClose.isInvalid()) |
12078 | FirstOpen = SourceLocation(); |
12079 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) |
12080 | << IsBitwiseOp |
12081 | << FixItHint::CreateInsertion(FirstOpen, "(") |
12082 | << FixItHint::CreateInsertion(FirstClose, ")"); |
12083 | |
12084 | // Second note suggests (!x) < y |
12085 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); |
12086 | SourceLocation SecondClose = LHS.get()->getEndLoc(); |
12087 | SecondClose = S.getLocForEndOfToken(Loc: SecondClose); |
12088 | if (SecondClose.isInvalid()) |
12089 | SecondOpen = SourceLocation(); |
12090 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) |
12091 | << FixItHint::CreateInsertion(SecondOpen, "(") |
12092 | << FixItHint::CreateInsertion(SecondClose, ")"); |
12093 | } |
12094 | |
12095 | // Returns true if E refers to a non-weak array. |
12096 | static bool checkForArray(const Expr *E) { |
12097 | const ValueDecl *D = nullptr; |
12098 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: E)) { |
12099 | D = DR->getDecl(); |
12100 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: E)) { |
12101 | if (Mem->isImplicitAccess()) |
12102 | D = Mem->getMemberDecl(); |
12103 | } |
12104 | if (!D) |
12105 | return false; |
12106 | return D->getType()->isArrayType() && !D->isWeak(); |
12107 | } |
12108 | |
12109 | /// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a |
12110 | /// pointer and size is an unsigned integer. Return whether the result is |
12111 | /// always true/false. |
12112 | static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS, |
12113 | const Expr *RHS, |
12114 | BinaryOperatorKind Opc) { |
12115 | if (!LHS->getType()->isPointerType() || |
12116 | S.getLangOpts().PointerOverflowDefined) |
12117 | return std::nullopt; |
12118 | |
12119 | // Canonicalize to >= or < predicate. |
12120 | switch (Opc) { |
12121 | case BO_GE: |
12122 | case BO_LT: |
12123 | break; |
12124 | case BO_GT: |
12125 | std::swap(a&: LHS, b&: RHS); |
12126 | Opc = BO_LT; |
12127 | break; |
12128 | case BO_LE: |
12129 | std::swap(a&: LHS, b&: RHS); |
12130 | Opc = BO_GE; |
12131 | break; |
12132 | default: |
12133 | return std::nullopt; |
12134 | } |
12135 | |
12136 | auto *BO = dyn_cast<BinaryOperator>(Val: LHS); |
12137 | if (!BO || BO->getOpcode() != BO_Add) |
12138 | return std::nullopt; |
12139 | |
12140 | Expr *Other; |
12141 | if (Expr::isSameComparisonOperand(E1: BO->getLHS(), E2: RHS)) |
12142 | Other = BO->getRHS(); |
12143 | else if (Expr::isSameComparisonOperand(E1: BO->getRHS(), E2: RHS)) |
12144 | Other = BO->getLHS(); |
12145 | else |
12146 | return std::nullopt; |
12147 | |
12148 | if (!Other->getType()->isUnsignedIntegerType()) |
12149 | return std::nullopt; |
12150 | |
12151 | return Opc == BO_GE; |
12152 | } |
12153 | |
12154 | /// Diagnose some forms of syntactically-obvious tautological comparison. |
12155 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, |
12156 | Expr *LHS, Expr *RHS, |
12157 | BinaryOperatorKind Opc) { |
12158 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); |
12159 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); |
12160 | |
12161 | QualType LHSType = LHS->getType(); |
12162 | QualType RHSType = RHS->getType(); |
12163 | if (LHSType->hasFloatingRepresentation() || |
12164 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || |
12165 | S.inTemplateInstantiation()) |
12166 | return; |
12167 | |
12168 | // WebAssembly Tables cannot be compared, therefore shouldn't emit |
12169 | // Tautological diagnostics. |
12170 | if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType()) |
12171 | return; |
12172 | |
12173 | // Comparisons between two array types are ill-formed for operator<=>, so |
12174 | // we shouldn't emit any additional warnings about it. |
12175 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) |
12176 | return; |
12177 | |
12178 | // For non-floating point types, check for self-comparisons of the form |
12179 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
12180 | // often indicate logic errors in the program. |
12181 | // |
12182 | // NOTE: Don't warn about comparison expressions resulting from macro |
12183 | // expansion. Also don't warn about comparisons which are only self |
12184 | // comparisons within a template instantiation. The warnings should catch |
12185 | // obvious cases in the definition of the template anyways. The idea is to |
12186 | // warn when the typed comparison operator will always evaluate to the same |
12187 | // result. |
12188 | |
12189 | // Used for indexing into %select in warn_comparison_always |
12190 | enum { |
12191 | AlwaysConstant, |
12192 | AlwaysTrue, |
12193 | AlwaysFalse, |
12194 | AlwaysEqual, // std::strong_ordering::equal from operator<=> |
12195 | }; |
12196 | |
12197 | // C++1a [array.comp]: |
12198 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two |
12199 | // operands of array type. |
12200 | // C++2a [depr.array.comp]: |
12201 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two |
12202 | // operands of array type are deprecated. |
12203 | if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() && |
12204 | RHSStripped->getType()->isArrayType()) { |
12205 | auto IsDeprArrayComparionIgnored = |
12206 | S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc); |
12207 | auto DiagID = S.getLangOpts().CPlusPlus26 |
12208 | ? diag::warn_array_comparison_cxx26 |
12209 | : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored |
12210 | ? diag::warn_array_comparison |
12211 | : diag::warn_depr_array_comparison; |
12212 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() |
12213 | << LHSStripped->getType() << RHSStripped->getType(); |
12214 | // Carry on to produce the tautological comparison warning, if this |
12215 | // expression is potentially-evaluated, we can resolve the array to a |
12216 | // non-weak declaration, and so on. |
12217 | } |
12218 | |
12219 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { |
12220 | if (Expr::isSameComparisonOperand(E1: LHS, E2: RHS)) { |
12221 | unsigned Result; |
12222 | switch (Opc) { |
12223 | case BO_EQ: |
12224 | case BO_LE: |
12225 | case BO_GE: |
12226 | Result = AlwaysTrue; |
12227 | break; |
12228 | case BO_NE: |
12229 | case BO_LT: |
12230 | case BO_GT: |
12231 | Result = AlwaysFalse; |
12232 | break; |
12233 | case BO_Cmp: |
12234 | Result = AlwaysEqual; |
12235 | break; |
12236 | default: |
12237 | Result = AlwaysConstant; |
12238 | break; |
12239 | } |
12240 | S.DiagRuntimeBehavior(Loc, nullptr, |
12241 | S.PDiag(diag::warn_comparison_always) |
12242 | << 0 /*self-comparison*/ |
12243 | << Result); |
12244 | } else if (checkForArray(E: LHSStripped) && checkForArray(E: RHSStripped)) { |
12245 | // What is it always going to evaluate to? |
12246 | unsigned Result; |
12247 | switch (Opc) { |
12248 | case BO_EQ: // e.g. array1 == array2 |
12249 | Result = AlwaysFalse; |
12250 | break; |
12251 | case BO_NE: // e.g. array1 != array2 |
12252 | Result = AlwaysTrue; |
12253 | break; |
12254 | default: // e.g. array1 <= array2 |
12255 | // The best we can say is 'a constant' |
12256 | Result = AlwaysConstant; |
12257 | break; |
12258 | } |
12259 | S.DiagRuntimeBehavior(Loc, nullptr, |
12260 | S.PDiag(diag::warn_comparison_always) |
12261 | << 1 /*array comparison*/ |
12262 | << Result); |
12263 | } else if (std::optional<bool> Res = |
12264 | isTautologicalBoundsCheck(S, LHS, RHS, Opc)) { |
12265 | S.DiagRuntimeBehavior(Loc, nullptr, |
12266 | S.PDiag(diag::warn_comparison_always) |
12267 | << 2 /*pointer comparison*/ |
12268 | << (*Res ? AlwaysTrue : AlwaysFalse)); |
12269 | } |
12270 | } |
12271 | |
12272 | if (isa<CastExpr>(Val: LHSStripped)) |
12273 | LHSStripped = LHSStripped->IgnoreParenCasts(); |
12274 | if (isa<CastExpr>(Val: RHSStripped)) |
12275 | RHSStripped = RHSStripped->IgnoreParenCasts(); |
12276 | |
12277 | // Warn about comparisons against a string constant (unless the other |
12278 | // operand is null); the user probably wants string comparison function. |
12279 | Expr *LiteralString = nullptr; |
12280 | Expr *LiteralStringStripped = nullptr; |
12281 | if ((isa<StringLiteral>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) && |
12282 | !RHSStripped->isNullPointerConstant(Ctx&: S.Context, |
12283 | NPC: Expr::NPC_ValueDependentIsNull)) { |
12284 | LiteralString = LHS; |
12285 | LiteralStringStripped = LHSStripped; |
12286 | } else if ((isa<StringLiteral>(Val: RHSStripped) || |
12287 | isa<ObjCEncodeExpr>(Val: RHSStripped)) && |
12288 | !LHSStripped->isNullPointerConstant(Ctx&: S.Context, |
12289 | NPC: Expr::NPC_ValueDependentIsNull)) { |
12290 | LiteralString = RHS; |
12291 | LiteralStringStripped = RHSStripped; |
12292 | } |
12293 | |
12294 | if (LiteralString) { |
12295 | S.DiagRuntimeBehavior(Loc, nullptr, |
12296 | S.PDiag(diag::warn_stringcompare) |
12297 | << isa<ObjCEncodeExpr>(LiteralStringStripped) |
12298 | << LiteralString->getSourceRange()); |
12299 | } |
12300 | } |
12301 | |
12302 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { |
12303 | switch (CK) { |
12304 | default: { |
12305 | #ifndef NDEBUG |
12306 | llvm::errs() << "unhandled cast kind: "<< CastExpr::getCastKindName(CK) |
12307 | << "\n"; |
12308 | #endif |
12309 | llvm_unreachable("unhandled cast kind"); |
12310 | } |
12311 | case CK_UserDefinedConversion: |
12312 | return ICK_Identity; |
12313 | case CK_LValueToRValue: |
12314 | return ICK_Lvalue_To_Rvalue; |
12315 | case CK_ArrayToPointerDecay: |
12316 | return ICK_Array_To_Pointer; |
12317 | case CK_FunctionToPointerDecay: |
12318 | return ICK_Function_To_Pointer; |
12319 | case CK_IntegralCast: |
12320 | return ICK_Integral_Conversion; |
12321 | case CK_FloatingCast: |
12322 | return ICK_Floating_Conversion; |
12323 | case CK_IntegralToFloating: |
12324 | case CK_FloatingToIntegral: |
12325 | return ICK_Floating_Integral; |
12326 | case CK_IntegralComplexCast: |
12327 | case CK_FloatingComplexCast: |
12328 | case CK_FloatingComplexToIntegralComplex: |
12329 | case CK_IntegralComplexToFloatingComplex: |
12330 | return ICK_Complex_Conversion; |
12331 | case CK_FloatingComplexToReal: |
12332 | case CK_FloatingRealToComplex: |
12333 | case CK_IntegralComplexToReal: |
12334 | case CK_IntegralRealToComplex: |
12335 | return ICK_Complex_Real; |
12336 | case CK_HLSLArrayRValue: |
12337 | return ICK_HLSL_Array_RValue; |
12338 | } |
12339 | } |
12340 | |
12341 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, |
12342 | QualType FromType, |
12343 | SourceLocation Loc) { |
12344 | // Check for a narrowing implicit conversion. |
12345 | StandardConversionSequence SCS; |
12346 | SCS.setAsIdentityConversion(); |
12347 | SCS.setToType(Idx: 0, T: FromType); |
12348 | SCS.setToType(Idx: 1, T: ToType); |
12349 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) |
12350 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); |
12351 | |
12352 | APValue PreNarrowingValue; |
12353 | QualType PreNarrowingType; |
12354 | switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue, |
12355 | ConstantType&: PreNarrowingType, |
12356 | /*IgnoreFloatToIntegralConversion*/ true)) { |
12357 | case NK_Dependent_Narrowing: |
12358 | // Implicit conversion to a narrower type, but the expression is |
12359 | // value-dependent so we can't tell whether it's actually narrowing. |
12360 | case NK_Not_Narrowing: |
12361 | return false; |
12362 | |
12363 | case NK_Constant_Narrowing: |
12364 | // Implicit conversion to a narrower type, and the value is not a constant |
12365 | // expression. |
12366 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) |
12367 | << /*Constant*/ 1 |
12368 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; |
12369 | return true; |
12370 | |
12371 | case NK_Variable_Narrowing: |
12372 | // Implicit conversion to a narrower type, and the value is not a constant |
12373 | // expression. |
12374 | case NK_Type_Narrowing: |
12375 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) |
12376 | << /*Constant*/ 0 << FromType << ToType; |
12377 | // TODO: It's not a constant expression, but what if the user intended it |
12378 | // to be? Can we produce notes to help them figure out why it isn't? |
12379 | return true; |
12380 | } |
12381 | llvm_unreachable("unhandled case in switch"); |
12382 | } |
12383 | |
12384 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, |
12385 | ExprResult &LHS, |
12386 | ExprResult &RHS, |
12387 | SourceLocation Loc) { |
12388 | QualType LHSType = LHS.get()->getType(); |
12389 | QualType RHSType = RHS.get()->getType(); |
12390 | // Dig out the original argument type and expression before implicit casts |
12391 | // were applied. These are the types/expressions we need to check the |
12392 | // [expr.spaceship] requirements against. |
12393 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); |
12394 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); |
12395 | QualType LHSStrippedType = LHSStripped.get()->getType(); |
12396 | QualType RHSStrippedType = RHSStripped.get()->getType(); |
12397 | |
12398 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the |
12399 | // other is not, the program is ill-formed. |
12400 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { |
12401 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
12402 | return QualType(); |
12403 | } |
12404 | |
12405 | // FIXME: Consider combining this with checkEnumArithmeticConversions. |
12406 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + |
12407 | RHSStrippedType->isEnumeralType(); |
12408 | if (NumEnumArgs == 1) { |
12409 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); |
12410 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; |
12411 | if (OtherTy->hasFloatingRepresentation()) { |
12412 | S.InvalidOperands(Loc, LHS&: LHSStripped, RHS&: RHSStripped); |
12413 | return QualType(); |
12414 | } |
12415 | } |
12416 | if (NumEnumArgs == 2) { |
12417 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration |
12418 | // type E, the operator yields the result of converting the operands |
12419 | // to the underlying type of E and applying <=> to the converted operands. |
12420 | if (!S.Context.hasSameUnqualifiedType(T1: LHSStrippedType, T2: RHSStrippedType)) { |
12421 | S.InvalidOperands(Loc, LHS, RHS); |
12422 | return QualType(); |
12423 | } |
12424 | QualType IntType = |
12425 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); |
12426 | assert(IntType->isArithmeticType()); |
12427 | |
12428 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we |
12429 | // promote the boolean type, and all other promotable integer types, to |
12430 | // avoid this. |
12431 | if (S.Context.isPromotableIntegerType(T: IntType)) |
12432 | IntType = S.Context.getPromotedIntegerType(PromotableType: IntType); |
12433 | |
12434 | LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast); |
12435 | RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: CK_IntegralCast); |
12436 | LHSType = RHSType = IntType; |
12437 | } |
12438 | |
12439 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the |
12440 | // usual arithmetic conversions are applied to the operands. |
12441 | QualType Type = |
12442 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison); |
12443 | if (LHS.isInvalid() || RHS.isInvalid()) |
12444 | return QualType(); |
12445 | if (Type.isNull()) |
12446 | return S.InvalidOperands(Loc, LHS, RHS); |
12447 | |
12448 | std::optional<ComparisonCategoryType> CCT = |
12449 | getComparisonCategoryForBuiltinCmp(T: Type); |
12450 | if (!CCT) |
12451 | return S.InvalidOperands(Loc, LHS, RHS); |
12452 | |
12453 | bool HasNarrowing = checkThreeWayNarrowingConversion( |
12454 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); |
12455 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, |
12456 | RHS.get()->getBeginLoc()); |
12457 | if (HasNarrowing) |
12458 | return QualType(); |
12459 | |
12460 | assert(!Type.isNull() && "composite type for <=> has not been set"); |
12461 | |
12462 | return S.CheckComparisonCategoryType( |
12463 | Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression); |
12464 | } |
12465 | |
12466 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, |
12467 | ExprResult &RHS, |
12468 | SourceLocation Loc, |
12469 | BinaryOperatorKind Opc) { |
12470 | if (Opc == BO_Cmp) |
12471 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); |
12472 | |
12473 | // C99 6.5.8p3 / C99 6.5.9p4 |
12474 | QualType Type = |
12475 | S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: ArithConvKind::Comparison); |
12476 | if (LHS.isInvalid() || RHS.isInvalid()) |
12477 | return QualType(); |
12478 | if (Type.isNull()) |
12479 | return S.InvalidOperands(Loc, LHS, RHS); |
12480 | assert(Type->isArithmeticType() || Type->isEnumeralType()); |
12481 | |
12482 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) |
12483 | return S.InvalidOperands(Loc, LHS, RHS); |
12484 | |
12485 | // Check for comparisons of floating point operands using != and ==. |
12486 | if (Type->hasFloatingRepresentation()) |
12487 | S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
12488 | |
12489 | // The result of comparisons is 'bool' in C++, 'int' in C. |
12490 | return S.Context.getLogicalOperationType(); |
12491 | } |
12492 | |
12493 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { |
12494 | if (!NullE.get()->getType()->isAnyPointerType()) |
12495 | return; |
12496 | int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1; |
12497 | if (!E.get()->getType()->isAnyPointerType() && |
12498 | E.get()->isNullPointerConstant(Ctx&: Context, |
12499 | NPC: Expr::NPC_ValueDependentIsNotNull) == |
12500 | Expr::NPCK_ZeroExpression) { |
12501 | if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) { |
12502 | if (CL->getValue() == 0) |
12503 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) |
12504 | << NullValue |
12505 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), |
12506 | NullValue ? "NULL": "(void *)0"); |
12507 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) { |
12508 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); |
12509 | QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType(); |
12510 | if (T == Context.CharTy) |
12511 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) |
12512 | << NullValue |
12513 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), |
12514 | NullValue ? "NULL": "(void *)0"); |
12515 | } |
12516 | } |
12517 | } |
12518 | |
12519 | // C99 6.5.8, C++ [expr.rel] |
12520 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, |
12521 | SourceLocation Loc, |
12522 | BinaryOperatorKind Opc) { |
12523 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); |
12524 | bool IsThreeWay = Opc == BO_Cmp; |
12525 | bool IsOrdered = IsRelational || IsThreeWay; |
12526 | auto IsAnyPointerType = [](ExprResult E) { |
12527 | QualType Ty = E.get()->getType(); |
12528 | return Ty->isPointerType() || Ty->isMemberPointerType(); |
12529 | }; |
12530 | |
12531 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer |
12532 | // type, array-to-pointer, ..., conversions are performed on both operands to |
12533 | // bring them to their composite type. |
12534 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before |
12535 | // any type-related checks. |
12536 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { |
12537 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
12538 | if (LHS.isInvalid()) |
12539 | return QualType(); |
12540 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
12541 | if (RHS.isInvalid()) |
12542 | return QualType(); |
12543 | } else { |
12544 | LHS = DefaultLvalueConversion(E: LHS.get()); |
12545 | if (LHS.isInvalid()) |
12546 | return QualType(); |
12547 | RHS = DefaultLvalueConversion(E: RHS.get()); |
12548 | if (RHS.isInvalid()) |
12549 | return QualType(); |
12550 | } |
12551 | |
12552 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true); |
12553 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { |
12554 | CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS); |
12555 | CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS); |
12556 | } |
12557 | |
12558 | // Handle vector comparisons separately. |
12559 | if (LHS.get()->getType()->isVectorType() || |
12560 | RHS.get()->getType()->isVectorType()) |
12561 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); |
12562 | |
12563 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
12564 | RHS.get()->getType()->isSveVLSBuiltinType()) |
12565 | return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); |
12566 | |
12567 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
12568 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
12569 | |
12570 | QualType LHSType = LHS.get()->getType(); |
12571 | QualType RHSType = RHS.get()->getType(); |
12572 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && |
12573 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) |
12574 | return checkArithmeticOrEnumeralCompare(S&: *this, LHS, RHS, Loc, Opc); |
12575 | |
12576 | if ((LHSType->isPointerType() && |
12577 | LHSType->getPointeeType().isWebAssemblyReferenceType()) || |
12578 | (RHSType->isPointerType() && |
12579 | RHSType->getPointeeType().isWebAssemblyReferenceType())) |
12580 | return InvalidOperands(Loc, LHS, RHS); |
12581 | |
12582 | const Expr::NullPointerConstantKind LHSNullKind = |
12583 | LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
12584 | const Expr::NullPointerConstantKind RHSNullKind = |
12585 | RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull); |
12586 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; |
12587 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
12588 | |
12589 | auto computeResultTy = [&]() { |
12590 | if (Opc != BO_Cmp) |
12591 | return Context.getLogicalOperationType(); |
12592 | assert(getLangOpts().CPlusPlus); |
12593 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); |
12594 | |
12595 | QualType CompositeTy = LHS.get()->getType(); |
12596 | assert(!CompositeTy->isReferenceType()); |
12597 | |
12598 | std::optional<ComparisonCategoryType> CCT = |
12599 | getComparisonCategoryForBuiltinCmp(T: CompositeTy); |
12600 | if (!CCT) |
12601 | return InvalidOperands(Loc, LHS, RHS); |
12602 | |
12603 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { |
12604 | // P0946R0: Comparisons between a null pointer constant and an object |
12605 | // pointer result in std::strong_equality, which is ill-formed under |
12606 | // P1959R0. |
12607 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) |
12608 | << (LHSIsNull ? LHS.get()->getSourceRange() |
12609 | : RHS.get()->getSourceRange()); |
12610 | return QualType(); |
12611 | } |
12612 | |
12613 | return CheckComparisonCategoryType( |
12614 | Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression); |
12615 | }; |
12616 | |
12617 | if (!IsOrdered && LHSIsNull != RHSIsNull) { |
12618 | bool IsEquality = Opc == BO_EQ; |
12619 | if (RHSIsNull) |
12620 | DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality, |
12621 | Range: RHS.get()->getSourceRange()); |
12622 | else |
12623 | DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality, |
12624 | Range: LHS.get()->getSourceRange()); |
12625 | } |
12626 | |
12627 | if (IsOrdered && LHSType->isFunctionPointerType() && |
12628 | RHSType->isFunctionPointerType()) { |
12629 | // Valid unless a relational comparison of function pointers |
12630 | bool IsError = Opc == BO_Cmp; |
12631 | auto DiagID = |
12632 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers |
12633 | : getLangOpts().CPlusPlus |
12634 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers |
12635 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; |
12636 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() |
12637 | << RHS.get()->getSourceRange(); |
12638 | if (IsError) |
12639 | return QualType(); |
12640 | } |
12641 | |
12642 | if ((LHSType->isIntegerType() && !LHSIsNull) || |
12643 | (RHSType->isIntegerType() && !RHSIsNull)) { |
12644 | // Skip normal pointer conversion checks in this case; we have better |
12645 | // diagnostics for this below. |
12646 | } else if (getLangOpts().CPlusPlus) { |
12647 | // Equality comparison of a function pointer to a void pointer is invalid, |
12648 | // but we allow it as an extension. |
12649 | // FIXME: If we really want to allow this, should it be part of composite |
12650 | // pointer type computation so it works in conditionals too? |
12651 | if (!IsOrdered && |
12652 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || |
12653 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { |
12654 | // This is a gcc extension compatibility comparison. |
12655 | // In a SFINAE context, we treat this as a hard error to maintain |
12656 | // conformance with the C++ standard. |
12657 | diagnoseFunctionPointerToVoidComparison( |
12658 | S&: *this, Loc, LHS, RHS, /*isError*/ IsError: (bool)isSFINAEContext()); |
12659 | |
12660 | if (isSFINAEContext()) |
12661 | return QualType(); |
12662 | |
12663 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12664 | return computeResultTy(); |
12665 | } |
12666 | |
12667 | // C++ [expr.eq]p2: |
12668 | // If at least one operand is a pointer [...] bring them to their |
12669 | // composite pointer type. |
12670 | // C++ [expr.spaceship]p6 |
12671 | // If at least one of the operands is of pointer type, [...] bring them |
12672 | // to their composite pointer type. |
12673 | // C++ [expr.rel]p2: |
12674 | // If both operands are pointers, [...] bring them to their composite |
12675 | // pointer type. |
12676 | // For <=>, the only valid non-pointer types are arrays and functions, and |
12677 | // we already decayed those, so this is really the same as the relational |
12678 | // comparison rule. |
12679 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= |
12680 | (IsOrdered ? 2 : 1) && |
12681 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || |
12682 | RHSType->isObjCObjectPointerType()))) { |
12683 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
12684 | return QualType(); |
12685 | return computeResultTy(); |
12686 | } |
12687 | } else if (LHSType->isPointerType() && |
12688 | RHSType->isPointerType()) { // C99 6.5.8p2 |
12689 | // All of the following pointer-related warnings are GCC extensions, except |
12690 | // when handling null pointer constants. |
12691 | QualType LCanPointeeTy = |
12692 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
12693 | QualType RCanPointeeTy = |
12694 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
12695 | |
12696 | // C99 6.5.9p2 and C99 6.5.8p2 |
12697 | if (Context.typesAreCompatible(T1: LCanPointeeTy.getUnqualifiedType(), |
12698 | T2: RCanPointeeTy.getUnqualifiedType())) { |
12699 | if (IsRelational) { |
12700 | // Pointers both need to point to complete or incomplete types |
12701 | if ((LCanPointeeTy->isIncompleteType() != |
12702 | RCanPointeeTy->isIncompleteType()) && |
12703 | !getLangOpts().C11) { |
12704 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) |
12705 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() |
12706 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() |
12707 | << RCanPointeeTy->isIncompleteType(); |
12708 | } |
12709 | } |
12710 | } else if (!IsRelational && |
12711 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { |
12712 | // Valid unless comparison between non-null pointer and function pointer |
12713 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) |
12714 | && !LHSIsNull && !RHSIsNull) |
12715 | diagnoseFunctionPointerToVoidComparison(S&: *this, Loc, LHS, RHS, |
12716 | /*isError*/IsError: false); |
12717 | } else { |
12718 | // Invalid |
12719 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/IsError: false); |
12720 | } |
12721 | if (LCanPointeeTy != RCanPointeeTy) { |
12722 | // Treat NULL constant as a special case in OpenCL. |
12723 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { |
12724 | if (!LCanPointeeTy.isAddressSpaceOverlapping(T: RCanPointeeTy, |
12725 | Ctx: getASTContext())) { |
12726 | Diag(Loc, |
12727 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
12728 | << LHSType << RHSType << 0 /* comparison */ |
12729 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
12730 | } |
12731 | } |
12732 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); |
12733 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); |
12734 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion |
12735 | : CK_BitCast; |
12736 | |
12737 | const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>(); |
12738 | const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>(); |
12739 | bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr(); |
12740 | bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr(); |
12741 | bool ChangingCFIUncheckedCallee = |
12742 | LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee; |
12743 | |
12744 | if (LHSIsNull && !RHSIsNull) |
12745 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: Kind); |
12746 | else if (!ChangingCFIUncheckedCallee) |
12747 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind); |
12748 | } |
12749 | return computeResultTy(); |
12750 | } |
12751 | |
12752 | |
12753 | // C++ [expr.eq]p4: |
12754 | // Two operands of type std::nullptr_t or one operand of type |
12755 | // std::nullptr_t and the other a null pointer constant compare |
12756 | // equal. |
12757 | // C23 6.5.9p5: |
12758 | // If both operands have type nullptr_t or one operand has type nullptr_t |
12759 | // and the other is a null pointer constant, they compare equal if the |
12760 | // former is a null pointer. |
12761 | if (!IsOrdered && LHSIsNull && RHSIsNull) { |
12762 | if (LHSType->isNullPtrType()) { |
12763 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12764 | return computeResultTy(); |
12765 | } |
12766 | if (RHSType->isNullPtrType()) { |
12767 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12768 | return computeResultTy(); |
12769 | } |
12770 | } |
12771 | |
12772 | if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { |
12773 | // C23 6.5.9p6: |
12774 | // Otherwise, at least one operand is a pointer. If one is a pointer and |
12775 | // the other is a null pointer constant or has type nullptr_t, they |
12776 | // compare equal |
12777 | if (LHSIsNull && RHSType->isPointerType()) { |
12778 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12779 | return computeResultTy(); |
12780 | } |
12781 | if (RHSIsNull && LHSType->isPointerType()) { |
12782 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12783 | return computeResultTy(); |
12784 | } |
12785 | } |
12786 | |
12787 | // Comparison of Objective-C pointers and block pointers against nullptr_t. |
12788 | // These aren't covered by the composite pointer type rules. |
12789 | if (!IsOrdered && RHSType->isNullPtrType() && |
12790 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { |
12791 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12792 | return computeResultTy(); |
12793 | } |
12794 | if (!IsOrdered && LHSType->isNullPtrType() && |
12795 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { |
12796 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12797 | return computeResultTy(); |
12798 | } |
12799 | |
12800 | if (getLangOpts().CPlusPlus) { |
12801 | if (IsRelational && |
12802 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || |
12803 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { |
12804 | // HACK: Relational comparison of nullptr_t against a pointer type is |
12805 | // invalid per DR583, but we allow it within std::less<> and friends, |
12806 | // since otherwise common uses of it break. |
12807 | // FIXME: Consider removing this hack once LWG fixes std::less<> and |
12808 | // friends to have std::nullptr_t overload candidates. |
12809 | DeclContext *DC = CurContext; |
12810 | if (isa<FunctionDecl>(Val: DC)) |
12811 | DC = DC->getParent(); |
12812 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) { |
12813 | if (CTSD->isInStdNamespace() && |
12814 | llvm::StringSwitch<bool>(CTSD->getName()) |
12815 | .Cases(S0: "less", S1: "less_equal", S2: "greater", S3: "greater_equal", Value: true) |
12816 | .Default(Value: false)) { |
12817 | if (RHSType->isNullPtrType()) |
12818 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12819 | else |
12820 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12821 | return computeResultTy(); |
12822 | } |
12823 | } |
12824 | } |
12825 | |
12826 | // C++ [expr.eq]p2: |
12827 | // If at least one operand is a pointer to member, [...] bring them to |
12828 | // their composite pointer type. |
12829 | if (!IsOrdered && |
12830 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { |
12831 | if (convertPointersToCompositeType(S&: *this, Loc, LHS, RHS)) |
12832 | return QualType(); |
12833 | else |
12834 | return computeResultTy(); |
12835 | } |
12836 | } |
12837 | |
12838 | // Handle block pointer types. |
12839 | if (!IsOrdered && LHSType->isBlockPointerType() && |
12840 | RHSType->isBlockPointerType()) { |
12841 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); |
12842 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); |
12843 | |
12844 | if (!LHSIsNull && !RHSIsNull && |
12845 | !Context.typesAreCompatible(T1: lpointee, T2: rpointee)) { |
12846 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) |
12847 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12848 | << RHS.get()->getSourceRange(); |
12849 | } |
12850 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12851 | return computeResultTy(); |
12852 | } |
12853 | |
12854 | // Allow block pointers to be compared with null pointer constants. |
12855 | if (!IsOrdered |
12856 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) |
12857 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { |
12858 | if (!LHSIsNull && !RHSIsNull) { |
12859 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() |
12860 | ->getPointeeType()->isVoidType()) |
12861 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() |
12862 | ->getPointeeType()->isVoidType()))) |
12863 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) |
12864 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12865 | << RHS.get()->getSourceRange(); |
12866 | } |
12867 | if (LHSIsNull && !RHSIsNull) |
12868 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12869 | CK: RHSType->isPointerType() ? CK_BitCast |
12870 | : CK_AnyPointerToBlockPointerCast); |
12871 | else |
12872 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12873 | CK: LHSType->isPointerType() ? CK_BitCast |
12874 | : CK_AnyPointerToBlockPointerCast); |
12875 | return computeResultTy(); |
12876 | } |
12877 | |
12878 | if (LHSType->isObjCObjectPointerType() || |
12879 | RHSType->isObjCObjectPointerType()) { |
12880 | const PointerType *LPT = LHSType->getAs<PointerType>(); |
12881 | const PointerType *RPT = RHSType->getAs<PointerType>(); |
12882 | if (LPT || RPT) { |
12883 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; |
12884 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; |
12885 | |
12886 | if (!LPtrToVoid && !RPtrToVoid && |
12887 | !Context.typesAreCompatible(T1: LHSType, T2: RHSType)) { |
12888 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
12889 | /*isError*/IsError: false); |
12890 | } |
12891 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than |
12892 | // the RHS, but we have test coverage for this behavior. |
12893 | // FIXME: Consider using convertPointersToCompositeType in C++. |
12894 | if (LHSIsNull && !RHSIsNull) { |
12895 | Expr *E = LHS.get(); |
12896 | if (getLangOpts().ObjCAutoRefCount) |
12897 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: RHSType, op&: E, |
12898 | CCK: CheckedConversionKind::Implicit); |
12899 | LHS = ImpCastExprToType(E, Type: RHSType, |
12900 | CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
12901 | } |
12902 | else { |
12903 | Expr *E = RHS.get(); |
12904 | if (getLangOpts().ObjCAutoRefCount) |
12905 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E, |
12906 | CCK: CheckedConversionKind::Implicit, |
12907 | /*Diagnose=*/true, |
12908 | /*DiagnoseCFAudited=*/false, Opc); |
12909 | RHS = ImpCastExprToType(E, Type: LHSType, |
12910 | CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
12911 | } |
12912 | return computeResultTy(); |
12913 | } |
12914 | if (LHSType->isObjCObjectPointerType() && |
12915 | RHSType->isObjCObjectPointerType()) { |
12916 | if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType)) |
12917 | diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, |
12918 | /*isError*/IsError: false); |
12919 | if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS)) |
12920 | diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc); |
12921 | |
12922 | if (LHSIsNull && !RHSIsNull) |
12923 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast); |
12924 | else |
12925 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast); |
12926 | return computeResultTy(); |
12927 | } |
12928 | |
12929 | if (!IsOrdered && LHSType->isBlockPointerType() && |
12930 | RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) { |
12931 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12932 | CK: CK_BlockPointerToObjCPointerCast); |
12933 | return computeResultTy(); |
12934 | } else if (!IsOrdered && |
12935 | LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) && |
12936 | RHSType->isBlockPointerType()) { |
12937 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12938 | CK: CK_BlockPointerToObjCPointerCast); |
12939 | return computeResultTy(); |
12940 | } |
12941 | } |
12942 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || |
12943 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { |
12944 | unsigned DiagID = 0; |
12945 | bool isError = false; |
12946 | if (LangOpts.DebuggerSupport) { |
12947 | // Under a debugger, allow the comparison of pointers to integers, |
12948 | // since users tend to want to compare addresses. |
12949 | } else if ((LHSIsNull && LHSType->isIntegerType()) || |
12950 | (RHSIsNull && RHSType->isIntegerType())) { |
12951 | if (IsOrdered) { |
12952 | isError = getLangOpts().CPlusPlus; |
12953 | DiagID = |
12954 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero |
12955 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; |
12956 | } |
12957 | } else if (getLangOpts().CPlusPlus) { |
12958 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; |
12959 | isError = true; |
12960 | } else if (IsOrdered) |
12961 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; |
12962 | else |
12963 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; |
12964 | |
12965 | if (DiagID) { |
12966 | Diag(Loc, DiagID) |
12967 | << LHSType << RHSType << LHS.get()->getSourceRange() |
12968 | << RHS.get()->getSourceRange(); |
12969 | if (isError) |
12970 | return QualType(); |
12971 | } |
12972 | |
12973 | if (LHSType->isIntegerType()) |
12974 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, |
12975 | CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
12976 | else |
12977 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, |
12978 | CK: RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
12979 | return computeResultTy(); |
12980 | } |
12981 | |
12982 | // Handle block pointers. |
12983 | if (!IsOrdered && RHSIsNull |
12984 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { |
12985 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
12986 | return computeResultTy(); |
12987 | } |
12988 | if (!IsOrdered && LHSIsNull |
12989 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { |
12990 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
12991 | return computeResultTy(); |
12992 | } |
12993 | |
12994 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { |
12995 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { |
12996 | return computeResultTy(); |
12997 | } |
12998 | |
12999 | if (LHSType->isQueueT() && RHSType->isQueueT()) { |
13000 | return computeResultTy(); |
13001 | } |
13002 | |
13003 | if (LHSIsNull && RHSType->isQueueT()) { |
13004 | LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer); |
13005 | return computeResultTy(); |
13006 | } |
13007 | |
13008 | if (LHSType->isQueueT() && RHSIsNull) { |
13009 | RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer); |
13010 | return computeResultTy(); |
13011 | } |
13012 | } |
13013 | |
13014 | return InvalidOperands(Loc, LHS, RHS); |
13015 | } |
13016 | |
13017 | QualType Sema::GetSignedVectorType(QualType V) { |
13018 | const VectorType *VTy = V->castAs<VectorType>(); |
13019 | unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType()); |
13020 | |
13021 | if (isa<ExtVectorType>(Val: VTy)) { |
13022 | if (VTy->isExtVectorBoolType()) |
13023 | return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements()); |
13024 | if (TypeSize == Context.getTypeSize(Context.CharTy)) |
13025 | return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements()); |
13026 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) |
13027 | return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements()); |
13028 | if (TypeSize == Context.getTypeSize(Context.IntTy)) |
13029 | return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements()); |
13030 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) |
13031 | return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements()); |
13032 | if (TypeSize == Context.getTypeSize(Context.LongTy)) |
13033 | return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements()); |
13034 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && |
13035 | "Unhandled vector element size in vector compare"); |
13036 | return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements()); |
13037 | } |
13038 | |
13039 | if (TypeSize == Context.getTypeSize(Context.Int128Ty)) |
13040 | return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(), |
13041 | VecKind: VectorKind::Generic); |
13042 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) |
13043 | return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(), |
13044 | VecKind: VectorKind::Generic); |
13045 | if (TypeSize == Context.getTypeSize(Context.LongTy)) |
13046 | return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(), |
13047 | VecKind: VectorKind::Generic); |
13048 | if (TypeSize == Context.getTypeSize(Context.IntTy)) |
13049 | return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(), |
13050 | VecKind: VectorKind::Generic); |
13051 | if (TypeSize == Context.getTypeSize(Context.ShortTy)) |
13052 | return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(), |
13053 | VecKind: VectorKind::Generic); |
13054 | assert(TypeSize == Context.getTypeSize(Context.CharTy) && |
13055 | "Unhandled vector element size in vector compare"); |
13056 | return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(), |
13057 | VecKind: VectorKind::Generic); |
13058 | } |
13059 | |
13060 | QualType Sema::GetSignedSizelessVectorType(QualType V) { |
13061 | const BuiltinType *VTy = V->castAs<BuiltinType>(); |
13062 | assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); |
13063 | |
13064 | const QualType ETy = V->getSveEltType(Ctx: Context); |
13065 | const auto TypeSize = Context.getTypeSize(T: ETy); |
13066 | |
13067 | const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true); |
13068 | const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC; |
13069 | return Context.getScalableVectorType(EltTy: IntTy, NumElts: VecSize.getKnownMinValue()); |
13070 | } |
13071 | |
13072 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
13073 | SourceLocation Loc, |
13074 | BinaryOperatorKind Opc) { |
13075 | if (Opc == BO_Cmp) { |
13076 | Diag(Loc, diag::err_three_way_vector_comparison); |
13077 | return QualType(); |
13078 | } |
13079 | |
13080 | // Check to make sure we're operating on vectors of the same type and width, |
13081 | // Allowing one side to be a scalar of element type. |
13082 | QualType vType = |
13083 | CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, |
13084 | /*AllowBothBool*/ true, |
13085 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
13086 | /*AllowBooleanOperation*/ AllowBoolOperation: true, |
13087 | /*ReportInvalid*/ true); |
13088 | if (vType.isNull()) |
13089 | return vType; |
13090 | |
13091 | QualType LHSType = LHS.get()->getType(); |
13092 | |
13093 | // Determine the return type of a vector compare. By default clang will return |
13094 | // a scalar for all vector compares except vector bool and vector pixel. |
13095 | // With the gcc compiler we will always return a vector type and with the xl |
13096 | // compiler we will always return a scalar type. This switch allows choosing |
13097 | // which behavior is prefered. |
13098 | if (getLangOpts().AltiVec) { |
13099 | switch (getLangOpts().getAltivecSrcCompat()) { |
13100 | case LangOptions::AltivecSrcCompatKind::Mixed: |
13101 | // If AltiVec, the comparison results in a numeric type, i.e. |
13102 | // bool for C++, int for C |
13103 | if (vType->castAs<VectorType>()->getVectorKind() == |
13104 | VectorKind::AltiVecVector) |
13105 | return Context.getLogicalOperationType(); |
13106 | else |
13107 | Diag(Loc, diag::warn_deprecated_altivec_src_compat); |
13108 | break; |
13109 | case LangOptions::AltivecSrcCompatKind::GCC: |
13110 | // For GCC we always return the vector type. |
13111 | break; |
13112 | case LangOptions::AltivecSrcCompatKind::XL: |
13113 | return Context.getLogicalOperationType(); |
13114 | break; |
13115 | } |
13116 | } |
13117 | |
13118 | // For non-floating point types, check for self-comparisons of the form |
13119 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
13120 | // often indicate logic errors in the program. |
13121 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
13122 | |
13123 | // Check for comparisons of floating point operands using != and ==. |
13124 | if (LHSType->hasFloatingRepresentation()) { |
13125 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
13126 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
13127 | } |
13128 | |
13129 | // Return a signed type for the vector. |
13130 | return GetSignedVectorType(V: vType); |
13131 | } |
13132 | |
13133 | QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, |
13134 | ExprResult &RHS, |
13135 | SourceLocation Loc, |
13136 | BinaryOperatorKind Opc) { |
13137 | if (Opc == BO_Cmp) { |
13138 | Diag(Loc, diag::err_three_way_vector_comparison); |
13139 | return QualType(); |
13140 | } |
13141 | |
13142 | // Check to make sure we're operating on vectors of the same type and width, |
13143 | // Allowing one side to be a scalar of element type. |
13144 | QualType vType = CheckSizelessVectorOperands( |
13145 | LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: ArithConvKind::Comparison); |
13146 | |
13147 | if (vType.isNull()) |
13148 | return vType; |
13149 | |
13150 | QualType LHSType = LHS.get()->getType(); |
13151 | |
13152 | // For non-floating point types, check for self-comparisons of the form |
13153 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
13154 | // often indicate logic errors in the program. |
13155 | diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: RHS.get(), Opc); |
13156 | |
13157 | // Check for comparisons of floating point operands using != and ==. |
13158 | if (LHSType->hasFloatingRepresentation()) { |
13159 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
13160 | CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc); |
13161 | } |
13162 | |
13163 | const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); |
13164 | const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); |
13165 | |
13166 | if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && |
13167 | RHSBuiltinTy->isSVEBool()) |
13168 | return LHSType; |
13169 | |
13170 | // Return a signed type for the vector. |
13171 | return GetSignedSizelessVectorType(V: vType); |
13172 | } |
13173 | |
13174 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, |
13175 | const ExprResult &XorRHS, |
13176 | const SourceLocation Loc) { |
13177 | // Do not diagnose macros. |
13178 | if (Loc.isMacroID()) |
13179 | return; |
13180 | |
13181 | // Do not diagnose if both LHS and RHS are macros. |
13182 | if (XorLHS.get()->getExprLoc().isMacroID() && |
13183 | XorRHS.get()->getExprLoc().isMacroID()) |
13184 | return; |
13185 | |
13186 | bool Negative = false; |
13187 | bool ExplicitPlus = false; |
13188 | const auto *LHSInt = dyn_cast<IntegerLiteral>(Val: XorLHS.get()); |
13189 | const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get()); |
13190 | |
13191 | if (!LHSInt) |
13192 | return; |
13193 | if (!RHSInt) { |
13194 | // Check negative literals. |
13195 | if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) { |
13196 | UnaryOperatorKind Opc = UO->getOpcode(); |
13197 | if (Opc != UO_Minus && Opc != UO_Plus) |
13198 | return; |
13199 | RHSInt = dyn_cast<IntegerLiteral>(Val: UO->getSubExpr()); |
13200 | if (!RHSInt) |
13201 | return; |
13202 | Negative = (Opc == UO_Minus); |
13203 | ExplicitPlus = !Negative; |
13204 | } else { |
13205 | return; |
13206 | } |
13207 | } |
13208 | |
13209 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); |
13210 | llvm::APInt RightSideValue = RHSInt->getValue(); |
13211 | if (LeftSideValue != 2 && LeftSideValue != 10) |
13212 | return; |
13213 | |
13214 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) |
13215 | return; |
13216 | |
13217 | CharSourceRange ExprRange = CharSourceRange::getCharRange( |
13218 | B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation())); |
13219 | llvm::StringRef ExprStr = |
13220 | Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
13221 | |
13222 | CharSourceRange XorRange = |
13223 | CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc)); |
13224 | llvm::StringRef XorStr = |
13225 | Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts()); |
13226 | // Do not diagnose if xor keyword/macro is used. |
13227 | if (XorStr == "xor") |
13228 | return; |
13229 | |
13230 | std::string LHSStr = std::string(Lexer::getSourceText( |
13231 | Range: CharSourceRange::getTokenRange(LHSInt->getSourceRange()), |
13232 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
13233 | std::string RHSStr = std::string(Lexer::getSourceText( |
13234 | Range: CharSourceRange::getTokenRange(RHSInt->getSourceRange()), |
13235 | SM: S.getSourceManager(), LangOpts: S.getLangOpts())); |
13236 | |
13237 | if (Negative) { |
13238 | RightSideValue = -RightSideValue; |
13239 | RHSStr = "-"+ RHSStr; |
13240 | } else if (ExplicitPlus) { |
13241 | RHSStr = "+"+ RHSStr; |
13242 | } |
13243 | |
13244 | StringRef LHSStrRef = LHSStr; |
13245 | StringRef RHSStrRef = RHSStr; |
13246 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal |
13247 | // literals. |
13248 | if (LHSStrRef.starts_with(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") || |
13249 | RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") || |
13250 | LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") || |
13251 | RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") || |
13252 | (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) || |
13253 | (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) || |
13254 | LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\'')) |
13255 | return; |
13256 | |
13257 | bool SuggestXor = |
13258 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "xor"); |
13259 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; |
13260 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); |
13261 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { |
13262 | std::string SuggestedExpr = "1 << "+ RHSStr; |
13263 | bool Overflow = false; |
13264 | llvm::APInt One = (LeftSideValue - 1); |
13265 | llvm::APInt PowValue = One.sshl_ov(Amt: RightSideValue, Overflow); |
13266 | if (Overflow) { |
13267 | if (RightSideIntValue < 64) |
13268 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) |
13269 | << ExprStr << toString(XorValue, 10, true) << ("1LL << "+ RHSStr) |
13270 | << FixItHint::CreateReplacement(ExprRange, "1LL << "+ RHSStr); |
13271 | else if (RightSideIntValue == 64) |
13272 | S.Diag(Loc, diag::warn_xor_used_as_pow) |
13273 | << ExprStr << toString(XorValue, 10, true); |
13274 | else |
13275 | return; |
13276 | } else { |
13277 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) |
13278 | << ExprStr << toString(XorValue, 10, true) << SuggestedExpr |
13279 | << toString(PowValue, 10, true) |
13280 | << FixItHint::CreateReplacement( |
13281 | ExprRange, (RightSideIntValue == 0) ? "1": SuggestedExpr); |
13282 | } |
13283 | |
13284 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) |
13285 | << ("0x2 ^ "+ RHSStr) << SuggestXor; |
13286 | } else if (LeftSideValue == 10) { |
13287 | std::string SuggestedValue = "1e"+ std::to_string(val: RightSideIntValue); |
13288 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) |
13289 | << ExprStr << toString(XorValue, 10, true) << SuggestedValue |
13290 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); |
13291 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) |
13292 | << ("0xA ^ "+ RHSStr) << SuggestXor; |
13293 | } |
13294 | } |
13295 | |
13296 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
13297 | SourceLocation Loc, |
13298 | BinaryOperatorKind Opc) { |
13299 | // Ensure that either both operands are of the same vector type, or |
13300 | // one operand is of a vector type and the other is of its element type. |
13301 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, IsCompAssign: false, |
13302 | /*AllowBothBool*/ true, |
13303 | /*AllowBoolConversions*/ false, |
13304 | /*AllowBooleanOperation*/ AllowBoolOperation: false, |
13305 | /*ReportInvalid*/ false); |
13306 | if (vType.isNull()) |
13307 | return InvalidOperands(Loc, LHS, RHS); |
13308 | if (getLangOpts().OpenCL && |
13309 | getLangOpts().getOpenCLCompatibleVersion() < 120 && |
13310 | vType->hasFloatingRepresentation()) |
13311 | return InvalidOperands(Loc, LHS, RHS); |
13312 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the |
13313 | // usage of the logical operators && and || with vectors in C. This |
13314 | // check could be notionally dropped. |
13315 | if (!getLangOpts().CPlusPlus && |
13316 | !(isa<ExtVectorType>(Val: vType->getAs<VectorType>()))) |
13317 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); |
13318 | // Beginning with HLSL 2021, HLSL disallows logical operators on vector |
13319 | // operands and instead requires the use of the `and`, `or`, `any`, `all`, and |
13320 | // `select` functions. |
13321 | if (getLangOpts().HLSL && |
13322 | getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) { |
13323 | (void)InvalidOperands(Loc, LHS, RHS); |
13324 | HLSL().emitLogicalOperatorFixIt(LHS: LHS.get(), RHS: RHS.get(), Opc); |
13325 | return QualType(); |
13326 | } |
13327 | |
13328 | return GetSignedVectorType(V: LHS.get()->getType()); |
13329 | } |
13330 | |
13331 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, |
13332 | SourceLocation Loc, |
13333 | bool IsCompAssign) { |
13334 | if (!IsCompAssign) { |
13335 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
13336 | if (LHS.isInvalid()) |
13337 | return QualType(); |
13338 | } |
13339 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
13340 | if (RHS.isInvalid()) |
13341 | return QualType(); |
13342 | |
13343 | // For conversion purposes, we ignore any qualifiers. |
13344 | // For example, "const float" and "float" are equivalent. |
13345 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
13346 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
13347 | |
13348 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); |
13349 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); |
13350 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); |
13351 | |
13352 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
13353 | return Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
13354 | |
13355 | // Type conversion may change LHS/RHS. Keep copies to the original results, in |
13356 | // case we have to return InvalidOperands. |
13357 | ExprResult OriginalLHS = LHS; |
13358 | ExprResult OriginalRHS = RHS; |
13359 | if (LHSMatType && !RHSMatType) { |
13360 | RHS = tryConvertExprToType(E: RHS.get(), Ty: LHSMatType->getElementType()); |
13361 | if (!RHS.isInvalid()) |
13362 | return LHSType; |
13363 | |
13364 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
13365 | } |
13366 | |
13367 | if (!LHSMatType && RHSMatType) { |
13368 | LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType()); |
13369 | if (!LHS.isInvalid()) |
13370 | return RHSType; |
13371 | return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS); |
13372 | } |
13373 | |
13374 | return InvalidOperands(Loc, LHS, RHS); |
13375 | } |
13376 | |
13377 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, |
13378 | SourceLocation Loc, |
13379 | bool IsCompAssign) { |
13380 | if (!IsCompAssign) { |
13381 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
13382 | if (LHS.isInvalid()) |
13383 | return QualType(); |
13384 | } |
13385 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
13386 | if (RHS.isInvalid()) |
13387 | return QualType(); |
13388 | |
13389 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); |
13390 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); |
13391 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); |
13392 | |
13393 | if (LHSMatType && RHSMatType) { |
13394 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) |
13395 | return InvalidOperands(Loc, LHS, RHS); |
13396 | |
13397 | if (Context.hasSameType(LHSMatType, RHSMatType)) |
13398 | return Context.getCommonSugaredType( |
13399 | X: LHS.get()->getType().getUnqualifiedType(), |
13400 | Y: RHS.get()->getType().getUnqualifiedType()); |
13401 | |
13402 | QualType LHSELTy = LHSMatType->getElementType(), |
13403 | RHSELTy = RHSMatType->getElementType(); |
13404 | if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy)) |
13405 | return InvalidOperands(Loc, LHS, RHS); |
13406 | |
13407 | return Context.getConstantMatrixType( |
13408 | ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy), |
13409 | NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns()); |
13410 | } |
13411 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); |
13412 | } |
13413 | |
13414 | static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { |
13415 | switch (Opc) { |
13416 | default: |
13417 | return false; |
13418 | case BO_And: |
13419 | case BO_AndAssign: |
13420 | case BO_Or: |
13421 | case BO_OrAssign: |
13422 | case BO_Xor: |
13423 | case BO_XorAssign: |
13424 | return true; |
13425 | } |
13426 | } |
13427 | |
13428 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, |
13429 | SourceLocation Loc, |
13430 | BinaryOperatorKind Opc) { |
13431 | checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false); |
13432 | |
13433 | bool IsCompAssign = |
13434 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; |
13435 | |
13436 | bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); |
13437 | |
13438 | if (LHS.get()->getType()->isVectorType() || |
13439 | RHS.get()->getType()->isVectorType()) { |
13440 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
13441 | RHS.get()->getType()->hasIntegerRepresentation()) |
13442 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
13443 | /*AllowBothBool*/ true, |
13444 | /*AllowBoolConversions*/ getLangOpts().ZVector, |
13445 | /*AllowBooleanOperation*/ AllowBoolOperation: LegalBoolVecOperator, |
13446 | /*ReportInvalid*/ true); |
13447 | return InvalidOperands(Loc, LHS, RHS); |
13448 | } |
13449 | |
13450 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
13451 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
13452 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
13453 | RHS.get()->getType()->hasIntegerRepresentation()) |
13454 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
13455 | OperationKind: ArithConvKind::BitwiseOp); |
13456 | return InvalidOperands(Loc, LHS, RHS); |
13457 | } |
13458 | |
13459 | if (LHS.get()->getType()->isSveVLSBuiltinType() || |
13460 | RHS.get()->getType()->isSveVLSBuiltinType()) { |
13461 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
13462 | RHS.get()->getType()->hasIntegerRepresentation()) |
13463 | return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, |
13464 | OperationKind: ArithConvKind::BitwiseOp); |
13465 | return InvalidOperands(Loc, LHS, RHS); |
13466 | } |
13467 | |
13468 | if (Opc == BO_And) |
13469 | diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc); |
13470 | |
13471 | if (LHS.get()->getType()->hasFloatingRepresentation() || |
13472 | RHS.get()->getType()->hasFloatingRepresentation()) |
13473 | return InvalidOperands(Loc, LHS, RHS); |
13474 | |
13475 | ExprResult LHSResult = LHS, RHSResult = RHS; |
13476 | QualType compType = UsualArithmeticConversions( |
13477 | LHS&: LHSResult, RHS&: RHSResult, Loc, |
13478 | ACK: IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp); |
13479 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) |
13480 | return QualType(); |
13481 | LHS = LHSResult.get(); |
13482 | RHS = RHSResult.get(); |
13483 | |
13484 | if (Opc == BO_Xor) |
13485 | diagnoseXorMisusedAsPow(S&: *this, XorLHS: LHS, XorRHS: RHS, Loc); |
13486 | |
13487 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) |
13488 | return compType; |
13489 | return InvalidOperands(Loc, LHS, RHS); |
13490 | } |
13491 | |
13492 | // C99 6.5.[13,14] |
13493 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
13494 | SourceLocation Loc, |
13495 | BinaryOperatorKind Opc) { |
13496 | // Check vector operands differently. |
13497 | if (LHS.get()->getType()->isVectorType() || |
13498 | RHS.get()->getType()->isVectorType()) |
13499 | return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc); |
13500 | |
13501 | bool EnumConstantInBoolContext = false; |
13502 | for (const ExprResult &HS : {LHS, RHS}) { |
13503 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(Val: HS.get())) { |
13504 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: DREHS->getDecl()); |
13505 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) |
13506 | EnumConstantInBoolContext = true; |
13507 | } |
13508 | } |
13509 | |
13510 | if (EnumConstantInBoolContext) |
13511 | Diag(Loc, diag::warn_enum_constant_in_bool_context); |
13512 | |
13513 | // WebAssembly tables can't be used with logical operators. |
13514 | QualType LHSTy = LHS.get()->getType(); |
13515 | QualType RHSTy = RHS.get()->getType(); |
13516 | const auto *LHSATy = dyn_cast<ArrayType>(Val&: LHSTy); |
13517 | const auto *RHSATy = dyn_cast<ArrayType>(Val&: RHSTy); |
13518 | if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) || |
13519 | (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) { |
13520 | return InvalidOperands(Loc, LHS, RHS); |
13521 | } |
13522 | |
13523 | // Diagnose cases where the user write a logical and/or but probably meant a |
13524 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS |
13525 | // is a constant. |
13526 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && |
13527 | !LHS.get()->getType()->isBooleanType() && |
13528 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && |
13529 | // Don't warn in macros or template instantiations. |
13530 | !Loc.isMacroID() && !inTemplateInstantiation()) { |
13531 | // If the RHS can be constant folded, and if it constant folds to something |
13532 | // that isn't 0 or 1 (which indicate a potential logical operation that |
13533 | // happened to fold to true/false) then warn. |
13534 | // Parens on the RHS are ignored. |
13535 | Expr::EvalResult EVResult; |
13536 | if (RHS.get()->EvaluateAsInt(Result&: EVResult, Ctx: Context)) { |
13537 | llvm::APSInt Result = EVResult.Val.getInt(); |
13538 | if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() && |
13539 | !RHS.get()->getExprLoc().isMacroID()) || |
13540 | (Result != 0 && Result != 1)) { |
13541 | Diag(Loc, diag::warn_logical_instead_of_bitwise) |
13542 | << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&": "||"); |
13543 | // Suggest replacing the logical operator with the bitwise version |
13544 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) |
13545 | << (Opc == BO_LAnd ? "&": "|") |
13546 | << FixItHint::CreateReplacement( |
13547 | SourceRange(Loc, getLocForEndOfToken(Loc)), |
13548 | Opc == BO_LAnd ? "&": "|"); |
13549 | if (Opc == BO_LAnd) |
13550 | // Suggest replacing "Foo() && kNonZero" with "Foo()" |
13551 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) |
13552 | << FixItHint::CreateRemoval( |
13553 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), |
13554 | RHS.get()->getEndLoc())); |
13555 | } |
13556 | } |
13557 | } |
13558 | |
13559 | if (!Context.getLangOpts().CPlusPlus) { |
13560 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do |
13561 | // not operate on the built-in scalar and vector float types. |
13562 | if (Context.getLangOpts().OpenCL && |
13563 | Context.getLangOpts().OpenCLVersion < 120) { |
13564 | if (LHS.get()->getType()->isFloatingType() || |
13565 | RHS.get()->getType()->isFloatingType()) |
13566 | return InvalidOperands(Loc, LHS, RHS); |
13567 | } |
13568 | |
13569 | LHS = UsualUnaryConversions(E: LHS.get()); |
13570 | if (LHS.isInvalid()) |
13571 | return QualType(); |
13572 | |
13573 | RHS = UsualUnaryConversions(E: RHS.get()); |
13574 | if (RHS.isInvalid()) |
13575 | return QualType(); |
13576 | |
13577 | if (!LHS.get()->getType()->isScalarType() || |
13578 | !RHS.get()->getType()->isScalarType()) |
13579 | return InvalidOperands(Loc, LHS, RHS); |
13580 | |
13581 | return Context.IntTy; |
13582 | } |
13583 | |
13584 | // The following is safe because we only use this method for |
13585 | // non-overloadable operands. |
13586 | |
13587 | // C++ [expr.log.and]p1 |
13588 | // C++ [expr.log.or]p1 |
13589 | // The operands are both contextually converted to type bool. |
13590 | ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get()); |
13591 | if (LHSRes.isInvalid()) |
13592 | return InvalidOperands(Loc, LHS, RHS); |
13593 | LHS = LHSRes; |
13594 | |
13595 | ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get()); |
13596 | if (RHSRes.isInvalid()) |
13597 | return InvalidOperands(Loc, LHS, RHS); |
13598 | RHS = RHSRes; |
13599 | |
13600 | // C++ [expr.log.and]p2 |
13601 | // C++ [expr.log.or]p2 |
13602 | // The result is a bool. |
13603 | return Context.BoolTy; |
13604 | } |
13605 | |
13606 | static bool IsReadonlyMessage(Expr *E, Sema &S) { |
13607 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
13608 | if (!ME) return false; |
13609 | if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false; |
13610 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( |
13611 | Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); |
13612 | if (!Base) return false; |
13613 | return Base->getMethodDecl() != nullptr; |
13614 | } |
13615 | |
13616 | /// Is the given expression (which must be 'const') a reference to a |
13617 | /// variable which was originally non-const, but which has become |
13618 | /// 'const' due to being captured within a block? |
13619 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; |
13620 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { |
13621 | assert(E->isLValue() && E->getType().isConstQualified()); |
13622 | E = E->IgnoreParens(); |
13623 | |
13624 | // Must be a reference to a declaration from an enclosing scope. |
13625 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
13626 | if (!DRE) return NCCK_None; |
13627 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; |
13628 | |
13629 | ValueDecl *Value = dyn_cast<ValueDecl>(Val: DRE->getDecl()); |
13630 | |
13631 | // The declaration must be a value which is not declared 'const'. |
13632 | if (!Value || Value->getType().isConstQualified()) |
13633 | return NCCK_None; |
13634 | |
13635 | BindingDecl *Binding = dyn_cast<BindingDecl>(Val: Value); |
13636 | if (Binding) { |
13637 | assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?"); |
13638 | assert(!isa<BlockDecl>(Binding->getDeclContext())); |
13639 | return NCCK_Lambda; |
13640 | } |
13641 | |
13642 | VarDecl *Var = dyn_cast<VarDecl>(Val: Value); |
13643 | if (!Var) |
13644 | return NCCK_None; |
13645 | |
13646 | assert(Var->hasLocalStorage() && "capture added 'const' to non-local?"); |
13647 | |
13648 | // Decide whether the first capture was for a block or a lambda. |
13649 | DeclContext *DC = S.CurContext, *Prev = nullptr; |
13650 | // Decide whether the first capture was for a block or a lambda. |
13651 | while (DC) { |
13652 | // For init-capture, it is possible that the variable belongs to the |
13653 | // template pattern of the current context. |
13654 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DC)) |
13655 | if (Var->isInitCapture() && |
13656 | FD->getTemplateInstantiationPattern() == Var->getDeclContext()) |
13657 | break; |
13658 | if (DC == Var->getDeclContext()) |
13659 | break; |
13660 | Prev = DC; |
13661 | DC = DC->getParent(); |
13662 | } |
13663 | // Unless we have an init-capture, we've gone one step too far. |
13664 | if (!Var->isInitCapture()) |
13665 | DC = Prev; |
13666 | return (isa<BlockDecl>(Val: DC) ? NCCK_Block : NCCK_Lambda); |
13667 | } |
13668 | |
13669 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { |
13670 | Ty = Ty.getNonReferenceType(); |
13671 | if (IsDereference && Ty->isPointerType()) |
13672 | Ty = Ty->getPointeeType(); |
13673 | return !Ty.isConstQualified(); |
13674 | } |
13675 | |
13676 | // Update err_typecheck_assign_const and note_typecheck_assign_const |
13677 | // when this enum is changed. |
13678 | enum { |
13679 | ConstFunction, |
13680 | ConstVariable, |
13681 | ConstMember, |
13682 | ConstMethod, |
13683 | NestedConstMember, |
13684 | ConstUnknown, // Keep as last element |
13685 | }; |
13686 | |
13687 | /// Emit the "read-only variable not assignable" error and print notes to give |
13688 | /// more information about why the variable is not assignable, such as pointing |
13689 | /// to the declaration of a const variable, showing that a method is const, or |
13690 | /// that the function is returning a const reference. |
13691 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, |
13692 | SourceLocation Loc) { |
13693 | SourceRange ExprRange = E->getSourceRange(); |
13694 | |
13695 | // Only emit one error on the first const found. All other consts will emit |
13696 | // a note to the error. |
13697 | bool DiagnosticEmitted = false; |
13698 | |
13699 | // Track if the current expression is the result of a dereference, and if the |
13700 | // next checked expression is the result of a dereference. |
13701 | bool IsDereference = false; |
13702 | bool NextIsDereference = false; |
13703 | |
13704 | // Loop to process MemberExpr chains. |
13705 | while (true) { |
13706 | IsDereference = NextIsDereference; |
13707 | |
13708 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); |
13709 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) { |
13710 | NextIsDereference = ME->isArrow(); |
13711 | const ValueDecl *VD = ME->getMemberDecl(); |
13712 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: VD)) { |
13713 | // Mutable fields can be modified even if the class is const. |
13714 | if (Field->isMutable()) { |
13715 | assert(DiagnosticEmitted && "Expected diagnostic not emitted."); |
13716 | break; |
13717 | } |
13718 | |
13719 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { |
13720 | if (!DiagnosticEmitted) { |
13721 | S.Diag(Loc, diag::err_typecheck_assign_const) |
13722 | << ExprRange << ConstMember << false /*static*/ << Field |
13723 | << Field->getType(); |
13724 | DiagnosticEmitted = true; |
13725 | } |
13726 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
13727 | << ConstMember << false /*static*/ << Field << Field->getType() |
13728 | << Field->getSourceRange(); |
13729 | } |
13730 | E = ME->getBase(); |
13731 | continue; |
13732 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: VD)) { |
13733 | if (VDecl->getType().isConstQualified()) { |
13734 | if (!DiagnosticEmitted) { |
13735 | S.Diag(Loc, diag::err_typecheck_assign_const) |
13736 | << ExprRange << ConstMember << true /*static*/ << VDecl |
13737 | << VDecl->getType(); |
13738 | DiagnosticEmitted = true; |
13739 | } |
13740 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
13741 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() |
13742 | << VDecl->getSourceRange(); |
13743 | } |
13744 | // Static fields do not inherit constness from parents. |
13745 | break; |
13746 | } |
13747 | break; // End MemberExpr |
13748 | } else if (const ArraySubscriptExpr *ASE = |
13749 | dyn_cast<ArraySubscriptExpr>(Val: E)) { |
13750 | E = ASE->getBase()->IgnoreParenImpCasts(); |
13751 | continue; |
13752 | } else if (const ExtVectorElementExpr *EVE = |
13753 | dyn_cast<ExtVectorElementExpr>(Val: E)) { |
13754 | E = EVE->getBase()->IgnoreParenImpCasts(); |
13755 | continue; |
13756 | } |
13757 | break; |
13758 | } |
13759 | |
13760 | if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) { |
13761 | // Function calls |
13762 | const FunctionDecl *FD = CE->getDirectCallee(); |
13763 | if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) { |
13764 | if (!DiagnosticEmitted) { |
13765 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange |
13766 | << ConstFunction << FD; |
13767 | DiagnosticEmitted = true; |
13768 | } |
13769 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), |
13770 | diag::note_typecheck_assign_const) |
13771 | << ConstFunction << FD << FD->getReturnType() |
13772 | << FD->getReturnTypeSourceRange(); |
13773 | } |
13774 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
13775 | // Point to variable declaration. |
13776 | if (const ValueDecl *VD = DRE->getDecl()) { |
13777 | if (!IsTypeModifiable(Ty: VD->getType(), IsDereference)) { |
13778 | if (!DiagnosticEmitted) { |
13779 | S.Diag(Loc, diag::err_typecheck_assign_const) |
13780 | << ExprRange << ConstVariable << VD << VD->getType(); |
13781 | DiagnosticEmitted = true; |
13782 | } |
13783 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
13784 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); |
13785 | } |
13786 | } |
13787 | } else if (isa<CXXThisExpr>(Val: E)) { |
13788 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { |
13789 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: DC)) { |
13790 | if (MD->isConst()) { |
13791 | if (!DiagnosticEmitted) { |
13792 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange |
13793 | << ConstMethod << MD; |
13794 | DiagnosticEmitted = true; |
13795 | } |
13796 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) |
13797 | << ConstMethod << MD << MD->getSourceRange(); |
13798 | } |
13799 | } |
13800 | } |
13801 | } |
13802 | |
13803 | if (DiagnosticEmitted) |
13804 | return; |
13805 | |
13806 | // Can't determine a more specific message, so display the generic error. |
13807 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; |
13808 | } |
13809 | |
13810 | enum OriginalExprKind { |
13811 | OEK_Variable, |
13812 | OEK_Member, |
13813 | OEK_LValue |
13814 | }; |
13815 | |
13816 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, |
13817 | const RecordType *Ty, |
13818 | SourceLocation Loc, SourceRange Range, |
13819 | OriginalExprKind OEK, |
13820 | bool &DiagnosticEmitted) { |
13821 | std::vector<const RecordType *> RecordTypeList; |
13822 | RecordTypeList.push_back(x: Ty); |
13823 | unsigned NextToCheckIndex = 0; |
13824 | // We walk the record hierarchy breadth-first to ensure that we print |
13825 | // diagnostics in field nesting order. |
13826 | while (RecordTypeList.size() > NextToCheckIndex) { |
13827 | bool IsNested = NextToCheckIndex > 0; |
13828 | for (const FieldDecl *Field : |
13829 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { |
13830 | // First, check every field for constness. |
13831 | QualType FieldTy = Field->getType(); |
13832 | if (FieldTy.isConstQualified()) { |
13833 | if (!DiagnosticEmitted) { |
13834 | S.Diag(Loc, diag::err_typecheck_assign_const) |
13835 | << Range << NestedConstMember << OEK << VD |
13836 | << IsNested << Field; |
13837 | DiagnosticEmitted = true; |
13838 | } |
13839 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) |
13840 | << NestedConstMember << IsNested << Field |
13841 | << FieldTy << Field->getSourceRange(); |
13842 | } |
13843 | |
13844 | // Then we append it to the list to check next in order. |
13845 | FieldTy = FieldTy.getCanonicalType(); |
13846 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { |
13847 | if (!llvm::is_contained(RecordTypeList, FieldRecTy)) |
13848 | RecordTypeList.push_back(FieldRecTy); |
13849 | } |
13850 | } |
13851 | ++NextToCheckIndex; |
13852 | } |
13853 | } |
13854 | |
13855 | /// Emit an error for the case where a record we are trying to assign to has a |
13856 | /// const-qualified field somewhere in its hierarchy. |
13857 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, |
13858 | SourceLocation Loc) { |
13859 | QualType Ty = E->getType(); |
13860 | assert(Ty->isRecordType() && "lvalue was not record?"); |
13861 | SourceRange Range = E->getSourceRange(); |
13862 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); |
13863 | bool DiagEmitted = false; |
13864 | |
13865 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) |
13866 | DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc, |
13867 | Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted); |
13868 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
13869 | DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc, |
13870 | Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted); |
13871 | else |
13872 | DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc, |
13873 | Range, OEK: OEK_LValue, DiagnosticEmitted&: DiagEmitted); |
13874 | if (!DiagEmitted) |
13875 | DiagnoseConstAssignment(S, E, Loc); |
13876 | } |
13877 | |
13878 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, |
13879 | /// emit an error and return true. If so, return false. |
13880 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { |
13881 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); |
13882 | |
13883 | S.CheckShadowingDeclModification(E, Loc); |
13884 | |
13885 | SourceLocation OrigLoc = Loc; |
13886 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context, |
13887 | Loc: &Loc); |
13888 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) |
13889 | IsLV = Expr::MLV_InvalidMessageExpression; |
13890 | if (IsLV == Expr::MLV_Valid) |
13891 | return false; |
13892 | |
13893 | unsigned DiagID = 0; |
13894 | bool NeedType = false; |
13895 | switch (IsLV) { // C99 6.5.16p2 |
13896 | case Expr::MLV_ConstQualified: |
13897 | // Use a specialized diagnostic when we're assigning to an object |
13898 | // from an enclosing function or block. |
13899 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { |
13900 | if (NCCK == NCCK_Block) |
13901 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; |
13902 | else |
13903 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; |
13904 | break; |
13905 | } |
13906 | |
13907 | // In ARC, use some specialized diagnostics for occasions where we |
13908 | // infer 'const'. These are always pseudo-strong variables. |
13909 | if (S.getLangOpts().ObjCAutoRefCount) { |
13910 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()); |
13911 | if (declRef && isa<VarDecl>(Val: declRef->getDecl())) { |
13912 | VarDecl *var = cast<VarDecl>(Val: declRef->getDecl()); |
13913 | |
13914 | // Use the normal diagnostic if it's pseudo-__strong but the |
13915 | // user actually wrote 'const'. |
13916 | if (var->isARCPseudoStrong() && |
13917 | (!var->getTypeSourceInfo() || |
13918 | !var->getTypeSourceInfo()->getType().isConstQualified())) { |
13919 | // There are three pseudo-strong cases: |
13920 | // - self |
13921 | ObjCMethodDecl *method = S.getCurMethodDecl(); |
13922 | if (method && var == method->getSelfDecl()) { |
13923 | DiagID = method->isClassMethod() |
13924 | ? diag::err_typecheck_arc_assign_self_class_method |
13925 | : diag::err_typecheck_arc_assign_self; |
13926 | |
13927 | // - Objective-C externally_retained attribute. |
13928 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || |
13929 | isa<ParmVarDecl>(var)) { |
13930 | DiagID = diag::err_typecheck_arc_assign_externally_retained; |
13931 | |
13932 | // - fast enumeration variables |
13933 | } else { |
13934 | DiagID = diag::err_typecheck_arr_assign_enumeration; |
13935 | } |
13936 | |
13937 | SourceRange Assign; |
13938 | if (Loc != OrigLoc) |
13939 | Assign = SourceRange(OrigLoc, OrigLoc); |
13940 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
13941 | // We need to preserve the AST regardless, so migration tool |
13942 | // can do its job. |
13943 | return false; |
13944 | } |
13945 | } |
13946 | } |
13947 | |
13948 | // If none of the special cases above are triggered, then this is a |
13949 | // simple const assignment. |
13950 | if (DiagID == 0) { |
13951 | DiagnoseConstAssignment(S, E, Loc); |
13952 | return true; |
13953 | } |
13954 | |
13955 | break; |
13956 | case Expr::MLV_ConstAddrSpace: |
13957 | DiagnoseConstAssignment(S, E, Loc); |
13958 | return true; |
13959 | case Expr::MLV_ConstQualifiedField: |
13960 | DiagnoseRecursiveConstFields(S, E, Loc); |
13961 | return true; |
13962 | case Expr::MLV_ArrayType: |
13963 | case Expr::MLV_ArrayTemporary: |
13964 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; |
13965 | NeedType = true; |
13966 | break; |
13967 | case Expr::MLV_NotObjectType: |
13968 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; |
13969 | NeedType = true; |
13970 | break; |
13971 | case Expr::MLV_LValueCast: |
13972 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; |
13973 | break; |
13974 | case Expr::MLV_Valid: |
13975 | llvm_unreachable("did not take early return for MLV_Valid"); |
13976 | case Expr::MLV_InvalidExpression: |
13977 | case Expr::MLV_MemberFunction: |
13978 | case Expr::MLV_ClassTemporary: |
13979 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; |
13980 | break; |
13981 | case Expr::MLV_IncompleteType: |
13982 | case Expr::MLV_IncompleteVoidType: |
13983 | return S.RequireCompleteType(Loc, E->getType(), |
13984 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); |
13985 | case Expr::MLV_DuplicateVectorComponents: |
13986 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; |
13987 | break; |
13988 | case Expr::MLV_NoSetterProperty: |
13989 | llvm_unreachable("readonly properties should be processed differently"); |
13990 | case Expr::MLV_InvalidMessageExpression: |
13991 | DiagID = diag::err_readonly_message_assignment; |
13992 | break; |
13993 | case Expr::MLV_SubObjCPropertySetting: |
13994 | DiagID = diag::err_no_subobject_property_setting; |
13995 | break; |
13996 | } |
13997 | |
13998 | SourceRange Assign; |
13999 | if (Loc != OrigLoc) |
14000 | Assign = SourceRange(OrigLoc, OrigLoc); |
14001 | if (NeedType) |
14002 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; |
14003 | else |
14004 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
14005 | return true; |
14006 | } |
14007 | |
14008 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, |
14009 | SourceLocation Loc, |
14010 | Sema &Sema) { |
14011 | if (Sema.inTemplateInstantiation()) |
14012 | return; |
14013 | if (Sema.isUnevaluatedContext()) |
14014 | return; |
14015 | if (Loc.isInvalid() || Loc.isMacroID()) |
14016 | return; |
14017 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) |
14018 | return; |
14019 | |
14020 | // C / C++ fields |
14021 | MemberExpr *ML = dyn_cast<MemberExpr>(Val: LHSExpr); |
14022 | MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr); |
14023 | if (ML && MR) { |
14024 | if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: MR->getBase()))) |
14025 | return; |
14026 | const ValueDecl *LHSDecl = |
14027 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); |
14028 | const ValueDecl *RHSDecl = |
14029 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); |
14030 | if (LHSDecl != RHSDecl) |
14031 | return; |
14032 | if (LHSDecl->getType().isVolatileQualified()) |
14033 | return; |
14034 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
14035 | if (RefTy->getPointeeType().isVolatileQualified()) |
14036 | return; |
14037 | |
14038 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; |
14039 | } |
14040 | |
14041 | // Objective-C instance variables |
14042 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(Val: LHSExpr); |
14043 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr); |
14044 | if (OL && OR && OL->getDecl() == OR->getDecl()) { |
14045 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts()); |
14046 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: OR->getBase()->IgnoreImpCasts()); |
14047 | if (RL && RR && RL->getDecl() == RR->getDecl()) |
14048 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; |
14049 | } |
14050 | } |
14051 | |
14052 | // C99 6.5.16.1 |
14053 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, |
14054 | SourceLocation Loc, |
14055 | QualType CompoundType, |
14056 | BinaryOperatorKind Opc) { |
14057 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); |
14058 | |
14059 | // Verify that LHS is a modifiable lvalue, and emit error if not. |
14060 | if (CheckForModifiableLvalue(E: LHSExpr, Loc, S&: *this)) |
14061 | return QualType(); |
14062 | |
14063 | QualType LHSType = LHSExpr->getType(); |
14064 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : |
14065 | CompoundType; |
14066 | |
14067 | if (RHS.isUsable()) { |
14068 | // Even if this check fails don't return early to allow the best |
14069 | // possible error recovery and to allow any subsequent diagnostics to |
14070 | // work. |
14071 | const ValueDecl *Assignee = nullptr; |
14072 | bool ShowFullyQualifiedAssigneeName = false; |
14073 | // In simple cases describe what is being assigned to |
14074 | if (auto *DR = dyn_cast<DeclRefExpr>(Val: LHSExpr->IgnoreParenCasts())) { |
14075 | Assignee = DR->getDecl(); |
14076 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHSExpr->IgnoreParenCasts())) { |
14077 | Assignee = ME->getMemberDecl(); |
14078 | ShowFullyQualifiedAssigneeName = true; |
14079 | } |
14080 | |
14081 | BoundsSafetyCheckAssignmentToCountAttrPtr( |
14082 | LHSTy: LHSType, RHSExpr: RHS.get(), Action: AssignmentAction::Assigning, Loc, Assignee, |
14083 | ShowFullyQualifiedAssigneeName); |
14084 | } |
14085 | |
14086 | // OpenCL v1.2 s6.1.1.1 p2: |
14087 | // The half data type can only be used to declare a pointer to a buffer that |
14088 | // contains half values |
14089 | if (getLangOpts().OpenCL && |
14090 | !getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: getLangOpts()) && |
14091 | LHSType->isHalfType()) { |
14092 | Diag(Loc, diag::err_opencl_half_load_store) << 1 |
14093 | << LHSType.getUnqualifiedType(); |
14094 | return QualType(); |
14095 | } |
14096 | |
14097 | // WebAssembly tables can't be used on RHS of an assignment expression. |
14098 | if (RHSType->isWebAssemblyTableType()) { |
14099 | Diag(Loc, diag::err_wasm_table_art) << 0; |
14100 | return QualType(); |
14101 | } |
14102 | |
14103 | AssignConvertType ConvTy; |
14104 | if (CompoundType.isNull()) { |
14105 | Expr *RHSCheck = RHS.get(); |
14106 | |
14107 | CheckIdentityFieldAssignment(LHSExpr, RHSExpr: RHSCheck, Loc, Sema&: *this); |
14108 | |
14109 | QualType LHSTy(LHSType); |
14110 | ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: RHS); |
14111 | if (RHS.isInvalid()) |
14112 | return QualType(); |
14113 | // Special case of NSObject attributes on c-style pointer types. |
14114 | if (ConvTy == AssignConvertType::IncompatiblePointer && |
14115 | ((Context.isObjCNSObjectType(Ty: LHSType) && |
14116 | RHSType->isObjCObjectPointerType()) || |
14117 | (Context.isObjCNSObjectType(Ty: RHSType) && |
14118 | LHSType->isObjCObjectPointerType()))) |
14119 | ConvTy = AssignConvertType::Compatible; |
14120 | |
14121 | if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType()) |
14122 | Diag(Loc, diag::err_objc_object_assignment) << LHSType; |
14123 | |
14124 | // If the RHS is a unary plus or minus, check to see if they = and + are |
14125 | // right next to each other. If so, the user may have typo'd "x =+ 4" |
14126 | // instead of "x += 4". |
14127 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: RHSCheck)) |
14128 | RHSCheck = ICE->getSubExpr(); |
14129 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: RHSCheck)) { |
14130 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && |
14131 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && |
14132 | // Only if the two operators are exactly adjacent. |
14133 | Loc.getLocWithOffset(Offset: 1) == UO->getOperatorLoc() && |
14134 | // And there is a space or other character before the subexpr of the |
14135 | // unary +/-. We don't want to warn on "x=-1". |
14136 | Loc.getLocWithOffset(Offset: 2) != UO->getSubExpr()->getBeginLoc() && |
14137 | UO->getSubExpr()->getBeginLoc().isFileID()) { |
14138 | Diag(Loc, diag::warn_not_compound_assign) |
14139 | << (UO->getOpcode() == UO_Plus ? "+": "-") |
14140 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); |
14141 | } |
14142 | } |
14143 | |
14144 | if (IsAssignConvertCompatible(ConvTy)) { |
14145 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { |
14146 | // Warn about retain cycles where a block captures the LHS, but |
14147 | // not if the LHS is a simple variable into which the block is |
14148 | // being stored...unless that variable can be captured by reference! |
14149 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); |
14150 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InnerLHS); |
14151 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) |
14152 | ObjC().checkRetainCycles(receiver: LHSExpr, argument: RHS.get()); |
14153 | } |
14154 | |
14155 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || |
14156 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { |
14157 | // It is safe to assign a weak reference into a strong variable. |
14158 | // Although this code can still have problems: |
14159 | // id x = self.weakProp; |
14160 | // id y = self.weakProp; |
14161 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
14162 | // paths through the function. This should be revisited if |
14163 | // -Wrepeated-use-of-weak is made flow-sensitive. |
14164 | // For ObjCWeak only, we do not warn if the assign is to a non-weak |
14165 | // variable, which will be valid for the current autorelease scope. |
14166 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, |
14167 | RHS.get()->getBeginLoc())) |
14168 | getCurFunction()->markSafeWeakUse(E: RHS.get()); |
14169 | |
14170 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { |
14171 | checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get()); |
14172 | } |
14173 | } |
14174 | } else { |
14175 | // Compound assignment "x += y" |
14176 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); |
14177 | } |
14178 | |
14179 | if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType, SrcExpr: RHS.get(), |
14180 | Action: AssignmentAction::Assigning)) |
14181 | return QualType(); |
14182 | |
14183 | CheckForNullPointerDereference(S&: *this, E: LHSExpr); |
14184 | |
14185 | AssignedEntity AE{.LHS: LHSExpr}; |
14186 | checkAssignmentLifetime(SemaRef&: *this, Entity: AE, Init: RHS.get()); |
14187 | |
14188 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { |
14189 | if (CompoundType.isNull()) { |
14190 | // C++2a [expr.ass]p5: |
14191 | // A simple-assignment whose left operand is of a volatile-qualified |
14192 | // type is deprecated unless the assignment is either a discarded-value |
14193 | // expression or an unevaluated operand |
14194 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(Elt: LHSExpr); |
14195 | } |
14196 | } |
14197 | |
14198 | // C11 6.5.16p3: The type of an assignment expression is the type of the |
14199 | // left operand would have after lvalue conversion. |
14200 | // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has |
14201 | // qualified type, the value has the unqualified version of the type of the |
14202 | // lvalue; additionally, if the lvalue has atomic type, the value has the |
14203 | // non-atomic version of the type of the lvalue. |
14204 | // C++ 5.17p1: the type of the assignment expression is that of its left |
14205 | // operand. |
14206 | return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); |
14207 | } |
14208 | |
14209 | // Scenarios to ignore if expression E is: |
14210 | // 1. an explicit cast expression into void |
14211 | // 2. a function call expression that returns void |
14212 | static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { |
14213 | E = E->IgnoreParens(); |
14214 | |
14215 | if (const CastExpr *CE = dyn_cast<CastExpr>(Val: E)) { |
14216 | if (CE->getCastKind() == CK_ToVoid) { |
14217 | return true; |
14218 | } |
14219 | |
14220 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. |
14221 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && |
14222 | CE->getSubExpr()->getType()->isDependentType()) { |
14223 | return true; |
14224 | } |
14225 | } |
14226 | |
14227 | if (const auto *CE = dyn_cast<CallExpr>(Val: E)) |
14228 | return CE->getCallReturnType(Ctx: Context)->isVoidType(); |
14229 | return false; |
14230 | } |
14231 | |
14232 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { |
14233 | // No warnings in macros |
14234 | if (Loc.isMacroID()) |
14235 | return; |
14236 | |
14237 | // Don't warn in template instantiations. |
14238 | if (inTemplateInstantiation()) |
14239 | return; |
14240 | |
14241 | // Scope isn't fine-grained enough to explicitly list the specific cases, so |
14242 | // instead, skip more than needed, then call back into here with the |
14243 | // CommaVisitor in SemaStmt.cpp. |
14244 | // The listed locations are the initialization and increment portions |
14245 | // of a for loop. The additional checks are on the condition of |
14246 | // if statements, do/while loops, and for loops. |
14247 | // Differences in scope flags for C89 mode requires the extra logic. |
14248 | const unsigned ForIncrementFlags = |
14249 | getLangOpts().C99 || getLangOpts().CPlusPlus |
14250 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope |
14251 | : Scope::ContinueScope | Scope::BreakScope; |
14252 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; |
14253 | const unsigned ScopeFlags = getCurScope()->getFlags(); |
14254 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || |
14255 | (ScopeFlags & ForInitFlags) == ForInitFlags) |
14256 | return; |
14257 | |
14258 | // If there are multiple comma operators used together, get the RHS of the |
14259 | // of the comma operator as the LHS. |
14260 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: LHS)) { |
14261 | if (BO->getOpcode() != BO_Comma) |
14262 | break; |
14263 | LHS = BO->getRHS(); |
14264 | } |
14265 | |
14266 | // Only allow some expressions on LHS to not warn. |
14267 | if (IgnoreCommaOperand(E: LHS, Context)) |
14268 | return; |
14269 | |
14270 | Diag(Loc, diag::warn_comma_operator); |
14271 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) |
14272 | << LHS->getSourceRange() |
14273 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), |
14274 | LangOpts.CPlusPlus ? "static_cast<void>(" |
14275 | : "(void)(") |
14276 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), |
14277 | ")"); |
14278 | } |
14279 | |
14280 | // C99 6.5.17 |
14281 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, |
14282 | SourceLocation Loc) { |
14283 | LHS = S.CheckPlaceholderExpr(E: LHS.get()); |
14284 | RHS = S.CheckPlaceholderExpr(E: RHS.get()); |
14285 | if (LHS.isInvalid() || RHS.isInvalid()) |
14286 | return QualType(); |
14287 | |
14288 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its |
14289 | // operands, but not unary promotions. |
14290 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). |
14291 | |
14292 | // So we treat the LHS as a ignored value, and in C++ we allow the |
14293 | // containing site to determine what should be done with the RHS. |
14294 | LHS = S.IgnoredValueConversions(E: LHS.get()); |
14295 | if (LHS.isInvalid()) |
14296 | return QualType(); |
14297 | |
14298 | S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); |
14299 | |
14300 | if (!S.getLangOpts().CPlusPlus) { |
14301 | RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
14302 | if (RHS.isInvalid()) |
14303 | return QualType(); |
14304 | if (!RHS.get()->getType()->isVoidType()) |
14305 | S.RequireCompleteType(Loc, RHS.get()->getType(), |
14306 | diag::err_incomplete_type); |
14307 | } |
14308 | |
14309 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) |
14310 | S.DiagnoseCommaOperator(LHS: LHS.get(), Loc); |
14311 | |
14312 | return RHS.get()->getType(); |
14313 | } |
14314 | |
14315 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine |
14316 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. |
14317 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, |
14318 | ExprValueKind &VK, |
14319 | ExprObjectKind &OK, |
14320 | SourceLocation OpLoc, bool IsInc, |
14321 | bool IsPrefix) { |
14322 | QualType ResType = Op->getType(); |
14323 | // Atomic types can be used for increment / decrement where the non-atomic |
14324 | // versions can, so ignore the _Atomic() specifier for the purpose of |
14325 | // checking. |
14326 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
14327 | ResType = ResAtomicType->getValueType(); |
14328 | |
14329 | assert(!ResType.isNull() && "no type for increment/decrement expression"); |
14330 | |
14331 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { |
14332 | // Decrement of bool is not allowed. |
14333 | if (!IsInc) { |
14334 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); |
14335 | return QualType(); |
14336 | } |
14337 | // Increment of bool sets it to true, but is deprecated. |
14338 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool |
14339 | : diag::warn_increment_bool) |
14340 | << Op->getSourceRange(); |
14341 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { |
14342 | // Error on enum increments and decrements in C++ mode |
14343 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; |
14344 | return QualType(); |
14345 | } else if (ResType->isRealType()) { |
14346 | // OK! |
14347 | } else if (ResType->isPointerType()) { |
14348 | // C99 6.5.2.4p2, 6.5.6p2 |
14349 | if (!checkArithmeticOpPointerOperand(S, Loc: OpLoc, Operand: Op)) |
14350 | return QualType(); |
14351 | } else if (ResType->isObjCObjectPointerType()) { |
14352 | // On modern runtimes, ObjC pointer arithmetic is forbidden. |
14353 | // Otherwise, we just need a complete type. |
14354 | if (checkArithmeticIncompletePointerType(S, Loc: OpLoc, Operand: Op) || |
14355 | checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: Op)) |
14356 | return QualType(); |
14357 | } else if (ResType->isAnyComplexType()) { |
14358 | // C99 does not support ++/-- on complex types, we allow as an extension. |
14359 | S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex |
14360 | : diag::ext_c2y_increment_complex) |
14361 | << IsInc << Op->getSourceRange(); |
14362 | } else if (ResType->isPlaceholderType()) { |
14363 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
14364 | if (PR.isInvalid()) return QualType(); |
14365 | return CheckIncrementDecrementOperand(S, Op: PR.get(), VK, OK, OpLoc, |
14366 | IsInc, IsPrefix); |
14367 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { |
14368 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) |
14369 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && |
14370 | (ResType->castAs<VectorType>()->getVectorKind() != |
14371 | VectorKind::AltiVecBool)) { |
14372 | // The z vector extensions allow ++ and -- for non-bool vectors. |
14373 | } else if (S.getLangOpts().OpenCL && ResType->isVectorType() && |
14374 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { |
14375 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. |
14376 | } else { |
14377 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) |
14378 | << ResType << int(IsInc) << Op->getSourceRange(); |
14379 | return QualType(); |
14380 | } |
14381 | // At this point, we know we have a real, complex or pointer type. |
14382 | // Now make sure the operand is a modifiable lvalue. |
14383 | if (CheckForModifiableLvalue(E: Op, Loc: OpLoc, S)) |
14384 | return QualType(); |
14385 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { |
14386 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: |
14387 | // An operand with volatile-qualified type is deprecated |
14388 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) |
14389 | << IsInc << ResType; |
14390 | } |
14391 | // In C++, a prefix increment is the same type as the operand. Otherwise |
14392 | // (in C or with postfix), the increment is the unqualified type of the |
14393 | // operand. |
14394 | if (IsPrefix && S.getLangOpts().CPlusPlus) { |
14395 | VK = VK_LValue; |
14396 | OK = Op->getObjectKind(); |
14397 | return ResType; |
14398 | } else { |
14399 | VK = VK_PRValue; |
14400 | return ResType.getUnqualifiedType(); |
14401 | } |
14402 | } |
14403 | |
14404 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). |
14405 | /// This routine allows us to typecheck complex/recursive expressions |
14406 | /// where the declaration is needed for type checking. We only need to |
14407 | /// handle cases when the expression references a function designator |
14408 | /// or is an lvalue. Here are some examples: |
14409 | /// - &(x) => x |
14410 | /// - &*****f => f for f a function designator. |
14411 | /// - &s.xx => s |
14412 | /// - &s.zz[1].yy -> s, if zz is an array |
14413 | /// - *(x + 1) -> x, if x is an array |
14414 | /// - &"123"[2] -> 0 |
14415 | /// - & __real__ x -> x |
14416 | /// |
14417 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to |
14418 | /// members. |
14419 | static ValueDecl *getPrimaryDecl(Expr *E) { |
14420 | switch (E->getStmtClass()) { |
14421 | case Stmt::DeclRefExprClass: |
14422 | return cast<DeclRefExpr>(Val: E)->getDecl(); |
14423 | case Stmt::MemberExprClass: |
14424 | // If this is an arrow operator, the address is an offset from |
14425 | // the base's value, so the object the base refers to is |
14426 | // irrelevant. |
14427 | if (cast<MemberExpr>(Val: E)->isArrow()) |
14428 | return nullptr; |
14429 | // Otherwise, the expression refers to a part of the base |
14430 | return getPrimaryDecl(E: cast<MemberExpr>(Val: E)->getBase()); |
14431 | case Stmt::ArraySubscriptExprClass: { |
14432 | // FIXME: This code shouldn't be necessary! We should catch the implicit |
14433 | // promotion of register arrays earlier. |
14434 | Expr* Base = cast<ArraySubscriptExpr>(Val: E)->getBase(); |
14435 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: Base)) { |
14436 | if (ICE->getSubExpr()->getType()->isArrayType()) |
14437 | return getPrimaryDecl(ICE->getSubExpr()); |
14438 | } |
14439 | return nullptr; |
14440 | } |
14441 | case Stmt::UnaryOperatorClass: { |
14442 | UnaryOperator *UO = cast<UnaryOperator>(Val: E); |
14443 | |
14444 | switch(UO->getOpcode()) { |
14445 | case UO_Real: |
14446 | case UO_Imag: |
14447 | case UO_Extension: |
14448 | return getPrimaryDecl(E: UO->getSubExpr()); |
14449 | default: |
14450 | return nullptr; |
14451 | } |
14452 | } |
14453 | case Stmt::ParenExprClass: |
14454 | return getPrimaryDecl(E: cast<ParenExpr>(Val: E)->getSubExpr()); |
14455 | case Stmt::ImplicitCastExprClass: |
14456 | // If the result of an implicit cast is an l-value, we care about |
14457 | // the sub-expression; otherwise, the result here doesn't matter. |
14458 | return getPrimaryDecl(cast<ImplicitCastExpr>(Val: E)->getSubExpr()); |
14459 | case Stmt::CXXUuidofExprClass: |
14460 | return cast<CXXUuidofExpr>(Val: E)->getGuidDecl(); |
14461 | default: |
14462 | return nullptr; |
14463 | } |
14464 | } |
14465 | |
14466 | namespace { |
14467 | enum { |
14468 | AO_Bit_Field = 0, |
14469 | AO_Vector_Element = 1, |
14470 | AO_Property_Expansion = 2, |
14471 | AO_Register_Variable = 3, |
14472 | AO_Matrix_Element = 4, |
14473 | AO_No_Error = 5 |
14474 | }; |
14475 | } |
14476 | /// Diagnose invalid operand for address of operations. |
14477 | /// |
14478 | /// \param Type The type of operand which cannot have its address taken. |
14479 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, |
14480 | Expr *E, unsigned Type) { |
14481 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); |
14482 | } |
14483 | |
14484 | bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, |
14485 | const Expr *Op, |
14486 | const CXXMethodDecl *MD) { |
14487 | const auto *DRE = cast<DeclRefExpr>(Val: Op->IgnoreParens()); |
14488 | |
14489 | if (Op != DRE) |
14490 | return Diag(OpLoc, diag::err_parens_pointer_member_function) |
14491 | << Op->getSourceRange(); |
14492 | |
14493 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. |
14494 | if (isa<CXXDestructorDecl>(MD)) |
14495 | return Diag(OpLoc, diag::err_typecheck_addrof_dtor) |
14496 | << DRE->getSourceRange(); |
14497 | |
14498 | if (DRE->getQualifier()) |
14499 | return false; |
14500 | |
14501 | if (MD->getParent()->getName().empty()) |
14502 | return Diag(OpLoc, diag::err_unqualified_pointer_member_function) |
14503 | << DRE->getSourceRange(); |
14504 | |
14505 | SmallString<32> Str; |
14506 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); |
14507 | return Diag(OpLoc, diag::err_unqualified_pointer_member_function) |
14508 | << DRE->getSourceRange() |
14509 | << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual); |
14510 | } |
14511 | |
14512 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { |
14513 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ |
14514 | if (PTy->getKind() == BuiltinType::Overload) { |
14515 | Expr *E = OrigOp.get()->IgnoreParens(); |
14516 | if (!isa<OverloadExpr>(Val: E)) { |
14517 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); |
14518 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) |
14519 | << OrigOp.get()->getSourceRange(); |
14520 | return QualType(); |
14521 | } |
14522 | |
14523 | OverloadExpr *Ovl = cast<OverloadExpr>(Val: E); |
14524 | if (isa<UnresolvedMemberExpr>(Val: Ovl)) |
14525 | if (!ResolveSingleFunctionTemplateSpecialization(ovl: Ovl)) { |
14526 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
14527 | << OrigOp.get()->getSourceRange(); |
14528 | return QualType(); |
14529 | } |
14530 | |
14531 | return Context.OverloadTy; |
14532 | } |
14533 | |
14534 | if (PTy->getKind() == BuiltinType::UnknownAny) |
14535 | return Context.UnknownAnyTy; |
14536 | |
14537 | if (PTy->getKind() == BuiltinType::BoundMember) { |
14538 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
14539 | << OrigOp.get()->getSourceRange(); |
14540 | return QualType(); |
14541 | } |
14542 | |
14543 | OrigOp = CheckPlaceholderExpr(E: OrigOp.get()); |
14544 | if (OrigOp.isInvalid()) return QualType(); |
14545 | } |
14546 | |
14547 | if (OrigOp.get()->isTypeDependent()) |
14548 | return Context.DependentTy; |
14549 | |
14550 | assert(!OrigOp.get()->hasPlaceholderType()); |
14551 | |
14552 | // Make sure to ignore parentheses in subsequent checks |
14553 | Expr *op = OrigOp.get()->IgnoreParens(); |
14554 | |
14555 | // In OpenCL captures for blocks called as lambda functions |
14556 | // are located in the private address space. Blocks used in |
14557 | // enqueue_kernel can be located in a different address space |
14558 | // depending on a vendor implementation. Thus preventing |
14559 | // taking an address of the capture to avoid invalid AS casts. |
14560 | if (LangOpts.OpenCL) { |
14561 | auto* VarRef = dyn_cast<DeclRefExpr>(Val: op); |
14562 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { |
14563 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); |
14564 | return QualType(); |
14565 | } |
14566 | } |
14567 | |
14568 | if (getLangOpts().C99) { |
14569 | // Implement C99-only parts of addressof rules. |
14570 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(Val: op)) { |
14571 | if (uOp->getOpcode() == UO_Deref) |
14572 | // Per C99 6.5.3.2, the address of a deref always returns a valid result |
14573 | // (assuming the deref expression is valid). |
14574 | return uOp->getSubExpr()->getType(); |
14575 | } |
14576 | // Technically, there should be a check for array subscript |
14577 | // expressions here, but the result of one is always an lvalue anyway. |
14578 | } |
14579 | ValueDecl *dcl = getPrimaryDecl(E: op); |
14580 | |
14581 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl)) |
14582 | if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
14583 | Loc: op->getBeginLoc())) |
14584 | return QualType(); |
14585 | |
14586 | Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context); |
14587 | unsigned AddressOfError = AO_No_Error; |
14588 | |
14589 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { |
14590 | bool sfinae = (bool)isSFINAEContext(); |
14591 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary |
14592 | : diag::ext_typecheck_addrof_temporary) |
14593 | << op->getType() << op->getSourceRange(); |
14594 | if (sfinae) |
14595 | return QualType(); |
14596 | // Materialize the temporary as an lvalue so that we can take its address. |
14597 | OrigOp = op = |
14598 | CreateMaterializeTemporaryExpr(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true); |
14599 | } else if (isa<ObjCSelectorExpr>(Val: op)) { |
14600 | return Context.getPointerType(T: op->getType()); |
14601 | } else if (lval == Expr::LV_MemberFunction) { |
14602 | // If it's an instance method, make a member pointer. |
14603 | // The expression must have exactly the form &A::foo. |
14604 | |
14605 | // If the underlying expression isn't a decl ref, give up. |
14606 | if (!isa<DeclRefExpr>(Val: op)) { |
14607 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
14608 | << OrigOp.get()->getSourceRange(); |
14609 | return QualType(); |
14610 | } |
14611 | DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op); |
14612 | CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl()); |
14613 | |
14614 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
14615 | QualType MPTy = Context.getMemberPointerType( |
14616 | T: op->getType(), Qualifier: DRE->getQualifier(), Cls: MD->getParent()); |
14617 | |
14618 | if (getLangOpts().PointerAuthCalls && MD->isVirtual() && |
14619 | !isUnevaluatedContext() && !MPTy->isDependentType()) { |
14620 | // When pointer authentication is enabled, argument and return types of |
14621 | // vitual member functions must be complete. This is because vitrual |
14622 | // member function pointers are implemented using virtual dispatch |
14623 | // thunks and the thunks cannot be emitted if the argument or return |
14624 | // types are incomplete. |
14625 | auto ReturnOrParamTypeIsIncomplete = [&](QualType T, |
14626 | SourceLocation DeclRefLoc, |
14627 | SourceLocation RetArgTypeLoc) { |
14628 | if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) { |
14629 | Diag(DeclRefLoc, |
14630 | diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret); |
14631 | Diag(RetArgTypeLoc, |
14632 | diag::note_ptrauth_virtual_function_incomplete_arg_ret_type) |
14633 | << T; |
14634 | return true; |
14635 | } |
14636 | return false; |
14637 | }; |
14638 | QualType RetTy = MD->getReturnType(); |
14639 | bool IsIncomplete = |
14640 | !RetTy->isVoidType() && |
14641 | ReturnOrParamTypeIsIncomplete( |
14642 | RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin()); |
14643 | for (auto *PVD : MD->parameters()) |
14644 | IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc, |
14645 | PVD->getBeginLoc()); |
14646 | if (IsIncomplete) |
14647 | return QualType(); |
14648 | } |
14649 | |
14650 | // Under the MS ABI, lock down the inheritance model now. |
14651 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
14652 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
14653 | return MPTy; |
14654 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { |
14655 | // C99 6.5.3.2p1 |
14656 | // The operand must be either an l-value or a function designator |
14657 | if (!op->getType()->isFunctionType()) { |
14658 | // Use a special diagnostic for loads from property references. |
14659 | if (isa<PseudoObjectExpr>(Val: op)) { |
14660 | AddressOfError = AO_Property_Expansion; |
14661 | } else { |
14662 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) |
14663 | << op->getType() << op->getSourceRange(); |
14664 | return QualType(); |
14665 | } |
14666 | } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: op)) { |
14667 | if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl())) |
14668 | CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD); |
14669 | } |
14670 | |
14671 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 |
14672 | // The operand cannot be a bit-field |
14673 | AddressOfError = AO_Bit_Field; |
14674 | } else if (op->getObjectKind() == OK_VectorComponent) { |
14675 | // The operand cannot be an element of a vector |
14676 | AddressOfError = AO_Vector_Element; |
14677 | } else if (op->getObjectKind() == OK_MatrixComponent) { |
14678 | // The operand cannot be an element of a matrix. |
14679 | AddressOfError = AO_Matrix_Element; |
14680 | } else if (dcl) { // C99 6.5.3.2p1 |
14681 | // We have an lvalue with a decl. Make sure the decl is not declared |
14682 | // with the register storage-class specifier. |
14683 | if (const VarDecl *vd = dyn_cast<VarDecl>(Val: dcl)) { |
14684 | // in C++ it is not error to take address of a register |
14685 | // variable (c++03 7.1.1P3) |
14686 | if (vd->getStorageClass() == SC_Register && |
14687 | !getLangOpts().CPlusPlus) { |
14688 | AddressOfError = AO_Register_Variable; |
14689 | } |
14690 | } else if (isa<MSPropertyDecl>(Val: dcl)) { |
14691 | AddressOfError = AO_Property_Expansion; |
14692 | } else if (isa<FunctionTemplateDecl>(Val: dcl)) { |
14693 | return Context.OverloadTy; |
14694 | } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: dcl)) { |
14695 | // Okay: we can take the address of a field. |
14696 | // Could be a pointer to member, though, if there is an explicit |
14697 | // scope qualifier for the class. |
14698 | |
14699 | // [C++26] [expr.prim.id.general] |
14700 | // If an id-expression E denotes a non-static non-type member |
14701 | // of some class C [...] and if E is a qualified-id, E is |
14702 | // not the un-parenthesized operand of the unary & operator [...] |
14703 | // the id-expression is transformed into a class member access expression. |
14704 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: op); |
14705 | DRE && DRE->getQualifier() && !isa<ParenExpr>(Val: OrigOp.get())) { |
14706 | DeclContext *Ctx = dcl->getDeclContext(); |
14707 | if (Ctx && Ctx->isRecord()) { |
14708 | if (dcl->getType()->isReferenceType()) { |
14709 | Diag(OpLoc, |
14710 | diag::err_cannot_form_pointer_to_member_of_reference_type) |
14711 | << dcl->getDeclName() << dcl->getType(); |
14712 | return QualType(); |
14713 | } |
14714 | |
14715 | while (cast<RecordDecl>(Val: Ctx)->isAnonymousStructOrUnion()) |
14716 | Ctx = Ctx->getParent(); |
14717 | |
14718 | QualType MPTy = Context.getMemberPointerType( |
14719 | T: op->getType(), Qualifier: DRE->getQualifier(), Cls: cast<CXXRecordDecl>(Val: Ctx)); |
14720 | // Under the MS ABI, lock down the inheritance model now. |
14721 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
14722 | (void)isCompleteType(Loc: OpLoc, T: MPTy); |
14723 | return MPTy; |
14724 | } |
14725 | } |
14726 | } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, |
14727 | MSGuidDecl, UnnamedGlobalConstantDecl>(Val: dcl)) |
14728 | llvm_unreachable("Unknown/unexpected decl type"); |
14729 | } |
14730 | |
14731 | if (AddressOfError != AO_No_Error) { |
14732 | diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: AddressOfError); |
14733 | return QualType(); |
14734 | } |
14735 | |
14736 | if (lval == Expr::LV_IncompleteVoidType) { |
14737 | // Taking the address of a void variable is technically illegal, but we |
14738 | // allow it in cases which are otherwise valid. |
14739 | // Example: "extern void x; void* y = &x;". |
14740 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); |
14741 | } |
14742 | |
14743 | // If the operand has type "type", the result has type "pointer to type". |
14744 | if (op->getType()->isObjCObjectType()) |
14745 | return Context.getObjCObjectPointerType(OIT: op->getType()); |
14746 | |
14747 | // Cannot take the address of WebAssembly references or tables. |
14748 | if (Context.getTargetInfo().getTriple().isWasm()) { |
14749 | QualType OpTy = op->getType(); |
14750 | if (OpTy.isWebAssemblyReferenceType()) { |
14751 | Diag(OpLoc, diag::err_wasm_ca_reference) |
14752 | << 1 << OrigOp.get()->getSourceRange(); |
14753 | return QualType(); |
14754 | } |
14755 | if (OpTy->isWebAssemblyTableType()) { |
14756 | Diag(OpLoc, diag::err_wasm_table_pr) |
14757 | << 1 << OrigOp.get()->getSourceRange(); |
14758 | return QualType(); |
14759 | } |
14760 | } |
14761 | |
14762 | CheckAddressOfPackedMember(rhs: op); |
14763 | |
14764 | return Context.getPointerType(T: op->getType()); |
14765 | } |
14766 | |
14767 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { |
14768 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp); |
14769 | if (!DRE) |
14770 | return; |
14771 | const Decl *D = DRE->getDecl(); |
14772 | if (!D) |
14773 | return; |
14774 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: D); |
14775 | if (!Param) |
14776 | return; |
14777 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) |
14778 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) |
14779 | return; |
14780 | if (FunctionScopeInfo *FD = S.getCurFunction()) |
14781 | FD->ModifiedNonNullParams.insert(Ptr: Param); |
14782 | } |
14783 | |
14784 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). |
14785 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, |
14786 | SourceLocation OpLoc, |
14787 | bool IsAfterAmp = false) { |
14788 | ExprResult ConvResult = S.UsualUnaryConversions(E: Op); |
14789 | if (ConvResult.isInvalid()) |
14790 | return QualType(); |
14791 | Op = ConvResult.get(); |
14792 | QualType OpTy = Op->getType(); |
14793 | QualType Result; |
14794 | |
14795 | if (isa<CXXReinterpretCastExpr>(Val: Op)) { |
14796 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); |
14797 | S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true, |
14798 | Range: Op->getSourceRange()); |
14799 | } |
14800 | |
14801 | if (const PointerType *PT = OpTy->getAs<PointerType>()) |
14802 | { |
14803 | Result = PT->getPointeeType(); |
14804 | } |
14805 | else if (const ObjCObjectPointerType *OPT = |
14806 | OpTy->getAs<ObjCObjectPointerType>()) |
14807 | Result = OPT->getPointeeType(); |
14808 | else { |
14809 | ExprResult PR = S.CheckPlaceholderExpr(E: Op); |
14810 | if (PR.isInvalid()) return QualType(); |
14811 | if (PR.get() != Op) |
14812 | return CheckIndirectionOperand(S, Op: PR.get(), VK, OpLoc); |
14813 | } |
14814 | |
14815 | if (Result.isNull()) { |
14816 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) |
14817 | << OpTy << Op->getSourceRange(); |
14818 | return QualType(); |
14819 | } |
14820 | |
14821 | if (Result->isVoidType()) { |
14822 | // C++ [expr.unary.op]p1: |
14823 | // [...] the expression to which [the unary * operator] is applied shall |
14824 | // be a pointer to an object type, or a pointer to a function type |
14825 | LangOptions LO = S.getLangOpts(); |
14826 | if (LO.CPlusPlus) |
14827 | S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp) |
14828 | << OpTy << Op->getSourceRange(); |
14829 | else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) |
14830 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) |
14831 | << OpTy << Op->getSourceRange(); |
14832 | } |
14833 | |
14834 | // Dereferences are usually l-values... |
14835 | VK = VK_LValue; |
14836 | |
14837 | // ...except that certain expressions are never l-values in C. |
14838 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) |
14839 | VK = VK_PRValue; |
14840 | |
14841 | return Result; |
14842 | } |
14843 | |
14844 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { |
14845 | BinaryOperatorKind Opc; |
14846 | switch (Kind) { |
14847 | default: llvm_unreachable("Unknown binop!"); |
14848 | case tok::periodstar: Opc = BO_PtrMemD; break; |
14849 | case tok::arrowstar: Opc = BO_PtrMemI; break; |
14850 | case tok::star: Opc = BO_Mul; break; |
14851 | case tok::slash: Opc = BO_Div; break; |
14852 | case tok::percent: Opc = BO_Rem; break; |
14853 | case tok::plus: Opc = BO_Add; break; |
14854 | case tok::minus: Opc = BO_Sub; break; |
14855 | case tok::lessless: Opc = BO_Shl; break; |
14856 | case tok::greatergreater: Opc = BO_Shr; break; |
14857 | case tok::lessequal: Opc = BO_LE; break; |
14858 | case tok::less: Opc = BO_LT; break; |
14859 | case tok::greaterequal: Opc = BO_GE; break; |
14860 | case tok::greater: Opc = BO_GT; break; |
14861 | case tok::exclaimequal: Opc = BO_NE; break; |
14862 | case tok::equalequal: Opc = BO_EQ; break; |
14863 | case tok::spaceship: Opc = BO_Cmp; break; |
14864 | case tok::amp: Opc = BO_And; break; |
14865 | case tok::caret: Opc = BO_Xor; break; |
14866 | case tok::pipe: Opc = BO_Or; break; |
14867 | case tok::ampamp: Opc = BO_LAnd; break; |
14868 | case tok::pipepipe: Opc = BO_LOr; break; |
14869 | case tok::equal: Opc = BO_Assign; break; |
14870 | case tok::starequal: Opc = BO_MulAssign; break; |
14871 | case tok::slashequal: Opc = BO_DivAssign; break; |
14872 | case tok::percentequal: Opc = BO_RemAssign; break; |
14873 | case tok::plusequal: Opc = BO_AddAssign; break; |
14874 | case tok::minusequal: Opc = BO_SubAssign; break; |
14875 | case tok::lesslessequal: Opc = BO_ShlAssign; break; |
14876 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; |
14877 | case tok::ampequal: Opc = BO_AndAssign; break; |
14878 | case tok::caretequal: Opc = BO_XorAssign; break; |
14879 | case tok::pipeequal: Opc = BO_OrAssign; break; |
14880 | case tok::comma: Opc = BO_Comma; break; |
14881 | } |
14882 | return Opc; |
14883 | } |
14884 | |
14885 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( |
14886 | tok::TokenKind Kind) { |
14887 | UnaryOperatorKind Opc; |
14888 | switch (Kind) { |
14889 | default: llvm_unreachable("Unknown unary op!"); |
14890 | case tok::plusplus: Opc = UO_PreInc; break; |
14891 | case tok::minusminus: Opc = UO_PreDec; break; |
14892 | case tok::amp: Opc = UO_AddrOf; break; |
14893 | case tok::star: Opc = UO_Deref; break; |
14894 | case tok::plus: Opc = UO_Plus; break; |
14895 | case tok::minus: Opc = UO_Minus; break; |
14896 | case tok::tilde: Opc = UO_Not; break; |
14897 | case tok::exclaim: Opc = UO_LNot; break; |
14898 | case tok::kw___real: Opc = UO_Real; break; |
14899 | case tok::kw___imag: Opc = UO_Imag; break; |
14900 | case tok::kw___extension__: Opc = UO_Extension; break; |
14901 | } |
14902 | return Opc; |
14903 | } |
14904 | |
14905 | const FieldDecl * |
14906 | Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { |
14907 | // Explore the case for adding 'this->' to the LHS of a self assignment, very |
14908 | // common for setters. |
14909 | // struct A { |
14910 | // int X; |
14911 | // -void setX(int X) { X = X; } |
14912 | // +void setX(int X) { this->X = X; } |
14913 | // }; |
14914 | |
14915 | // Only consider parameters for self assignment fixes. |
14916 | if (!isa<ParmVarDecl>(Val: SelfAssigned)) |
14917 | return nullptr; |
14918 | const auto *Method = |
14919 | dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: true)); |
14920 | if (!Method) |
14921 | return nullptr; |
14922 | |
14923 | const CXXRecordDecl *Parent = Method->getParent(); |
14924 | // In theory this is fixable if the lambda explicitly captures this, but |
14925 | // that's added complexity that's rarely going to be used. |
14926 | if (Parent->isLambda()) |
14927 | return nullptr; |
14928 | |
14929 | // FIXME: Use an actual Lookup operation instead of just traversing fields |
14930 | // in order to get base class fields. |
14931 | auto Field = |
14932 | llvm::find_if(Parent->fields(), |
14933 | [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { |
14934 | return F->getDeclName() == Name; |
14935 | }); |
14936 | return (Field != Parent->field_end()) ? *Field : nullptr; |
14937 | } |
14938 | |
14939 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. |
14940 | /// This warning suppressed in the event of macro expansions. |
14941 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, |
14942 | SourceLocation OpLoc, bool IsBuiltin) { |
14943 | if (S.inTemplateInstantiation()) |
14944 | return; |
14945 | if (S.isUnevaluatedContext()) |
14946 | return; |
14947 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) |
14948 | return; |
14949 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); |
14950 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); |
14951 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr); |
14952 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr); |
14953 | if (!LHSDeclRef || !RHSDeclRef || |
14954 | LHSDeclRef->getLocation().isMacroID() || |
14955 | RHSDeclRef->getLocation().isMacroID()) |
14956 | return; |
14957 | const ValueDecl *LHSDecl = |
14958 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); |
14959 | const ValueDecl *RHSDecl = |
14960 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); |
14961 | if (LHSDecl != RHSDecl) |
14962 | return; |
14963 | if (LHSDecl->getType().isVolatileQualified()) |
14964 | return; |
14965 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
14966 | if (RefTy->getPointeeType().isVolatileQualified()) |
14967 | return; |
14968 | |
14969 | auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin |
14970 | : diag::warn_self_assignment_overloaded) |
14971 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() |
14972 | << RHSExpr->getSourceRange(); |
14973 | if (const FieldDecl *SelfAssignField = |
14974 | S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl)) |
14975 | Diag << 1 << SelfAssignField |
14976 | << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->"); |
14977 | else |
14978 | Diag << 0; |
14979 | } |
14980 | |
14981 | /// Check if a bitwise-& is performed on an Objective-C pointer. This |
14982 | /// is usually indicative of introspection within the Objective-C pointer. |
14983 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, |
14984 | SourceLocation OpLoc) { |
14985 | if (!S.getLangOpts().ObjC) |
14986 | return; |
14987 | |
14988 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; |
14989 | const Expr *LHS = L.get(); |
14990 | const Expr *RHS = R.get(); |
14991 | |
14992 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
14993 | ObjCPointerExpr = LHS; |
14994 | OtherExpr = RHS; |
14995 | } |
14996 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
14997 | ObjCPointerExpr = RHS; |
14998 | OtherExpr = LHS; |
14999 | } |
15000 | |
15001 | // This warning is deliberately made very specific to reduce false |
15002 | // positives with logic that uses '&' for hashing. This logic mainly |
15003 | // looks for code trying to introspect into tagged pointers, which |
15004 | // code should generally never do. |
15005 | if (ObjCPointerExpr && isa<IntegerLiteral>(Val: OtherExpr->IgnoreParenCasts())) { |
15006 | unsigned Diag = diag::warn_objc_pointer_masking; |
15007 | // Determine if we are introspecting the result of performSelectorXXX. |
15008 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); |
15009 | // Special case messages to -performSelector and friends, which |
15010 | // can return non-pointer values boxed in a pointer value. |
15011 | // Some clients may wish to silence warnings in this subcase. |
15012 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: Ex)) { |
15013 | Selector S = ME->getSelector(); |
15014 | StringRef SelArg0 = S.getNameForSlot(argIndex: 0); |
15015 | if (SelArg0.starts_with("performSelector")) |
15016 | Diag = diag::warn_objc_pointer_masking_performSelector; |
15017 | } |
15018 | |
15019 | S.Diag(OpLoc, Diag) |
15020 | << ObjCPointerExpr->getSourceRange(); |
15021 | } |
15022 | } |
15023 | |
15024 | static NamedDecl *getDeclFromExpr(Expr *E) { |
15025 | if (!E) |
15026 | return nullptr; |
15027 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
15028 | return DRE->getDecl(); |
15029 | if (auto *ME = dyn_cast<MemberExpr>(Val: E)) |
15030 | return ME->getMemberDecl(); |
15031 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: E)) |
15032 | return IRE->getDecl(); |
15033 | return nullptr; |
15034 | } |
15035 | |
15036 | // This helper function promotes a binary operator's operands (which are of a |
15037 | // half vector type) to a vector of floats and then truncates the result to |
15038 | // a vector of either half or short. |
15039 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, |
15040 | BinaryOperatorKind Opc, QualType ResultTy, |
15041 | ExprValueKind VK, ExprObjectKind OK, |
15042 | bool IsCompAssign, SourceLocation OpLoc, |
15043 | FPOptionsOverride FPFeatures) { |
15044 | auto &Context = S.getASTContext(); |
15045 | assert((isVector(ResultTy, Context.HalfTy) || |
15046 | isVector(ResultTy, Context.ShortTy)) && |
15047 | "Result must be a vector of half or short"); |
15048 | assert(isVector(LHS.get()->getType(), Context.HalfTy) && |
15049 | isVector(RHS.get()->getType(), Context.HalfTy) && |
15050 | "both operands expected to be a half vector"); |
15051 | |
15052 | RHS = convertVector(RHS.get(), Context.FloatTy, S); |
15053 | QualType BinOpResTy = RHS.get()->getType(); |
15054 | |
15055 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, |
15056 | // change BinOpResTy to a vector of ints. |
15057 | if (isVector(ResultTy, Context.ShortTy)) |
15058 | BinOpResTy = S.GetSignedVectorType(V: BinOpResTy); |
15059 | |
15060 | if (IsCompAssign) |
15061 | return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
15062 | ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures, |
15063 | CompLHSType: BinOpResTy, CompResultType: BinOpResTy); |
15064 | |
15065 | LHS = convertVector(LHS.get(), Context.FloatTy, S); |
15066 | auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, |
15067 | ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures); |
15068 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); |
15069 | } |
15070 | |
15071 | static std::pair<ExprResult, ExprResult> |
15072 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, |
15073 | Expr *RHSExpr) { |
15074 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
15075 | if (!S.Context.isDependenceAllowed()) { |
15076 | // C cannot handle TypoExpr nodes on either side of a binop because it |
15077 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
15078 | // been dealt with before checking the operands. |
15079 | LHS = S.CorrectDelayedTyposInExpr(ER: LHS); |
15080 | RHS = S.CorrectDelayedTyposInExpr( |
15081 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, |
15082 | [Opc, LHS](Expr *E) { |
15083 | if (Opc != BO_Assign) |
15084 | return ExprResult(E); |
15085 | // Avoid correcting the RHS to the same Expr as the LHS. |
15086 | Decl *D = getDeclFromExpr(E); |
15087 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; |
15088 | }); |
15089 | } |
15090 | return std::make_pair(x&: LHS, y&: RHS); |
15091 | } |
15092 | |
15093 | /// Returns true if conversion between vectors of halfs and vectors of floats |
15094 | /// is needed. |
15095 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, |
15096 | Expr *E0, Expr *E1 = nullptr) { |
15097 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || |
15098 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) |
15099 | return false; |
15100 | |
15101 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { |
15102 | QualType Ty = E->IgnoreImplicit()->getType(); |
15103 | |
15104 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h |
15105 | // to vectors of floats. Although the element type of the vectors is __fp16, |
15106 | // the vectors shouldn't be treated as storage-only types. See the |
15107 | // discussion here: https://reviews.llvm.org/rG825235c140e7 |
15108 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
15109 | if (VT->getVectorKind() == VectorKind::Neon) |
15110 | return false; |
15111 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; |
15112 | } |
15113 | return false; |
15114 | }; |
15115 | |
15116 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); |
15117 | } |
15118 | |
15119 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, |
15120 | BinaryOperatorKind Opc, Expr *LHSExpr, |
15121 | Expr *RHSExpr, bool ForFoldExpression) { |
15122 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: RHSExpr)) { |
15123 | // The syntax only allows initializer lists on the RHS of assignment, |
15124 | // so we don't need to worry about accepting invalid code for |
15125 | // non-assignment operators. |
15126 | // C++11 5.17p9: |
15127 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning |
15128 | // of x = {} is x = T(). |
15129 | InitializationKind Kind = InitializationKind::CreateDirectList( |
15130 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
15131 | InitializedEntity Entity = |
15132 | InitializedEntity::InitializeTemporary(Type: LHSExpr->getType()); |
15133 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); |
15134 | ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: RHSExpr); |
15135 | if (Init.isInvalid()) |
15136 | return Init; |
15137 | RHSExpr = Init.get(); |
15138 | } |
15139 | |
15140 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
15141 | QualType ResultTy; // Result type of the binary operator. |
15142 | // The following two variables are used for compound assignment operators |
15143 | QualType CompLHSTy; // Type of LHS after promotions for computation |
15144 | QualType CompResultTy; // Type of computation result |
15145 | ExprValueKind VK = VK_PRValue; |
15146 | ExprObjectKind OK = OK_Ordinary; |
15147 | bool ConvertHalfVec = false; |
15148 | |
15149 | std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr); |
15150 | if (!LHS.isUsable() || !RHS.isUsable()) |
15151 | return ExprError(); |
15152 | |
15153 | if (getLangOpts().OpenCL) { |
15154 | QualType LHSTy = LHSExpr->getType(); |
15155 | QualType RHSTy = RHSExpr->getType(); |
15156 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by |
15157 | // the ATOMIC_VAR_INIT macro. |
15158 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { |
15159 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
15160 | if (BO_Assign == Opc) |
15161 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; |
15162 | else |
15163 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
15164 | return ExprError(); |
15165 | } |
15166 | |
15167 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
15168 | // only with a builtin functions and therefore should be disallowed here. |
15169 | if (LHSTy->isImageType() || RHSTy->isImageType() || |
15170 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || |
15171 | LHSTy->isPipeType() || RHSTy->isPipeType() || |
15172 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { |
15173 | ResultTy = InvalidOperands(Loc: OpLoc, LHS, RHS); |
15174 | return ExprError(); |
15175 | } |
15176 | } |
15177 | |
15178 | checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
15179 | checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr); |
15180 | |
15181 | switch (Opc) { |
15182 | case BO_Assign: |
15183 | ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: QualType(), Opc); |
15184 | if (getLangOpts().CPlusPlus && |
15185 | LHS.get()->getObjectKind() != OK_ObjCProperty) { |
15186 | VK = LHS.get()->getValueKind(); |
15187 | OK = LHS.get()->getObjectKind(); |
15188 | } |
15189 | if (!ResultTy.isNull()) { |
15190 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
15191 | DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc); |
15192 | |
15193 | // Avoid copying a block to the heap if the block is assigned to a local |
15194 | // auto variable that is declared in the same scope as the block. This |
15195 | // optimization is unsafe if the local variable is declared in an outer |
15196 | // scope. For example: |
15197 | // |
15198 | // BlockTy b; |
15199 | // { |
15200 | // b = ^{...}; |
15201 | // } |
15202 | // // It is unsafe to invoke the block here if it wasn't copied to the |
15203 | // // heap. |
15204 | // b(); |
15205 | |
15206 | if (auto *BE = dyn_cast<BlockExpr>(Val: RHS.get()->IgnoreParens())) |
15207 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens())) |
15208 | if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) |
15209 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) |
15210 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); |
15211 | |
15212 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) |
15213 | checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(), |
15214 | UseContext: NonTrivialCUnionContext::Assignment, NonTrivialKind: NTCUK_Copy); |
15215 | } |
15216 | RecordModifiableNonNullParam(S&: *this, Exp: LHS.get()); |
15217 | break; |
15218 | case BO_PtrMemD: |
15219 | case BO_PtrMemI: |
15220 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, |
15221 | isIndirect: Opc == BO_PtrMemI); |
15222 | break; |
15223 | case BO_Mul: |
15224 | case BO_Div: |
15225 | ConvertHalfVec = true; |
15226 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: false, |
15227 | IsDiv: Opc == BO_Div); |
15228 | break; |
15229 | case BO_Rem: |
15230 | ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc); |
15231 | break; |
15232 | case BO_Add: |
15233 | ConvertHalfVec = true; |
15234 | ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc); |
15235 | break; |
15236 | case BO_Sub: |
15237 | ConvertHalfVec = true; |
15238 | ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc); |
15239 | break; |
15240 | case BO_Shl: |
15241 | case BO_Shr: |
15242 | ResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc); |
15243 | break; |
15244 | case BO_LE: |
15245 | case BO_LT: |
15246 | case BO_GE: |
15247 | case BO_GT: |
15248 | ConvertHalfVec = true; |
15249 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
15250 | |
15251 | if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr); |
15252 | !ForFoldExpression && BI && BI->isComparisonOp()) |
15253 | Diag(OpLoc, diag::warn_consecutive_comparison) |
15254 | << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc); |
15255 | |
15256 | break; |
15257 | case BO_EQ: |
15258 | case BO_NE: |
15259 | ConvertHalfVec = true; |
15260 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
15261 | break; |
15262 | case BO_Cmp: |
15263 | ConvertHalfVec = true; |
15264 | ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc); |
15265 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); |
15266 | break; |
15267 | case BO_And: |
15268 | checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc); |
15269 | [[fallthrough]]; |
15270 | case BO_Xor: |
15271 | case BO_Or: |
15272 | ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
15273 | break; |
15274 | case BO_LAnd: |
15275 | case BO_LOr: |
15276 | ConvertHalfVec = true; |
15277 | ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc); |
15278 | break; |
15279 | case BO_MulAssign: |
15280 | case BO_DivAssign: |
15281 | ConvertHalfVec = true; |
15282 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true, |
15283 | IsDiv: Opc == BO_DivAssign); |
15284 | CompLHSTy = CompResultTy; |
15285 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15286 | ResultTy = |
15287 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15288 | break; |
15289 | case BO_RemAssign: |
15290 | CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true); |
15291 | CompLHSTy = CompResultTy; |
15292 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15293 | ResultTy = |
15294 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15295 | break; |
15296 | case BO_AddAssign: |
15297 | ConvertHalfVec = true; |
15298 | CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy); |
15299 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15300 | ResultTy = |
15301 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15302 | break; |
15303 | case BO_SubAssign: |
15304 | ConvertHalfVec = true; |
15305 | CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, CompLHSTy: &CompLHSTy); |
15306 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15307 | ResultTy = |
15308 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15309 | break; |
15310 | case BO_ShlAssign: |
15311 | case BO_ShrAssign: |
15312 | CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true); |
15313 | CompLHSTy = CompResultTy; |
15314 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15315 | ResultTy = |
15316 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15317 | break; |
15318 | case BO_AndAssign: |
15319 | case BO_OrAssign: // fallthrough |
15320 | DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true); |
15321 | [[fallthrough]]; |
15322 | case BO_XorAssign: |
15323 | CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc); |
15324 | CompLHSTy = CompResultTy; |
15325 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
15326 | ResultTy = |
15327 | CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc); |
15328 | break; |
15329 | case BO_Comma: |
15330 | ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: OpLoc); |
15331 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { |
15332 | VK = RHS.get()->getValueKind(); |
15333 | OK = RHS.get()->getObjectKind(); |
15334 | } |
15335 | break; |
15336 | } |
15337 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) |
15338 | return ExprError(); |
15339 | |
15340 | // Some of the binary operations require promoting operands of half vector to |
15341 | // float vectors and truncating the result back to half vector. For now, we do |
15342 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or |
15343 | // arm64). |
15344 | assert( |
15345 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == |
15346 | isVector(LHS.get()->getType(), Context.HalfTy)) && |
15347 | "both sides are half vectors or neither sides are"); |
15348 | ConvertHalfVec = |
15349 | needsConversionOfHalfVec(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get()); |
15350 | |
15351 | // Check for array bounds violations for both sides of the BinaryOperator |
15352 | CheckArrayAccess(E: LHS.get()); |
15353 | CheckArrayAccess(E: RHS.get()); |
15354 | |
15355 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) { |
15356 | NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope, |
15357 | Name: &Context.Idents.get(Name: "object_setClass"), |
15358 | Loc: SourceLocation(), NameKind: LookupOrdinaryName); |
15359 | if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) { |
15360 | SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc()); |
15361 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) |
15362 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), |
15363 | "object_setClass(") |
15364 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), |
15365 | ",") |
15366 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); |
15367 | } |
15368 | else |
15369 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); |
15370 | } |
15371 | else if (const ObjCIvarRefExpr *OIRE = |
15372 | dyn_cast<ObjCIvarRefExpr>(Val: LHS.get()->IgnoreParenCasts())) |
15373 | DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get()); |
15374 | |
15375 | // Opc is not a compound assignment if CompResultTy is null. |
15376 | if (CompResultTy.isNull()) { |
15377 | if (ConvertHalfVec) |
15378 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false, |
15379 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15380 | return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, |
15381 | VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15382 | } |
15383 | |
15384 | // Handle compound assignments. |
15385 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != |
15386 | OK_ObjCProperty) { |
15387 | VK = VK_LValue; |
15388 | OK = LHS.get()->getObjectKind(); |
15389 | } |
15390 | |
15391 | // The LHS is not converted to the result type for fixed-point compound |
15392 | // assignment as the common type is computed on demand. Reset the CompLHSTy |
15393 | // to the LHS type we would have gotten after unary conversions. |
15394 | if (CompResultTy->isFixedPointType()) |
15395 | CompLHSTy = UsualUnaryConversions(E: LHS.get()).get()->getType(); |
15396 | |
15397 | if (ConvertHalfVec) |
15398 | return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true, |
15399 | OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15400 | |
15401 | return CompoundAssignOperator::Create( |
15402 | C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc, |
15403 | FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: CompResultTy); |
15404 | } |
15405 | |
15406 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison |
15407 | /// operators are mixed in a way that suggests that the programmer forgot that |
15408 | /// comparison operators have higher precedence. The most typical example of |
15409 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". |
15410 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, |
15411 | SourceLocation OpLoc, Expr *LHSExpr, |
15412 | Expr *RHSExpr) { |
15413 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr); |
15414 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: RHSExpr); |
15415 | |
15416 | // Check that one of the sides is a comparison operator and the other isn't. |
15417 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); |
15418 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); |
15419 | if (isLeftComp == isRightComp) |
15420 | return; |
15421 | |
15422 | // Bitwise operations are sometimes used as eager logical ops. |
15423 | // Don't diagnose this. |
15424 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); |
15425 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); |
15426 | if (isLeftBitwise || isRightBitwise) |
15427 | return; |
15428 | |
15429 | SourceRange DiagRange = isLeftComp |
15430 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) |
15431 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); |
15432 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); |
15433 | SourceRange ParensRange = |
15434 | isLeftComp |
15435 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) |
15436 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); |
15437 | |
15438 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) |
15439 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; |
15440 | SuggestParentheses(Self, OpLoc, |
15441 | Self.PDiag(diag::note_precedence_silence) << OpStr, |
15442 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); |
15443 | SuggestParentheses(Self, OpLoc, |
15444 | Self.PDiag(diag::note_precedence_bitwise_first) |
15445 | << BinaryOperator::getOpcodeStr(Opc), |
15446 | ParensRange); |
15447 | } |
15448 | |
15449 | /// It accepts a '&&' expr that is inside a '||' one. |
15450 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression |
15451 | /// in parentheses. |
15452 | static void |
15453 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, |
15454 | BinaryOperator *Bop) { |
15455 | assert(Bop->getOpcode() == BO_LAnd); |
15456 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) |
15457 | << Bop->getSourceRange() << OpLoc; |
15458 | SuggestParentheses(Self, Bop->getOperatorLoc(), |
15459 | Self.PDiag(diag::note_precedence_silence) |
15460 | << Bop->getOpcodeStr(), |
15461 | Bop->getSourceRange()); |
15462 | } |
15463 | |
15464 | /// Look for '&&' in the left hand of a '||' expr. |
15465 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, |
15466 | Expr *LHSExpr, Expr *RHSExpr) { |
15467 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: LHSExpr)) { |
15468 | if (Bop->getOpcode() == BO_LAnd) { |
15469 | // If it's "string_literal && a || b" don't warn since the precedence |
15470 | // doesn't matter. |
15471 | if (!isa<StringLiteral>(Val: Bop->getLHS()->IgnoreParenImpCasts())) |
15472 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
15473 | } else if (Bop->getOpcode() == BO_LOr) { |
15474 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: Bop->getRHS())) { |
15475 | // If it's "a || b && string_literal || c" we didn't warn earlier for |
15476 | // "a || b && string_literal", but warn now. |
15477 | if (RBop->getOpcode() == BO_LAnd && |
15478 | isa<StringLiteral>(Val: RBop->getRHS()->IgnoreParenImpCasts())) |
15479 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop); |
15480 | } |
15481 | } |
15482 | } |
15483 | } |
15484 | |
15485 | /// Look for '&&' in the right hand of a '||' expr. |
15486 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, |
15487 | Expr *LHSExpr, Expr *RHSExpr) { |
15488 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: RHSExpr)) { |
15489 | if (Bop->getOpcode() == BO_LAnd) { |
15490 | // If it's "a || b && string_literal" don't warn since the precedence |
15491 | // doesn't matter. |
15492 | if (!isa<StringLiteral>(Val: Bop->getRHS()->IgnoreParenImpCasts())) |
15493 | return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop); |
15494 | } |
15495 | } |
15496 | } |
15497 | |
15498 | /// Look for bitwise op in the left or right hand of a bitwise op with |
15499 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps |
15500 | /// the '&' expression in parentheses. |
15501 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, |
15502 | SourceLocation OpLoc, Expr *SubExpr) { |
15503 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
15504 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { |
15505 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) |
15506 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) |
15507 | << Bop->getSourceRange() << OpLoc; |
15508 | SuggestParentheses(S, Bop->getOperatorLoc(), |
15509 | S.PDiag(diag::note_precedence_silence) |
15510 | << Bop->getOpcodeStr(), |
15511 | Bop->getSourceRange()); |
15512 | } |
15513 | } |
15514 | } |
15515 | |
15516 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, |
15517 | Expr *SubExpr, StringRef Shift) { |
15518 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: SubExpr)) { |
15519 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { |
15520 | StringRef Op = Bop->getOpcodeStr(); |
15521 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) |
15522 | << Bop->getSourceRange() << OpLoc << Shift << Op; |
15523 | SuggestParentheses(S, Bop->getOperatorLoc(), |
15524 | S.PDiag(diag::note_precedence_silence) << Op, |
15525 | Bop->getSourceRange()); |
15526 | } |
15527 | } |
15528 | } |
15529 | |
15530 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, |
15531 | Expr *LHSExpr, Expr *RHSExpr) { |
15532 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr); |
15533 | if (!OCE) |
15534 | return; |
15535 | |
15536 | FunctionDecl *FD = OCE->getDirectCallee(); |
15537 | if (!FD || !FD->isOverloadedOperator()) |
15538 | return; |
15539 | |
15540 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); |
15541 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) |
15542 | return; |
15543 | |
15544 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) |
15545 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() |
15546 | << (Kind == OO_LessLess); |
15547 | SuggestParentheses(S, OCE->getOperatorLoc(), |
15548 | S.PDiag(diag::note_precedence_silence) |
15549 | << (Kind == OO_LessLess ? "<<": ">>"), |
15550 | OCE->getSourceRange()); |
15551 | SuggestParentheses( |
15552 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), |
15553 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); |
15554 | } |
15555 | |
15556 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky |
15557 | /// precedence. |
15558 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, |
15559 | SourceLocation OpLoc, Expr *LHSExpr, |
15560 | Expr *RHSExpr){ |
15561 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". |
15562 | if (BinaryOperator::isBitwiseOp(Opc)) |
15563 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); |
15564 | |
15565 | // Diagnose "arg1 & arg2 | arg3" |
15566 | if ((Opc == BO_Or || Opc == BO_Xor) && |
15567 | !OpLoc.isMacroID()/* Don't warn in macros. */) { |
15568 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: LHSExpr); |
15569 | DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: RHSExpr); |
15570 | } |
15571 | |
15572 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. |
15573 | // We don't warn for 'assert(a || b && "bad")' since this is safe. |
15574 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { |
15575 | DiagnoseLogicalAndInLogicalOrLHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15576 | DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15577 | } |
15578 | |
15579 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext())) |
15580 | || Opc == BO_Shr) { |
15581 | StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc); |
15582 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift); |
15583 | DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift); |
15584 | } |
15585 | |
15586 | // Warn on overloaded shift operators and comparisons, such as: |
15587 | // cout << 5 == 4; |
15588 | if (BinaryOperator::isComparisonOp(Opc)) |
15589 | DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr); |
15590 | } |
15591 | |
15592 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, |
15593 | tok::TokenKind Kind, |
15594 | Expr *LHSExpr, Expr *RHSExpr) { |
15595 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); |
15596 | assert(LHSExpr && "ActOnBinOp(): missing left expression"); |
15597 | assert(RHSExpr && "ActOnBinOp(): missing right expression"); |
15598 | |
15599 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" |
15600 | DiagnoseBinOpPrecedence(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr); |
15601 | |
15602 | BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc) |
15603 | ? BuiltinCountedByRefKind::Assignment |
15604 | : BuiltinCountedByRefKind::BinaryExpr; |
15605 | |
15606 | CheckInvalidBuiltinCountedByRef(E: LHSExpr, K); |
15607 | CheckInvalidBuiltinCountedByRef(E: RHSExpr, K); |
15608 | |
15609 | return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr); |
15610 | } |
15611 | |
15612 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, |
15613 | UnresolvedSetImpl &Functions) { |
15614 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); |
15615 | if (OverOp != OO_None && OverOp != OO_Equal) |
15616 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
15617 | |
15618 | // In C++20 onwards, we may have a second operator to look up. |
15619 | if (getLangOpts().CPlusPlus20) { |
15620 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp)) |
15621 | LookupOverloadedOperatorName(Op: ExtraOp, S, Functions); |
15622 | } |
15623 | } |
15624 | |
15625 | /// Build an overloaded binary operator expression in the given scope. |
15626 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, |
15627 | BinaryOperatorKind Opc, |
15628 | Expr *LHS, Expr *RHS) { |
15629 | switch (Opc) { |
15630 | case BO_Assign: |
15631 | // In the non-overloaded case, we warn about self-assignment (x = x) for |
15632 | // both simple assignment and certain compound assignments where algebra |
15633 | // tells us the operation yields a constant result. When the operator is |
15634 | // overloaded, we can't do the latter because we don't want to assume that |
15635 | // those algebraic identities still apply; for example, a path-building |
15636 | // library might use operator/= to append paths. But it's still reasonable |
15637 | // to assume that simple assignment is just moving/copying values around |
15638 | // and so self-assignment is likely a bug. |
15639 | DiagnoseSelfAssignment(S, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: false); |
15640 | [[fallthrough]]; |
15641 | case BO_DivAssign: |
15642 | case BO_RemAssign: |
15643 | case BO_SubAssign: |
15644 | case BO_AndAssign: |
15645 | case BO_OrAssign: |
15646 | case BO_XorAssign: |
15647 | CheckIdentityFieldAssignment(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: S); |
15648 | break; |
15649 | default: |
15650 | break; |
15651 | } |
15652 | |
15653 | // Find all of the overloaded operators visible from this point. |
15654 | UnresolvedSet<16> Functions; |
15655 | S.LookupBinOp(S: Sc, OpLoc, Opc, Functions); |
15656 | |
15657 | // Build the (potentially-overloaded, potentially-dependent) |
15658 | // binary operation. |
15659 | return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS); |
15660 | } |
15661 | |
15662 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, |
15663 | BinaryOperatorKind Opc, Expr *LHSExpr, |
15664 | Expr *RHSExpr, bool ForFoldExpression) { |
15665 | ExprResult LHS, RHS; |
15666 | std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *this, Opc, LHSExpr, RHSExpr); |
15667 | if (!LHS.isUsable() || !RHS.isUsable()) |
15668 | return ExprError(); |
15669 | LHSExpr = LHS.get(); |
15670 | RHSExpr = RHS.get(); |
15671 | |
15672 | // We want to end up calling one of SemaPseudoObject::checkAssignment |
15673 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if |
15674 | // both expressions are overloadable or either is type-dependent), |
15675 | // or CreateBuiltinBinOp (in any other case). We also want to get |
15676 | // any placeholder types out of the way. |
15677 | |
15678 | // Handle pseudo-objects in the LHS. |
15679 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { |
15680 | // Assignments with a pseudo-object l-value need special analysis. |
15681 | if (pty->getKind() == BuiltinType::PseudoObject && |
15682 | BinaryOperator::isAssignmentOp(Opc)) |
15683 | return PseudoObject().checkAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: RHSExpr); |
15684 | |
15685 | // Don't resolve overloads if the other type is overloadable. |
15686 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { |
15687 | // We can't actually test that if we still have a placeholder, |
15688 | // though. Fortunately, none of the exceptions we see in that |
15689 | // code below are valid when the LHS is an overload set. Note |
15690 | // that an overload set can be dependently-typed, but it never |
15691 | // instantiates to having an overloadable type. |
15692 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
15693 | if (resolvedRHS.isInvalid()) return ExprError(); |
15694 | RHSExpr = resolvedRHS.get(); |
15695 | |
15696 | if (RHSExpr->isTypeDependent() || |
15697 | RHSExpr->getType()->isOverloadableType()) |
15698 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15699 | } |
15700 | |
15701 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function |
15702 | // template, diagnose the missing 'template' keyword instead of diagnosing |
15703 | // an invalid use of a bound member function. |
15704 | // |
15705 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due |
15706 | // to C++1z [over.over]/1.4, but we already checked for that case above. |
15707 | if (Opc == BO_LT && inTemplateInstantiation() && |
15708 | (pty->getKind() == BuiltinType::BoundMember || |
15709 | pty->getKind() == BuiltinType::Overload)) { |
15710 | auto *OE = dyn_cast<OverloadExpr>(Val: LHSExpr); |
15711 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && |
15712 | llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) { |
15713 | return isa<FunctionTemplateDecl>(Val: ND); |
15714 | })) { |
15715 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() |
15716 | : OE->getNameLoc(), |
15717 | diag::err_template_kw_missing) |
15718 | << OE->getName().getAsIdentifierInfo(); |
15719 | return ExprError(); |
15720 | } |
15721 | } |
15722 | |
15723 | ExprResult LHS = CheckPlaceholderExpr(E: LHSExpr); |
15724 | if (LHS.isInvalid()) return ExprError(); |
15725 | LHSExpr = LHS.get(); |
15726 | } |
15727 | |
15728 | // Handle pseudo-objects in the RHS. |
15729 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { |
15730 | // An overload in the RHS can potentially be resolved by the type |
15731 | // being assigned to. |
15732 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { |
15733 | if (getLangOpts().CPlusPlus && |
15734 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
15735 | LHSExpr->getType()->isOverloadableType())) |
15736 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15737 | |
15738 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, |
15739 | ForFoldExpression); |
15740 | } |
15741 | |
15742 | // Don't resolve overloads if the other type is overloadable. |
15743 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && |
15744 | LHSExpr->getType()->isOverloadableType()) |
15745 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15746 | |
15747 | ExprResult resolvedRHS = CheckPlaceholderExpr(E: RHSExpr); |
15748 | if (!resolvedRHS.isUsable()) return ExprError(); |
15749 | RHSExpr = resolvedRHS.get(); |
15750 | } |
15751 | |
15752 | if (getLangOpts().CPlusPlus) { |
15753 | // Otherwise, build an overloaded op if either expression is type-dependent |
15754 | // or has an overloadable type. |
15755 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
15756 | LHSExpr->getType()->isOverloadableType() || |
15757 | RHSExpr->getType()->isOverloadableType()) |
15758 | return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr); |
15759 | } |
15760 | |
15761 | if (getLangOpts().RecoveryAST && |
15762 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { |
15763 | assert(!getLangOpts().CPlusPlus); |
15764 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && |
15765 | "Should only occur in error-recovery path."); |
15766 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
15767 | // C [6.15.16] p3: |
15768 | // An assignment expression has the value of the left operand after the |
15769 | // assignment, but is not an lvalue. |
15770 | return CompoundAssignOperator::Create( |
15771 | C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, |
15772 | ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary, |
15773 | opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides()); |
15774 | QualType ResultType; |
15775 | switch (Opc) { |
15776 | case BO_Assign: |
15777 | ResultType = LHSExpr->getType().getUnqualifiedType(); |
15778 | break; |
15779 | case BO_LT: |
15780 | case BO_GT: |
15781 | case BO_LE: |
15782 | case BO_GE: |
15783 | case BO_EQ: |
15784 | case BO_NE: |
15785 | case BO_LAnd: |
15786 | case BO_LOr: |
15787 | // These operators have a fixed result type regardless of operands. |
15788 | ResultType = Context.IntTy; |
15789 | break; |
15790 | case BO_Comma: |
15791 | ResultType = RHSExpr->getType(); |
15792 | break; |
15793 | default: |
15794 | ResultType = Context.DependentTy; |
15795 | break; |
15796 | } |
15797 | return BinaryOperator::Create(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType, |
15798 | VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc, |
15799 | FPFeatures: CurFPFeatureOverrides()); |
15800 | } |
15801 | |
15802 | // Build a built-in binary operation. |
15803 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression); |
15804 | } |
15805 | |
15806 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { |
15807 | if (T.isNull() || T->isDependentType()) |
15808 | return false; |
15809 | |
15810 | if (!Ctx.isPromotableIntegerType(T)) |
15811 | return true; |
15812 | |
15813 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(T: Ctx.IntTy); |
15814 | } |
15815 | |
15816 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, |
15817 | UnaryOperatorKind Opc, Expr *InputExpr, |
15818 | bool IsAfterAmp) { |
15819 | ExprResult Input = InputExpr; |
15820 | ExprValueKind VK = VK_PRValue; |
15821 | ExprObjectKind OK = OK_Ordinary; |
15822 | QualType resultType; |
15823 | bool CanOverflow = false; |
15824 | |
15825 | bool ConvertHalfVec = false; |
15826 | if (getLangOpts().OpenCL) { |
15827 | QualType Ty = InputExpr->getType(); |
15828 | // The only legal unary operation for atomics is '&'. |
15829 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || |
15830 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
15831 | // only with a builtin functions and therefore should be disallowed here. |
15832 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() |
15833 | || Ty->isBlockPointerType())) { |
15834 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15835 | << InputExpr->getType() |
15836 | << Input.get()->getSourceRange()); |
15837 | } |
15838 | } |
15839 | |
15840 | if (getLangOpts().HLSL && OpLoc.isValid()) { |
15841 | if (Opc == UO_AddrOf) |
15842 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); |
15843 | if (Opc == UO_Deref) |
15844 | return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); |
15845 | } |
15846 | |
15847 | if (InputExpr->isTypeDependent() && |
15848 | InputExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Dependent)) { |
15849 | resultType = Context.DependentTy; |
15850 | } else { |
15851 | switch (Opc) { |
15852 | case UO_PreInc: |
15853 | case UO_PreDec: |
15854 | case UO_PostInc: |
15855 | case UO_PostDec: |
15856 | resultType = |
15857 | CheckIncrementDecrementOperand(S&: *this, Op: Input.get(), VK, OK, OpLoc, |
15858 | IsInc: Opc == UO_PreInc || Opc == UO_PostInc, |
15859 | IsPrefix: Opc == UO_PreInc || Opc == UO_PreDec); |
15860 | CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType); |
15861 | break; |
15862 | case UO_AddrOf: |
15863 | resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc); |
15864 | CheckAddressOfNoDeref(E: InputExpr); |
15865 | RecordModifiableNonNullParam(S&: *this, Exp: InputExpr); |
15866 | break; |
15867 | case UO_Deref: { |
15868 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
15869 | if (Input.isInvalid()) |
15870 | return ExprError(); |
15871 | resultType = |
15872 | CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp); |
15873 | break; |
15874 | } |
15875 | case UO_Plus: |
15876 | case UO_Minus: |
15877 | CanOverflow = Opc == UO_Minus && |
15878 | isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType()); |
15879 | Input = UsualUnaryConversions(E: Input.get()); |
15880 | if (Input.isInvalid()) |
15881 | return ExprError(); |
15882 | // Unary plus and minus require promoting an operand of half vector to a |
15883 | // float vector and truncating the result back to a half vector. For now, |
15884 | // we do this only when HalfArgsAndReturns is set (that is, when the |
15885 | // target is arm or arm64). |
15886 | ConvertHalfVec = needsConversionOfHalfVec(OpRequiresConversion: true, Ctx&: Context, E0: Input.get()); |
15887 | |
15888 | // If the operand is a half vector, promote it to a float vector. |
15889 | if (ConvertHalfVec) |
15890 | Input = convertVector(Input.get(), Context.FloatTy, *this); |
15891 | resultType = Input.get()->getType(); |
15892 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 |
15893 | break; |
15894 | else if (resultType->isVectorType() && |
15895 | // The z vector extensions don't allow + or - with bool vectors. |
15896 | (!Context.getLangOpts().ZVector || |
15897 | resultType->castAs<VectorType>()->getVectorKind() != |
15898 | VectorKind::AltiVecBool)) |
15899 | break; |
15900 | else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and - |
15901 | break; |
15902 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 |
15903 | Opc == UO_Plus && resultType->isPointerType()) |
15904 | break; |
15905 | |
15906 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15907 | << resultType << Input.get()->getSourceRange()); |
15908 | |
15909 | case UO_Not: // bitwise complement |
15910 | Input = UsualUnaryConversions(E: Input.get()); |
15911 | if (Input.isInvalid()) |
15912 | return ExprError(); |
15913 | resultType = Input.get()->getType(); |
15914 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. |
15915 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) |
15916 | // C99 does not support '~' for complex conjugation. |
15917 | Diag(OpLoc, diag::ext_integer_complement_complex) |
15918 | << resultType << Input.get()->getSourceRange(); |
15919 | else if (resultType->hasIntegerRepresentation()) |
15920 | break; |
15921 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { |
15922 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate |
15923 | // on vector float types. |
15924 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
15925 | if (!T->isIntegerType()) |
15926 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15927 | << resultType << Input.get()->getSourceRange()); |
15928 | } else { |
15929 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15930 | << resultType << Input.get()->getSourceRange()); |
15931 | } |
15932 | break; |
15933 | |
15934 | case UO_LNot: // logical negation |
15935 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). |
15936 | Input = DefaultFunctionArrayLvalueConversion(E: Input.get()); |
15937 | if (Input.isInvalid()) |
15938 | return ExprError(); |
15939 | resultType = Input.get()->getType(); |
15940 | |
15941 | // Though we still have to promote half FP to float... |
15942 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { |
15943 | Input = ImpCastExprToType(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast) |
15944 | .get(); |
15945 | resultType = Context.FloatTy; |
15946 | } |
15947 | |
15948 | // WebAsembly tables can't be used in unary expressions. |
15949 | if (resultType->isPointerType() && |
15950 | resultType->getPointeeType().isWebAssemblyReferenceType()) { |
15951 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15952 | << resultType << Input.get()->getSourceRange()); |
15953 | } |
15954 | |
15955 | if (resultType->isScalarType() && !isScopedEnumerationType(T: resultType)) { |
15956 | // C99 6.5.3.3p1: ok, fallthrough; |
15957 | if (Context.getLangOpts().CPlusPlus) { |
15958 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: |
15959 | // operand contextually converted to bool. |
15960 | Input = ImpCastExprToType(E: Input.get(), Type: Context.BoolTy, |
15961 | CK: ScalarTypeToBooleanCastKind(ScalarTy: resultType)); |
15962 | } else if (Context.getLangOpts().OpenCL && |
15963 | Context.getLangOpts().OpenCLVersion < 120) { |
15964 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
15965 | // operate on scalar float types. |
15966 | if (!resultType->isIntegerType() && !resultType->isPointerType()) |
15967 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15968 | << resultType << Input.get()->getSourceRange()); |
15969 | } |
15970 | } else if (resultType->isExtVectorType()) { |
15971 | if (Context.getLangOpts().OpenCL && |
15972 | Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { |
15973 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
15974 | // operate on vector float types. |
15975 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); |
15976 | if (!T->isIntegerType()) |
15977 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15978 | << resultType << Input.get()->getSourceRange()); |
15979 | } |
15980 | // Vector logical not returns the signed variant of the operand type. |
15981 | resultType = GetSignedVectorType(V: resultType); |
15982 | break; |
15983 | } else if (Context.getLangOpts().CPlusPlus && |
15984 | resultType->isVectorType()) { |
15985 | const VectorType *VTy = resultType->castAs<VectorType>(); |
15986 | if (VTy->getVectorKind() != VectorKind::Generic) |
15987 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15988 | << resultType << Input.get()->getSourceRange()); |
15989 | |
15990 | // Vector logical not returns the signed variant of the operand type. |
15991 | resultType = GetSignedVectorType(V: resultType); |
15992 | break; |
15993 | } else { |
15994 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
15995 | << resultType << Input.get()->getSourceRange()); |
15996 | } |
15997 | |
15998 | // LNot always has type int. C99 6.5.3.3p5. |
15999 | // In C++, it's bool. C++ 5.3.1p8 |
16000 | resultType = Context.getLogicalOperationType(); |
16001 | break; |
16002 | case UO_Real: |
16003 | case UO_Imag: |
16004 | resultType = CheckRealImagOperand(S&: *this, V&: Input, Loc: OpLoc, IsReal: Opc == UO_Real); |
16005 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps |
16006 | // ordinary complex l-values to ordinary l-values and all other values to |
16007 | // r-values. |
16008 | if (Input.isInvalid()) |
16009 | return ExprError(); |
16010 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { |
16011 | if (Input.get()->isGLValue() && |
16012 | Input.get()->getObjectKind() == OK_Ordinary) |
16013 | VK = Input.get()->getValueKind(); |
16014 | } else if (!getLangOpts().CPlusPlus) { |
16015 | // In C, a volatile scalar is read by __imag. In C++, it is not. |
16016 | Input = DefaultLvalueConversion(E: Input.get()); |
16017 | } |
16018 | break; |
16019 | case UO_Extension: |
16020 | resultType = Input.get()->getType(); |
16021 | VK = Input.get()->getValueKind(); |
16022 | OK = Input.get()->getObjectKind(); |
16023 | break; |
16024 | case UO_Coawait: |
16025 | // It's unnecessary to represent the pass-through operator co_await in the |
16026 | // AST; just return the input expression instead. |
16027 | assert(!Input.get()->getType()->isDependentType() && |
16028 | "the co_await expression must be non-dependant before " |
16029 | "building operator co_await"); |
16030 | return Input; |
16031 | } |
16032 | } |
16033 | if (resultType.isNull() || Input.isInvalid()) |
16034 | return ExprError(); |
16035 | |
16036 | // Check for array bounds violations in the operand of the UnaryOperator, |
16037 | // except for the '*' and '&' operators that have to be handled specially |
16038 | // by CheckArrayAccess (as there are special cases like &array[arraysize] |
16039 | // that are explicitly defined as valid by the standard). |
16040 | if (Opc != UO_AddrOf && Opc != UO_Deref) |
16041 | CheckArrayAccess(E: Input.get()); |
16042 | |
16043 | auto *UO = |
16044 | UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK, |
16045 | l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides()); |
16046 | |
16047 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && |
16048 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && |
16049 | !isUnevaluatedContext()) |
16050 | ExprEvalContexts.back().PossibleDerefs.insert(UO); |
16051 | |
16052 | // Convert the result back to a half vector. |
16053 | if (ConvertHalfVec) |
16054 | return convertVector(UO, Context.HalfTy, *this); |
16055 | return UO; |
16056 | } |
16057 | |
16058 | bool Sema::isQualifiedMemberAccess(Expr *E) { |
16059 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
16060 | if (!DRE->getQualifier()) |
16061 | return false; |
16062 | |
16063 | ValueDecl *VD = DRE->getDecl(); |
16064 | if (!VD->isCXXClassMember()) |
16065 | return false; |
16066 | |
16067 | if (isa<FieldDecl>(Val: VD) || isa<IndirectFieldDecl>(Val: VD)) |
16068 | return true; |
16069 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD)) |
16070 | return Method->isImplicitObjectMemberFunction(); |
16071 | |
16072 | return false; |
16073 | } |
16074 | |
16075 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) { |
16076 | if (!ULE->getQualifier()) |
16077 | return false; |
16078 | |
16079 | for (NamedDecl *D : ULE->decls()) { |
16080 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { |
16081 | if (Method->isImplicitObjectMemberFunction()) |
16082 | return true; |
16083 | } else { |
16084 | // Overload set does not contain methods. |
16085 | break; |
16086 | } |
16087 | } |
16088 | |
16089 | return false; |
16090 | } |
16091 | |
16092 | return false; |
16093 | } |
16094 | |
16095 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
16096 | UnaryOperatorKind Opc, Expr *Input, |
16097 | bool IsAfterAmp) { |
16098 | // First things first: handle placeholders so that the |
16099 | // overloaded-operator check considers the right type. |
16100 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { |
16101 | // Increment and decrement of pseudo-object references. |
16102 | if (pty->getKind() == BuiltinType::PseudoObject && |
16103 | UnaryOperator::isIncrementDecrementOp(Op: Opc)) |
16104 | return PseudoObject().checkIncDec(S, OpLoc, Opcode: Opc, Op: Input); |
16105 | |
16106 | // extension is always a builtin operator. |
16107 | if (Opc == UO_Extension) |
16108 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
16109 | |
16110 | // & gets special logic for several kinds of placeholder. |
16111 | // The builtin code knows what to do. |
16112 | if (Opc == UO_AddrOf && |
16113 | (pty->getKind() == BuiltinType::Overload || |
16114 | pty->getKind() == BuiltinType::UnknownAny || |
16115 | pty->getKind() == BuiltinType::BoundMember)) |
16116 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input); |
16117 | |
16118 | // Anything else needs to be handled now. |
16119 | ExprResult Result = CheckPlaceholderExpr(E: Input); |
16120 | if (Result.isInvalid()) return ExprError(); |
16121 | Input = Result.get(); |
16122 | } |
16123 | |
16124 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && |
16125 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && |
16126 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) { |
16127 | // Find all of the overloaded operators visible from this point. |
16128 | UnresolvedSet<16> Functions; |
16129 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); |
16130 | if (S && OverOp != OO_None) |
16131 | LookupOverloadedOperatorName(Op: OverOp, S, Functions); |
16132 | |
16133 | return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input); |
16134 | } |
16135 | |
16136 | return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp); |
16137 | } |
16138 | |
16139 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, |
16140 | Expr *Input, bool IsAfterAmp) { |
16141 | return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input, |
16142 | IsAfterAmp); |
16143 | } |
16144 | |
16145 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
16146 | LabelDecl *TheDecl) { |
16147 | TheDecl->markUsed(Context); |
16148 | // Create the AST node. The address of a label always has type 'void*'. |
16149 | auto *Res = new (Context) AddrLabelExpr( |
16150 | OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy)); |
16151 | |
16152 | if (getCurFunction()) |
16153 | getCurFunction()->AddrLabels.push_back(Elt: Res); |
16154 | |
16155 | return Res; |
16156 | } |
16157 | |
16158 | void Sema::ActOnStartStmtExpr() { |
16159 | PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context); |
16160 | // Make sure we diagnose jumping into a statement expression. |
16161 | setFunctionHasBranchProtectedScope(); |
16162 | } |
16163 | |
16164 | void Sema::ActOnStmtExprError() { |
16165 | // Note that function is also called by TreeTransform when leaving a |
16166 | // StmtExpr scope without rebuilding anything. |
16167 | |
16168 | DiscardCleanupsInEvaluationContext(); |
16169 | PopExpressionEvaluationContext(); |
16170 | } |
16171 | |
16172 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, |
16173 | SourceLocation RPLoc) { |
16174 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S)); |
16175 | } |
16176 | |
16177 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
16178 | SourceLocation RPLoc, unsigned TemplateDepth) { |
16179 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); |
16180 | CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt); |
16181 | |
16182 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
16183 | DiscardCleanupsInEvaluationContext(); |
16184 | assert(!Cleanup.exprNeedsCleanups() && |
16185 | "cleanups within StmtExpr not correctly bound!"); |
16186 | PopExpressionEvaluationContext(); |
16187 | |
16188 | // FIXME: there are a variety of strange constraints to enforce here, for |
16189 | // example, it is not possible to goto into a stmt expression apparently. |
16190 | // More semantic analysis is needed. |
16191 | |
16192 | // If there are sub-stmts in the compound stmt, take the type of the last one |
16193 | // as the type of the stmtexpr. |
16194 | QualType Ty = Context.VoidTy; |
16195 | bool StmtExprMayBindToTemp = false; |
16196 | if (!Compound->body_empty()) { |
16197 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. |
16198 | if (const auto *LastStmt = |
16199 | dyn_cast<ValueStmt>(Val: Compound->getStmtExprResult())) { |
16200 | if (const Expr *Value = LastStmt->getExprStmt()) { |
16201 | StmtExprMayBindToTemp = true; |
16202 | Ty = Value->getType(); |
16203 | } |
16204 | } |
16205 | } |
16206 | |
16207 | // FIXME: Check that expression type is complete/non-abstract; statement |
16208 | // expressions are not lvalues. |
16209 | Expr *ResStmtExpr = |
16210 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); |
16211 | if (StmtExprMayBindToTemp) |
16212 | return MaybeBindToTemporary(E: ResStmtExpr); |
16213 | return ResStmtExpr; |
16214 | } |
16215 | |
16216 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { |
16217 | if (ER.isInvalid()) |
16218 | return ExprError(); |
16219 | |
16220 | // Do function/array conversion on the last expression, but not |
16221 | // lvalue-to-rvalue. However, initialize an unqualified type. |
16222 | ER = DefaultFunctionArrayConversion(E: ER.get()); |
16223 | if (ER.isInvalid()) |
16224 | return ExprError(); |
16225 | Expr *E = ER.get(); |
16226 | |
16227 | if (E->isTypeDependent()) |
16228 | return E; |
16229 | |
16230 | // In ARC, if the final expression ends in a consume, splice |
16231 | // the consume out and bind it later. In the alternate case |
16232 | // (when dealing with a retainable type), the result |
16233 | // initialization will create a produce. In both cases the |
16234 | // result will be +1, and we'll need to balance that out with |
16235 | // a bind. |
16236 | auto *Cast = dyn_cast<ImplicitCastExpr>(Val: E); |
16237 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) |
16238 | return Cast->getSubExpr(); |
16239 | |
16240 | // FIXME: Provide a better location for the initialization. |
16241 | return PerformCopyInitialization( |
16242 | Entity: InitializedEntity::InitializeStmtExprResult( |
16243 | ReturnLoc: E->getBeginLoc(), Type: E->getType().getAtomicUnqualifiedType()), |
16244 | EqualLoc: SourceLocation(), Init: E); |
16245 | } |
16246 | |
16247 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
16248 | TypeSourceInfo *TInfo, |
16249 | ArrayRef<OffsetOfComponent> Components, |
16250 | SourceLocation RParenLoc) { |
16251 | QualType ArgTy = TInfo->getType(); |
16252 | bool Dependent = ArgTy->isDependentType(); |
16253 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); |
16254 | |
16255 | // We must have at least one component that refers to the type, and the first |
16256 | // one is known to be a field designator. Verify that the ArgTy represents |
16257 | // a struct/union/class. |
16258 | if (!Dependent && !ArgTy->isRecordType()) |
16259 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) |
16260 | << ArgTy << TypeRange); |
16261 | |
16262 | // Type must be complete per C99 7.17p3 because a declaring a variable |
16263 | // with an incomplete type would be ill-formed. |
16264 | if (!Dependent |
16265 | && RequireCompleteType(BuiltinLoc, ArgTy, |
16266 | diag::err_offsetof_incomplete_type, TypeRange)) |
16267 | return ExprError(); |
16268 | |
16269 | bool DidWarnAboutNonPOD = false; |
16270 | QualType CurrentType = ArgTy; |
16271 | SmallVector<OffsetOfNode, 4> Comps; |
16272 | SmallVector<Expr*, 4> Exprs; |
16273 | for (const OffsetOfComponent &OC : Components) { |
16274 | if (OC.isBrackets) { |
16275 | // Offset of an array sub-field. TODO: Should we allow vector elements? |
16276 | if (!CurrentType->isDependentType()) { |
16277 | const ArrayType *AT = Context.getAsArrayType(T: CurrentType); |
16278 | if(!AT) |
16279 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) |
16280 | << CurrentType); |
16281 | CurrentType = AT->getElementType(); |
16282 | } else |
16283 | CurrentType = Context.DependentTy; |
16284 | |
16285 | ExprResult IdxRval = DefaultLvalueConversion(E: static_cast<Expr*>(OC.U.E)); |
16286 | if (IdxRval.isInvalid()) |
16287 | return ExprError(); |
16288 | Expr *Idx = IdxRval.get(); |
16289 | |
16290 | // The expression must be an integral expression. |
16291 | // FIXME: An integral constant expression? |
16292 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && |
16293 | !Idx->getType()->isIntegerType()) |
16294 | return ExprError( |
16295 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) |
16296 | << Idx->getSourceRange()); |
16297 | |
16298 | // Record this array index. |
16299 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); |
16300 | Exprs.push_back(Elt: Idx); |
16301 | continue; |
16302 | } |
16303 | |
16304 | // Offset of a field. |
16305 | if (CurrentType->isDependentType()) { |
16306 | // We have the offset of a field, but we can't look into the dependent |
16307 | // type. Just record the identifier of the field. |
16308 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); |
16309 | CurrentType = Context.DependentTy; |
16310 | continue; |
16311 | } |
16312 | |
16313 | // We need to have a complete type to look into. |
16314 | if (RequireCompleteType(OC.LocStart, CurrentType, |
16315 | diag::err_offsetof_incomplete_type)) |
16316 | return ExprError(); |
16317 | |
16318 | // Look for the designated field. |
16319 | const RecordType *RC = CurrentType->getAs<RecordType>(); |
16320 | if (!RC) |
16321 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) |
16322 | << CurrentType); |
16323 | RecordDecl *RD = RC->getDecl(); |
16324 | |
16325 | // C++ [lib.support.types]p5: |
16326 | // The macro offsetof accepts a restricted set of type arguments in this |
16327 | // International Standard. type shall be a POD structure or a POD union |
16328 | // (clause 9). |
16329 | // C++11 [support.types]p4: |
16330 | // If type is not a standard-layout class (Clause 9), the results are |
16331 | // undefined. |
16332 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
16333 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); |
16334 | unsigned DiagID = |
16335 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type |
16336 | : diag::ext_offsetof_non_pod_type; |
16337 | |
16338 | if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) { |
16339 | Diag(BuiltinLoc, DiagID) |
16340 | << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType; |
16341 | DidWarnAboutNonPOD = true; |
16342 | } |
16343 | } |
16344 | |
16345 | // Look for the field. |
16346 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); |
16347 | LookupQualifiedName(R, RD); |
16348 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); |
16349 | IndirectFieldDecl *IndirectMemberDecl = nullptr; |
16350 | if (!MemberDecl) { |
16351 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) |
16352 | MemberDecl = IndirectMemberDecl->getAnonField(); |
16353 | } |
16354 | |
16355 | if (!MemberDecl) { |
16356 | // Lookup could be ambiguous when looking up a placeholder variable |
16357 | // __builtin_offsetof(S, _). |
16358 | // In that case we would already have emitted a diagnostic |
16359 | if (!R.isAmbiguous()) |
16360 | Diag(BuiltinLoc, diag::err_no_member) |
16361 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd); |
16362 | return ExprError(); |
16363 | } |
16364 | |
16365 | // C99 7.17p3: |
16366 | // (If the specified member is a bit-field, the behavior is undefined.) |
16367 | // |
16368 | // We diagnose this as an error. |
16369 | if (MemberDecl->isBitField()) { |
16370 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) |
16371 | << MemberDecl->getDeclName() |
16372 | << SourceRange(BuiltinLoc, RParenLoc); |
16373 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); |
16374 | return ExprError(); |
16375 | } |
16376 | |
16377 | RecordDecl *Parent = MemberDecl->getParent(); |
16378 | if (IndirectMemberDecl) |
16379 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); |
16380 | |
16381 | // If the member was found in a base class, introduce OffsetOfNodes for |
16382 | // the base class indirections. |
16383 | CXXBasePaths Paths; |
16384 | if (IsDerivedFrom(Loc: OC.LocStart, Derived: CurrentType, Base: Context.getTypeDeclType(Parent), |
16385 | Paths)) { |
16386 | if (Paths.getDetectedVirtual()) { |
16387 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) |
16388 | << MemberDecl->getDeclName() |
16389 | << SourceRange(BuiltinLoc, RParenLoc); |
16390 | return ExprError(); |
16391 | } |
16392 | |
16393 | CXXBasePath &Path = Paths.front(); |
16394 | for (const CXXBasePathElement &B : Path) |
16395 | Comps.push_back(Elt: OffsetOfNode(B.Base)); |
16396 | } |
16397 | |
16398 | if (IndirectMemberDecl) { |
16399 | for (auto *FI : IndirectMemberDecl->chain()) { |
16400 | assert(isa<FieldDecl>(FI)); |
16401 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, |
16402 | cast<FieldDecl>(Val: FI), OC.LocEnd)); |
16403 | } |
16404 | } else |
16405 | Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); |
16406 | |
16407 | CurrentType = MemberDecl->getType().getNonReferenceType(); |
16408 | } |
16409 | |
16410 | return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo, |
16411 | comps: Comps, exprs: Exprs, RParenLoc); |
16412 | } |
16413 | |
16414 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, |
16415 | SourceLocation BuiltinLoc, |
16416 | SourceLocation TypeLoc, |
16417 | ParsedType ParsedArgTy, |
16418 | ArrayRef<OffsetOfComponent> Components, |
16419 | SourceLocation RParenLoc) { |
16420 | |
16421 | TypeSourceInfo *ArgTInfo; |
16422 | QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo); |
16423 | if (ArgTy.isNull()) |
16424 | return ExprError(); |
16425 | |
16426 | if (!ArgTInfo) |
16427 | ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc); |
16428 | |
16429 | return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc); |
16430 | } |
16431 | |
16432 | |
16433 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, |
16434 | Expr *CondExpr, |
16435 | Expr *LHSExpr, Expr *RHSExpr, |
16436 | SourceLocation RPLoc) { |
16437 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); |
16438 | |
16439 | ExprValueKind VK = VK_PRValue; |
16440 | ExprObjectKind OK = OK_Ordinary; |
16441 | QualType resType; |
16442 | bool CondIsTrue = false; |
16443 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { |
16444 | resType = Context.DependentTy; |
16445 | } else { |
16446 | // The conditional expression is required to be a constant expression. |
16447 | llvm::APSInt condEval(32); |
16448 | ExprResult CondICE = VerifyIntegerConstantExpression( |
16449 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); |
16450 | if (CondICE.isInvalid()) |
16451 | return ExprError(); |
16452 | CondExpr = CondICE.get(); |
16453 | CondIsTrue = condEval.getZExtValue(); |
16454 | |
16455 | // If the condition is > zero, then the AST type is the same as the LHSExpr. |
16456 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; |
16457 | |
16458 | resType = ActiveExpr->getType(); |
16459 | VK = ActiveExpr->getValueKind(); |
16460 | OK = ActiveExpr->getObjectKind(); |
16461 | } |
16462 | |
16463 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, |
16464 | resType, VK, OK, RPLoc, CondIsTrue); |
16465 | } |
16466 | |
16467 | //===----------------------------------------------------------------------===// |
16468 | // Clang Extensions. |
16469 | //===----------------------------------------------------------------------===// |
16470 | |
16471 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { |
16472 | BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc); |
16473 | |
16474 | if (LangOpts.CPlusPlus) { |
16475 | MangleNumberingContext *MCtx; |
16476 | Decl *ManglingContextDecl; |
16477 | std::tie(args&: MCtx, args&: ManglingContextDecl) = |
16478 | getCurrentMangleNumberContext(DC: Block->getDeclContext()); |
16479 | if (MCtx) { |
16480 | unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block); |
16481 | Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl); |
16482 | } |
16483 | } |
16484 | |
16485 | PushBlockScope(BlockScope: CurScope, Block); |
16486 | CurContext->addDecl(Block); |
16487 | if (CurScope) |
16488 | PushDeclContext(CurScope, Block); |
16489 | else |
16490 | CurContext = Block; |
16491 | |
16492 | getCurBlock()->HasImplicitReturnType = true; |
16493 | |
16494 | // Enter a new evaluation context to insulate the block from any |
16495 | // cleanups from the enclosing full-expression. |
16496 | PushExpressionEvaluationContext( |
16497 | NewContext: ExpressionEvaluationContext::PotentiallyEvaluated); |
16498 | } |
16499 | |
16500 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
16501 | Scope *CurScope) { |
16502 | assert(ParamInfo.getIdentifier() == nullptr && |
16503 | "block-id should have no identifier!"); |
16504 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); |
16505 | BlockScopeInfo *CurBlock = getCurBlock(); |
16506 | |
16507 | TypeSourceInfo *Sig = GetTypeForDeclarator(D&: ParamInfo); |
16508 | QualType T = Sig->getType(); |
16509 | DiagnoseUnexpandedParameterPack(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block); |
16510 | |
16511 | // GetTypeForDeclarator always produces a function type for a block |
16512 | // literal signature. Furthermore, it is always a FunctionProtoType |
16513 | // unless the function was written with a typedef. |
16514 | assert(T->isFunctionType() && |
16515 | "GetTypeForDeclarator made a non-function block signature"); |
16516 | |
16517 | // Look for an explicit signature in that function type. |
16518 | FunctionProtoTypeLoc ExplicitSignature; |
16519 | |
16520 | if ((ExplicitSignature = Sig->getTypeLoc() |
16521 | .getAsAdjusted<FunctionProtoTypeLoc>())) { |
16522 | |
16523 | // Check whether that explicit signature was synthesized by |
16524 | // GetTypeForDeclarator. If so, don't save that as part of the |
16525 | // written signature. |
16526 | if (ExplicitSignature.getLocalRangeBegin() == |
16527 | ExplicitSignature.getLocalRangeEnd()) { |
16528 | // This would be much cheaper if we stored TypeLocs instead of |
16529 | // TypeSourceInfos. |
16530 | TypeLoc Result = ExplicitSignature.getReturnLoc(); |
16531 | unsigned Size = Result.getFullDataSize(); |
16532 | Sig = Context.CreateTypeSourceInfo(T: Result.getType(), Size); |
16533 | Sig->getTypeLoc().initializeFullCopy(Other: Result, Size); |
16534 | |
16535 | ExplicitSignature = FunctionProtoTypeLoc(); |
16536 | } |
16537 | } |
16538 | |
16539 | CurBlock->TheDecl->setSignatureAsWritten(Sig); |
16540 | CurBlock->FunctionType = T; |
16541 | |
16542 | const auto *Fn = T->castAs<FunctionType>(); |
16543 | QualType RetTy = Fn->getReturnType(); |
16544 | bool isVariadic = |
16545 | (isa<FunctionProtoType>(Val: Fn) && cast<FunctionProtoType>(Val: Fn)->isVariadic()); |
16546 | |
16547 | CurBlock->TheDecl->setIsVariadic(isVariadic); |
16548 | |
16549 | // Context.DependentTy is used as a placeholder for a missing block |
16550 | // return type. TODO: what should we do with declarators like: |
16551 | // ^ * { ... } |
16552 | // If the answer is "apply template argument deduction".... |
16553 | if (RetTy != Context.DependentTy) { |
16554 | CurBlock->ReturnType = RetTy; |
16555 | CurBlock->TheDecl->setBlockMissingReturnType(false); |
16556 | CurBlock->HasImplicitReturnType = false; |
16557 | } |
16558 | |
16559 | // Push block parameters from the declarator if we had them. |
16560 | SmallVector<ParmVarDecl*, 8> Params; |
16561 | if (ExplicitSignature) { |
16562 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { |
16563 | ParmVarDecl *Param = ExplicitSignature.getParam(I); |
16564 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && |
16565 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { |
16566 | // Diagnose this as an extension in C17 and earlier. |
16567 | if (!getLangOpts().C23) |
16568 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23); |
16569 | } |
16570 | Params.push_back(Elt: Param); |
16571 | } |
16572 | |
16573 | // Fake up parameter variables if we have a typedef, like |
16574 | // ^ fntype { ... } |
16575 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { |
16576 | for (const auto &I : Fn->param_types()) { |
16577 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( |
16578 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); |
16579 | Params.push_back(Elt: Param); |
16580 | } |
16581 | } |
16582 | |
16583 | // Set the parameters on the block decl. |
16584 | if (!Params.empty()) { |
16585 | CurBlock->TheDecl->setParams(Params); |
16586 | CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(), |
16587 | /*CheckParameterNames=*/false); |
16588 | } |
16589 | |
16590 | // Finally we can process decl attributes. |
16591 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); |
16592 | |
16593 | // Put the parameter variables in scope. |
16594 | for (auto *AI : CurBlock->TheDecl->parameters()) { |
16595 | AI->setOwningFunction(CurBlock->TheDecl); |
16596 | |
16597 | // If this has an identifier, add it to the scope stack. |
16598 | if (AI->getIdentifier()) { |
16599 | CheckShadow(CurBlock->TheScope, AI); |
16600 | |
16601 | PushOnScopeChains(AI, CurBlock->TheScope); |
16602 | } |
16603 | |
16604 | if (AI->isInvalidDecl()) |
16605 | CurBlock->TheDecl->setInvalidDecl(); |
16606 | } |
16607 | } |
16608 | |
16609 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { |
16610 | // Leave the expression-evaluation context. |
16611 | DiscardCleanupsInEvaluationContext(); |
16612 | PopExpressionEvaluationContext(); |
16613 | |
16614 | // Pop off CurBlock, handle nested blocks. |
16615 | PopDeclContext(); |
16616 | PopFunctionScopeInfo(); |
16617 | } |
16618 | |
16619 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, |
16620 | Stmt *Body, Scope *CurScope) { |
16621 | // If blocks are disabled, emit an error. |
16622 | if (!LangOpts.Blocks) |
16623 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; |
16624 | |
16625 | // Leave the expression-evaluation context. |
16626 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
16627 | DiscardCleanupsInEvaluationContext(); |
16628 | assert(!Cleanup.exprNeedsCleanups() && |
16629 | "cleanups within block not correctly bound!"); |
16630 | PopExpressionEvaluationContext(); |
16631 | |
16632 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back()); |
16633 | BlockDecl *BD = BSI->TheDecl; |
16634 | |
16635 | maybeAddDeclWithEffects(D: BD); |
16636 | |
16637 | if (BSI->HasImplicitReturnType) |
16638 | deduceClosureReturnType(*BSI); |
16639 | |
16640 | QualType RetTy = Context.VoidTy; |
16641 | if (!BSI->ReturnType.isNull()) |
16642 | RetTy = BSI->ReturnType; |
16643 | |
16644 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); |
16645 | QualType BlockTy; |
16646 | |
16647 | // If the user wrote a function type in some form, try to use that. |
16648 | if (!BSI->FunctionType.isNull()) { |
16649 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); |
16650 | |
16651 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); |
16652 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(noReturn: true); |
16653 | |
16654 | // Turn protoless block types into nullary block types. |
16655 | if (isa<FunctionNoProtoType>(Val: FTy)) { |
16656 | FunctionProtoType::ExtProtoInfo EPI; |
16657 | EPI.ExtInfo = Ext; |
16658 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI); |
16659 | |
16660 | // Otherwise, if we don't need to change anything about the function type, |
16661 | // preserve its sugar structure. |
16662 | } else if (FTy->getReturnType() == RetTy && |
16663 | (!NoReturn || FTy->getNoReturnAttr())) { |
16664 | BlockTy = BSI->FunctionType; |
16665 | |
16666 | // Otherwise, make the minimal modifications to the function type. |
16667 | } else { |
16668 | const FunctionProtoType *FPT = cast<FunctionProtoType>(Val: FTy); |
16669 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
16670 | EPI.TypeQuals = Qualifiers(); |
16671 | EPI.ExtInfo = Ext; |
16672 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI); |
16673 | } |
16674 | |
16675 | // If we don't have a function type, just build one from nothing. |
16676 | } else { |
16677 | FunctionProtoType::ExtProtoInfo EPI; |
16678 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn); |
16679 | BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: {}, EPI); |
16680 | } |
16681 | |
16682 | DiagnoseUnusedParameters(Parameters: BD->parameters()); |
16683 | BlockTy = Context.getBlockPointerType(T: BlockTy); |
16684 | |
16685 | // If needed, diagnose invalid gotos and switches in the block. |
16686 | if (getCurFunction()->NeedsScopeChecking() && |
16687 | !PP.isCodeCompletionEnabled()) |
16688 | DiagnoseInvalidJumps(cast<CompoundStmt>(Val: Body)); |
16689 | |
16690 | BD->setBody(cast<CompoundStmt>(Val: Body)); |
16691 | |
16692 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) |
16693 | DiagnoseUnguardedAvailabilityViolations(BD); |
16694 | |
16695 | // Try to apply the named return value optimization. We have to check again |
16696 | // if we can do this, though, because blocks keep return statements around |
16697 | // to deduce an implicit return type. |
16698 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && |
16699 | !BD->isDependentContext()) |
16700 | computeNRVO(Body, BSI); |
16701 | |
16702 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || |
16703 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) |
16704 | checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(), |
16705 | UseContext: NonTrivialCUnionContext::FunctionReturn, |
16706 | NonTrivialKind: NTCUK_Destruct | NTCUK_Copy); |
16707 | |
16708 | PopDeclContext(); |
16709 | |
16710 | // Set the captured variables on the block. |
16711 | SmallVector<BlockDecl::Capture, 4> Captures; |
16712 | for (Capture &Cap : BSI->Captures) { |
16713 | if (Cap.isInvalid() || Cap.isThisCapture()) |
16714 | continue; |
16715 | // Cap.getVariable() is always a VarDecl because |
16716 | // blocks cannot capture structured bindings or other ValueDecl kinds. |
16717 | auto *Var = cast<VarDecl>(Val: Cap.getVariable()); |
16718 | Expr *CopyExpr = nullptr; |
16719 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { |
16720 | if (const RecordType *Record = |
16721 | Cap.getCaptureType()->getAs<RecordType>()) { |
16722 | // The capture logic needs the destructor, so make sure we mark it. |
16723 | // Usually this is unnecessary because most local variables have |
16724 | // their destructors marked at declaration time, but parameters are |
16725 | // an exception because it's technically only the call site that |
16726 | // actually requires the destructor. |
16727 | if (isa<ParmVarDecl>(Val: Var)) |
16728 | FinalizeVarWithDestructor(VD: Var, DeclInitType: Record); |
16729 | |
16730 | // Enter a separate potentially-evaluated context while building block |
16731 | // initializers to isolate their cleanups from those of the block |
16732 | // itself. |
16733 | // FIXME: Is this appropriate even when the block itself occurs in an |
16734 | // unevaluated operand? |
16735 | EnterExpressionEvaluationContext EvalContext( |
16736 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); |
16737 | |
16738 | SourceLocation Loc = Cap.getLocation(); |
16739 | |
16740 | ExprResult Result = BuildDeclarationNameExpr( |
16741 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); |
16742 | |
16743 | // According to the blocks spec, the capture of a variable from |
16744 | // the stack requires a const copy constructor. This is not true |
16745 | // of the copy/move done to move a __block variable to the heap. |
16746 | if (!Result.isInvalid() && |
16747 | !Result.get()->getType().isConstQualified()) { |
16748 | Result = ImpCastExprToType(E: Result.get(), |
16749 | Type: Result.get()->getType().withConst(), |
16750 | CK: CK_NoOp, VK: VK_LValue); |
16751 | } |
16752 | |
16753 | if (!Result.isInvalid()) { |
16754 | Result = PerformCopyInitialization( |
16755 | Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(), |
16756 | Type: Cap.getCaptureType()), |
16757 | EqualLoc: Loc, Init: Result.get()); |
16758 | } |
16759 | |
16760 | // Build a full-expression copy expression if initialization |
16761 | // succeeded and used a non-trivial constructor. Recover from |
16762 | // errors by pretending that the copy isn't necessary. |
16763 | if (!Result.isInvalid() && |
16764 | !cast<CXXConstructExpr>(Val: Result.get())->getConstructor() |
16765 | ->isTrivial()) { |
16766 | Result = MaybeCreateExprWithCleanups(SubExpr: Result); |
16767 | CopyExpr = Result.get(); |
16768 | } |
16769 | } |
16770 | } |
16771 | |
16772 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), |
16773 | CopyExpr); |
16774 | Captures.push_back(Elt: NewCap); |
16775 | } |
16776 | BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0); |
16777 | |
16778 | // Pop the block scope now but keep it alive to the end of this function. |
16779 | AnalysisBasedWarnings::Policy WP = |
16780 | AnalysisWarnings.getPolicyInEffectAt(Loc: Body->getEndLoc()); |
16781 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); |
16782 | |
16783 | BlockExpr *Result = new (Context) |
16784 | BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack); |
16785 | |
16786 | // If the block isn't obviously global, i.e. it captures anything at |
16787 | // all, then we need to do a few things in the surrounding context: |
16788 | if (Result->getBlockDecl()->hasCaptures()) { |
16789 | // First, this expression has a new cleanup object. |
16790 | ExprCleanupObjects.push_back(Elt: Result->getBlockDecl()); |
16791 | Cleanup.setExprNeedsCleanups(true); |
16792 | |
16793 | // It also gets a branch-protected scope if any of the captured |
16794 | // variables needs destruction. |
16795 | for (const auto &CI : Result->getBlockDecl()->captures()) { |
16796 | const VarDecl *var = CI.getVariable(); |
16797 | if (var->getType().isDestructedType() != QualType::DK_none) { |
16798 | setFunctionHasBranchProtectedScope(); |
16799 | break; |
16800 | } |
16801 | } |
16802 | } |
16803 | |
16804 | if (getCurFunction()) |
16805 | getCurFunction()->addBlock(BD); |
16806 | |
16807 | // This can happen if the block's return type is deduced, but |
16808 | // the return expression is invalid. |
16809 | if (BD->isInvalidDecl()) |
16810 | return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(), |
16811 | SubExprs: {Result}, T: Result->getType()); |
16812 | return Result; |
16813 | } |
16814 | |
16815 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
16816 | SourceLocation RPLoc) { |
16817 | TypeSourceInfo *TInfo; |
16818 | GetTypeFromParser(Ty, TInfo: &TInfo); |
16819 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); |
16820 | } |
16821 | |
16822 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, |
16823 | Expr *E, TypeSourceInfo *TInfo, |
16824 | SourceLocation RPLoc) { |
16825 | Expr *OrigExpr = E; |
16826 | bool IsMS = false; |
16827 | |
16828 | // CUDA device code does not support varargs. |
16829 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { |
16830 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(Val: CurContext)) { |
16831 | CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F); |
16832 | if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device || |
16833 | T == CUDAFunctionTarget::HostDevice) |
16834 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); |
16835 | } |
16836 | } |
16837 | |
16838 | // NVPTX does not support va_arg expression. |
16839 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && |
16840 | Context.getTargetInfo().getTriple().isNVPTX()) |
16841 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); |
16842 | |
16843 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() |
16844 | // as Microsoft ABI on an actual Microsoft platform, where |
16845 | // __builtin_ms_va_list and __builtin_va_list are the same.) |
16846 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && |
16847 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { |
16848 | QualType MSVaListType = Context.getBuiltinMSVaListType(); |
16849 | if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) { |
16850 | if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
16851 | return ExprError(); |
16852 | IsMS = true; |
16853 | } |
16854 | } |
16855 | |
16856 | // Get the va_list type |
16857 | QualType VaListType = Context.getBuiltinVaListType(); |
16858 | if (!IsMS) { |
16859 | if (VaListType->isArrayType()) { |
16860 | // Deal with implicit array decay; for example, on x86-64, |
16861 | // va_list is an array, but it's supposed to decay to |
16862 | // a pointer for va_arg. |
16863 | VaListType = Context.getArrayDecayedType(T: VaListType); |
16864 | // Make sure the input expression also decays appropriately. |
16865 | ExprResult Result = UsualUnaryConversions(E); |
16866 | if (Result.isInvalid()) |
16867 | return ExprError(); |
16868 | E = Result.get(); |
16869 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { |
16870 | // If va_list is a record type and we are compiling in C++ mode, |
16871 | // check the argument using reference binding. |
16872 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
16873 | Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false); |
16874 | ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E); |
16875 | if (Init.isInvalid()) |
16876 | return ExprError(); |
16877 | E = Init.getAs<Expr>(); |
16878 | } else { |
16879 | // Otherwise, the va_list argument must be an l-value because |
16880 | // it is modified by va_arg. |
16881 | if (!E->isTypeDependent() && |
16882 | CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *this)) |
16883 | return ExprError(); |
16884 | } |
16885 | } |
16886 | |
16887 | if (!IsMS && !E->isTypeDependent() && |
16888 | !Context.hasSameType(VaListType, E->getType())) |
16889 | return ExprError( |
16890 | Diag(E->getBeginLoc(), |
16891 | diag::err_first_argument_to_va_arg_not_of_type_va_list) |
16892 | << OrigExpr->getType() << E->getSourceRange()); |
16893 | |
16894 | if (!TInfo->getType()->isDependentType()) { |
16895 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), |
16896 | diag::err_second_parameter_to_va_arg_incomplete, |
16897 | TInfo->getTypeLoc())) |
16898 | return ExprError(); |
16899 | |
16900 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), |
16901 | TInfo->getType(), |
16902 | diag::err_second_parameter_to_va_arg_abstract, |
16903 | TInfo->getTypeLoc())) |
16904 | return ExprError(); |
16905 | |
16906 | if (!TInfo->getType().isPODType(Context)) { |
16907 | Diag(TInfo->getTypeLoc().getBeginLoc(), |
16908 | TInfo->getType()->isObjCLifetimeType() |
16909 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified |
16910 | : diag::warn_second_parameter_to_va_arg_not_pod) |
16911 | << TInfo->getType() |
16912 | << TInfo->getTypeLoc().getSourceRange(); |
16913 | } |
16914 | |
16915 | if (TInfo->getType()->isArrayType()) { |
16916 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, |
16917 | PDiag(diag::warn_second_parameter_to_va_arg_array) |
16918 | << TInfo->getType() |
16919 | << TInfo->getTypeLoc().getSourceRange()); |
16920 | } |
16921 | |
16922 | // Check for va_arg where arguments of the given type will be promoted |
16923 | // (i.e. this va_arg is guaranteed to have undefined behavior). |
16924 | QualType PromoteType; |
16925 | if (Context.isPromotableIntegerType(T: TInfo->getType())) { |
16926 | PromoteType = Context.getPromotedIntegerType(PromotableType: TInfo->getType()); |
16927 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, |
16928 | // and C23 7.16.1.1p2 says, in part: |
16929 | // If type is not compatible with the type of the actual next argument |
16930 | // (as promoted according to the default argument promotions), the |
16931 | // behavior is undefined, except for the following cases: |
16932 | // - both types are pointers to qualified or unqualified versions of |
16933 | // compatible types; |
16934 | // - one type is compatible with a signed integer type, the other |
16935 | // type is compatible with the corresponding unsigned integer type, |
16936 | // and the value is representable in both types; |
16937 | // - one type is pointer to qualified or unqualified void and the |
16938 | // other is a pointer to a qualified or unqualified character type; |
16939 | // - or, the type of the next argument is nullptr_t and type is a |
16940 | // pointer type that has the same representation and alignment |
16941 | // requirements as a pointer to a character type. |
16942 | // Given that type compatibility is the primary requirement (ignoring |
16943 | // qualifications), you would think we could call typesAreCompatible() |
16944 | // directly to test this. However, in C++, that checks for *same type*, |
16945 | // which causes false positives when passing an enumeration type to |
16946 | // va_arg. Instead, get the underlying type of the enumeration and pass |
16947 | // that. |
16948 | QualType UnderlyingType = TInfo->getType(); |
16949 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) |
16950 | UnderlyingType = ET->getDecl()->getIntegerType(); |
16951 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
16952 | /*CompareUnqualified*/ true)) |
16953 | PromoteType = QualType(); |
16954 | |
16955 | // If the types are still not compatible, we need to test whether the |
16956 | // promoted type and the underlying type are the same except for |
16957 | // signedness. Ask the AST for the correctly corresponding type and see |
16958 | // if that's compatible. |
16959 | if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && |
16960 | PromoteType->isUnsignedIntegerType() != |
16961 | UnderlyingType->isUnsignedIntegerType()) { |
16962 | UnderlyingType = |
16963 | UnderlyingType->isUnsignedIntegerType() |
16964 | ? Context.getCorrespondingSignedType(T: UnderlyingType) |
16965 | : Context.getCorrespondingUnsignedType(T: UnderlyingType); |
16966 | if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType, |
16967 | /*CompareUnqualified*/ true)) |
16968 | PromoteType = QualType(); |
16969 | } |
16970 | } |
16971 | if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float)) |
16972 | PromoteType = Context.DoubleTy; |
16973 | if (!PromoteType.isNull()) |
16974 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, |
16975 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) |
16976 | << TInfo->getType() |
16977 | << PromoteType |
16978 | << TInfo->getTypeLoc().getSourceRange()); |
16979 | } |
16980 | |
16981 | QualType T = TInfo->getType().getNonLValueExprType(Context); |
16982 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); |
16983 | } |
16984 | |
16985 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { |
16986 | // The type of __null will be int or long, depending on the size of |
16987 | // pointers on the target. |
16988 | QualType Ty; |
16989 | unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
16990 | if (pw == Context.getTargetInfo().getIntWidth()) |
16991 | Ty = Context.IntTy; |
16992 | else if (pw == Context.getTargetInfo().getLongWidth()) |
16993 | Ty = Context.LongTy; |
16994 | else if (pw == Context.getTargetInfo().getLongLongWidth()) |
16995 | Ty = Context.LongLongTy; |
16996 | else { |
16997 | llvm_unreachable("I don't know size of pointer!"); |
16998 | } |
16999 | |
17000 | return new (Context) GNUNullExpr(Ty, TokenLoc); |
17001 | } |
17002 | |
17003 | static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { |
17004 | CXXRecordDecl *ImplDecl = nullptr; |
17005 | |
17006 | // Fetch the std::source_location::__impl decl. |
17007 | if (NamespaceDecl *Std = S.getStdNamespace()) { |
17008 | LookupResult ResultSL(S, &S.PP.getIdentifierTable().get(Name: "source_location"), |
17009 | Loc, Sema::LookupOrdinaryName); |
17010 | if (S.LookupQualifiedName(ResultSL, Std)) { |
17011 | if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { |
17012 | LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"), |
17013 | Loc, Sema::LookupOrdinaryName); |
17014 | if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && |
17015 | S.LookupQualifiedName(ResultImpl, SLDecl)) { |
17016 | ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); |
17017 | } |
17018 | } |
17019 | } |
17020 | } |
17021 | |
17022 | if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { |
17023 | S.Diag(Loc, diag::err_std_source_location_impl_not_found); |
17024 | return nullptr; |
17025 | } |
17026 | |
17027 | // Verify that __impl is a trivial struct type, with no base classes, and with |
17028 | // only the four expected fields. |
17029 | if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || |
17030 | ImplDecl->getNumBases() != 0) { |
17031 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); |
17032 | return nullptr; |
17033 | } |
17034 | |
17035 | unsigned Count = 0; |
17036 | for (FieldDecl *F : ImplDecl->fields()) { |
17037 | StringRef Name = F->getName(); |
17038 | |
17039 | if (Name == "_M_file_name") { |
17040 | if (F->getType() != |
17041 | S.Context.getPointerType(S.Context.CharTy.withConst())) |
17042 | break; |
17043 | Count++; |
17044 | } else if (Name == "_M_function_name") { |
17045 | if (F->getType() != |
17046 | S.Context.getPointerType(S.Context.CharTy.withConst())) |
17047 | break; |
17048 | Count++; |
17049 | } else if (Name == "_M_line") { |
17050 | if (!F->getType()->isIntegerType()) |
17051 | break; |
17052 | Count++; |
17053 | } else if (Name == "_M_column") { |
17054 | if (!F->getType()->isIntegerType()) |
17055 | break; |
17056 | Count++; |
17057 | } else { |
17058 | Count = 100; // invalid |
17059 | break; |
17060 | } |
17061 | } |
17062 | if (Count != 4) { |
17063 | S.Diag(Loc, diag::err_std_source_location_impl_malformed); |
17064 | return nullptr; |
17065 | } |
17066 | |
17067 | return ImplDecl; |
17068 | } |
17069 | |
17070 | ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind, |
17071 | SourceLocation BuiltinLoc, |
17072 | SourceLocation RPLoc) { |
17073 | QualType ResultTy; |
17074 | switch (Kind) { |
17075 | case SourceLocIdentKind::File: |
17076 | case SourceLocIdentKind::FileName: |
17077 | case SourceLocIdentKind::Function: |
17078 | case SourceLocIdentKind::FuncSig: { |
17079 | QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0); |
17080 | ResultTy = |
17081 | Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); |
17082 | break; |
17083 | } |
17084 | case SourceLocIdentKind::Line: |
17085 | case SourceLocIdentKind::Column: |
17086 | ResultTy = Context.UnsignedIntTy; |
17087 | break; |
17088 | case SourceLocIdentKind::SourceLocStruct: |
17089 | if (!StdSourceLocationImplDecl) { |
17090 | StdSourceLocationImplDecl = |
17091 | LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc); |
17092 | if (!StdSourceLocationImplDecl) |
17093 | return ExprError(); |
17094 | } |
17095 | ResultTy = Context.getPointerType( |
17096 | T: Context.getRecordType(Decl: StdSourceLocationImplDecl).withConst()); |
17097 | break; |
17098 | } |
17099 | |
17100 | return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext); |
17101 | } |
17102 | |
17103 | ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, |
17104 | SourceLocation BuiltinLoc, |
17105 | SourceLocation RPLoc, |
17106 | DeclContext *ParentContext) { |
17107 | return new (Context) |
17108 | SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); |
17109 | } |
17110 | |
17111 | ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, |
17112 | StringLiteral *BinaryData, StringRef FileName) { |
17113 | EmbedDataStorage *Data = new (Context) EmbedDataStorage; |
17114 | Data->BinaryData = BinaryData; |
17115 | Data->FileName = FileName; |
17116 | return new (Context) |
17117 | EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0, |
17118 | Data->getDataElementCount()); |
17119 | } |
17120 | |
17121 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, |
17122 | const Expr *SrcExpr) { |
17123 | if (!DstType->isFunctionPointerType() || |
17124 | !SrcExpr->getType()->isFunctionType()) |
17125 | return false; |
17126 | |
17127 | auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts()); |
17128 | if (!DRE) |
17129 | return false; |
17130 | |
17131 | auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()); |
17132 | if (!FD) |
17133 | return false; |
17134 | |
17135 | return !S.checkAddressOfFunctionIsAvailable(Function: FD, |
17136 | /*Complain=*/true, |
17137 | Loc: SrcExpr->getBeginLoc()); |
17138 | } |
17139 | |
17140 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, |
17141 | SourceLocation Loc, |
17142 | QualType DstType, QualType SrcType, |
17143 | Expr *SrcExpr, AssignmentAction Action, |
17144 | bool *Complained) { |
17145 | if (Complained) |
17146 | *Complained = false; |
17147 | |
17148 | // Decode the result (notice that AST's are still created for extensions). |
17149 | bool CheckInferredResultType = false; |
17150 | bool isInvalid = false; |
17151 | unsigned DiagKind = 0; |
17152 | ConversionFixItGenerator ConvHints; |
17153 | bool MayHaveConvFixit = false; |
17154 | bool MayHaveFunctionDiff = false; |
17155 | const ObjCInterfaceDecl *IFace = nullptr; |
17156 | const ObjCProtocolDecl *PDecl = nullptr; |
17157 | |
17158 | switch (ConvTy) { |
17159 | case AssignConvertType::Compatible: |
17160 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); |
17161 | return false; |
17162 | case AssignConvertType::CompatibleVoidPtrToNonVoidPtr: |
17163 | // Still a valid conversion, but we may want to diagnose for C++ |
17164 | // compatibility reasons. |
17165 | DiagKind = diag::warn_compatible_implicit_pointer_conv; |
17166 | break; |
17167 | case AssignConvertType::PointerToInt: |
17168 | if (getLangOpts().CPlusPlus) { |
17169 | DiagKind = diag::err_typecheck_convert_pointer_int; |
17170 | isInvalid = true; |
17171 | } else { |
17172 | DiagKind = diag::ext_typecheck_convert_pointer_int; |
17173 | } |
17174 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17175 | MayHaveConvFixit = true; |
17176 | break; |
17177 | case AssignConvertType::IntToPointer: |
17178 | if (getLangOpts().CPlusPlus) { |
17179 | DiagKind = diag::err_typecheck_convert_int_pointer; |
17180 | isInvalid = true; |
17181 | } else { |
17182 | DiagKind = diag::ext_typecheck_convert_int_pointer; |
17183 | } |
17184 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17185 | MayHaveConvFixit = true; |
17186 | break; |
17187 | case AssignConvertType::IncompatibleFunctionPointerStrict: |
17188 | DiagKind = |
17189 | diag::warn_typecheck_convert_incompatible_function_pointer_strict; |
17190 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17191 | MayHaveConvFixit = true; |
17192 | break; |
17193 | case AssignConvertType::IncompatibleFunctionPointer: |
17194 | if (getLangOpts().CPlusPlus) { |
17195 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; |
17196 | isInvalid = true; |
17197 | } else { |
17198 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; |
17199 | } |
17200 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17201 | MayHaveConvFixit = true; |
17202 | break; |
17203 | case AssignConvertType::IncompatiblePointer: |
17204 | if (Action == AssignmentAction::Passing_CFAudited) { |
17205 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; |
17206 | } else if (getLangOpts().CPlusPlus) { |
17207 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; |
17208 | isInvalid = true; |
17209 | } else { |
17210 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; |
17211 | } |
17212 | CheckInferredResultType = DstType->isObjCObjectPointerType() && |
17213 | SrcType->isObjCObjectPointerType(); |
17214 | if (CheckInferredResultType) { |
17215 | SrcType = SrcType.getUnqualifiedType(); |
17216 | DstType = DstType.getUnqualifiedType(); |
17217 | } else { |
17218 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17219 | } |
17220 | MayHaveConvFixit = true; |
17221 | break; |
17222 | case AssignConvertType::IncompatiblePointerSign: |
17223 | if (getLangOpts().CPlusPlus) { |
17224 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; |
17225 | isInvalid = true; |
17226 | } else { |
17227 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; |
17228 | } |
17229 | break; |
17230 | case AssignConvertType::FunctionVoidPointer: |
17231 | if (getLangOpts().CPlusPlus) { |
17232 | DiagKind = diag::err_typecheck_convert_pointer_void_func; |
17233 | isInvalid = true; |
17234 | } else { |
17235 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; |
17236 | } |
17237 | break; |
17238 | case AssignConvertType::IncompatiblePointerDiscardsQualifiers: { |
17239 | // Perform array-to-pointer decay if necessary. |
17240 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: SrcType); |
17241 | |
17242 | isInvalid = true; |
17243 | |
17244 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); |
17245 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); |
17246 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { |
17247 | DiagKind = diag::err_typecheck_incompatible_address_space; |
17248 | break; |
17249 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { |
17250 | DiagKind = diag::err_typecheck_incompatible_ownership; |
17251 | break; |
17252 | } else if (!lhq.getPointerAuth().isEquivalent(Other: rhq.getPointerAuth())) { |
17253 | DiagKind = diag::err_typecheck_incompatible_ptrauth; |
17254 | break; |
17255 | } |
17256 | |
17257 | llvm_unreachable("unknown error case for discarding qualifiers!"); |
17258 | // fallthrough |
17259 | } |
17260 | case AssignConvertType::CompatiblePointerDiscardsQualifiers: |
17261 | // If the qualifiers lost were because we were applying the |
17262 | // (deprecated) C++ conversion from a string literal to a char* |
17263 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: |
17264 | // Ideally, this check would be performed in |
17265 | // checkPointerTypesForAssignment. However, that would require a |
17266 | // bit of refactoring (so that the second argument is an |
17267 | // expression, rather than a type), which should be done as part |
17268 | // of a larger effort to fix checkPointerTypesForAssignment for |
17269 | // C++ semantics. |
17270 | if (getLangOpts().CPlusPlus && |
17271 | IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType)) |
17272 | return false; |
17273 | if (getLangOpts().CPlusPlus) { |
17274 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; |
17275 | isInvalid = true; |
17276 | } else { |
17277 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; |
17278 | } |
17279 | |
17280 | break; |
17281 | case AssignConvertType::IncompatibleNestedPointerQualifiers: |
17282 | if (getLangOpts().CPlusPlus) { |
17283 | isInvalid = true; |
17284 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; |
17285 | } else { |
17286 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; |
17287 | } |
17288 | break; |
17289 | case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch: |
17290 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; |
17291 | isInvalid = true; |
17292 | break; |
17293 | case AssignConvertType::IntToBlockPointer: |
17294 | DiagKind = diag::err_int_to_block_pointer; |
17295 | isInvalid = true; |
17296 | break; |
17297 | case AssignConvertType::IncompatibleBlockPointer: |
17298 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; |
17299 | isInvalid = true; |
17300 | break; |
17301 | case AssignConvertType::IncompatibleObjCQualifiedId: { |
17302 | if (SrcType->isObjCQualifiedIdType()) { |
17303 | const ObjCObjectPointerType *srcOPT = |
17304 | SrcType->castAs<ObjCObjectPointerType>(); |
17305 | for (auto *srcProto : srcOPT->quals()) { |
17306 | PDecl = srcProto; |
17307 | break; |
17308 | } |
17309 | if (const ObjCInterfaceType *IFaceT = |
17310 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
17311 | IFace = IFaceT->getDecl(); |
17312 | } |
17313 | else if (DstType->isObjCQualifiedIdType()) { |
17314 | const ObjCObjectPointerType *dstOPT = |
17315 | DstType->castAs<ObjCObjectPointerType>(); |
17316 | for (auto *dstProto : dstOPT->quals()) { |
17317 | PDecl = dstProto; |
17318 | break; |
17319 | } |
17320 | if (const ObjCInterfaceType *IFaceT = |
17321 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) |
17322 | IFace = IFaceT->getDecl(); |
17323 | } |
17324 | if (getLangOpts().CPlusPlus) { |
17325 | DiagKind = diag::err_incompatible_qualified_id; |
17326 | isInvalid = true; |
17327 | } else { |
17328 | DiagKind = diag::warn_incompatible_qualified_id; |
17329 | } |
17330 | break; |
17331 | } |
17332 | case AssignConvertType::IncompatibleVectors: |
17333 | if (getLangOpts().CPlusPlus) { |
17334 | DiagKind = diag::err_incompatible_vectors; |
17335 | isInvalid = true; |
17336 | } else { |
17337 | DiagKind = diag::warn_incompatible_vectors; |
17338 | } |
17339 | break; |
17340 | case AssignConvertType::IncompatibleObjCWeakRef: |
17341 | DiagKind = diag::err_arc_weak_unavailable_assign; |
17342 | isInvalid = true; |
17343 | break; |
17344 | case AssignConvertType::Incompatible: |
17345 | if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) { |
17346 | if (Complained) |
17347 | *Complained = true; |
17348 | return true; |
17349 | } |
17350 | |
17351 | DiagKind = diag::err_typecheck_convert_incompatible; |
17352 | ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this); |
17353 | MayHaveConvFixit = true; |
17354 | isInvalid = true; |
17355 | MayHaveFunctionDiff = true; |
17356 | break; |
17357 | } |
17358 | |
17359 | QualType FirstType, SecondType; |
17360 | switch (Action) { |
17361 | case AssignmentAction::Assigning: |
17362 | case AssignmentAction::Initializing: |
17363 | // The destination type comes first. |
17364 | FirstType = DstType; |
17365 | SecondType = SrcType; |
17366 | break; |
17367 | |
17368 | case AssignmentAction::Returning: |
17369 | case AssignmentAction::Passing: |
17370 | case AssignmentAction::Passing_CFAudited: |
17371 | case AssignmentAction::Converting: |
17372 | case AssignmentAction::Sending: |
17373 | case AssignmentAction::Casting: |
17374 | // The source type comes first. |
17375 | FirstType = SrcType; |
17376 | SecondType = DstType; |
17377 | break; |
17378 | } |
17379 | |
17380 | PartialDiagnostic FDiag = PDiag(DiagKind); |
17381 | AssignmentAction ActionForDiag = Action; |
17382 | if (Action == AssignmentAction::Passing_CFAudited) |
17383 | ActionForDiag = AssignmentAction::Passing; |
17384 | |
17385 | FDiag << FirstType << SecondType << ActionForDiag |
17386 | << SrcExpr->getSourceRange(); |
17387 | |
17388 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || |
17389 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { |
17390 | auto isPlainChar = [](const clang::Type *Type) { |
17391 | return Type->isSpecificBuiltinType(K: BuiltinType::Char_S) || |
17392 | Type->isSpecificBuiltinType(K: BuiltinType::Char_U); |
17393 | }; |
17394 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || |
17395 | isPlainChar(SecondType->getPointeeOrArrayElementType())); |
17396 | } |
17397 | |
17398 | // If we can fix the conversion, suggest the FixIts. |
17399 | if (!ConvHints.isNull()) { |
17400 | for (FixItHint &H : ConvHints.Hints) |
17401 | FDiag << H; |
17402 | } |
17403 | |
17404 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } |
17405 | |
17406 | if (MayHaveFunctionDiff) |
17407 | HandleFunctionTypeMismatch(PDiag&: FDiag, FromType: SecondType, ToType: FirstType); |
17408 | |
17409 | Diag(Loc, FDiag); |
17410 | if ((DiagKind == diag::warn_incompatible_qualified_id || |
17411 | DiagKind == diag::err_incompatible_qualified_id) && |
17412 | PDecl && IFace && !IFace->hasDefinition()) |
17413 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) |
17414 | << IFace << PDecl; |
17415 | |
17416 | if (SecondType == Context.OverloadTy) |
17417 | NoteAllOverloadCandidates(OverloadExpr::find(E: SrcExpr).Expression, |
17418 | FirstType, /*TakingAddress=*/true); |
17419 | |
17420 | if (CheckInferredResultType) |
17421 | ObjC().EmitRelatedResultTypeNote(E: SrcExpr); |
17422 | |
17423 | if (Action == AssignmentAction::Returning && |
17424 | ConvTy == AssignConvertType::IncompatiblePointer) |
17425 | ObjC().EmitRelatedResultTypeNoteForReturn(destType: DstType); |
17426 | |
17427 | if (Complained) |
17428 | *Complained = true; |
17429 | return isInvalid; |
17430 | } |
17431 | |
17432 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
17433 | llvm::APSInt *Result, |
17434 | AllowFoldKind CanFold) { |
17435 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { |
17436 | public: |
17437 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, |
17438 | QualType T) override { |
17439 | return S.Diag(Loc, diag::err_ice_not_integral) |
17440 | << T << S.LangOpts.CPlusPlus; |
17441 | } |
17442 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
17443 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; |
17444 | } |
17445 | } Diagnoser; |
17446 | |
17447 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
17448 | } |
17449 | |
17450 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
17451 | llvm::APSInt *Result, |
17452 | unsigned DiagID, |
17453 | AllowFoldKind CanFold) { |
17454 | class IDDiagnoser : public VerifyICEDiagnoser { |
17455 | unsigned DiagID; |
17456 | |
17457 | public: |
17458 | IDDiagnoser(unsigned DiagID) |
17459 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } |
17460 | |
17461 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { |
17462 | return S.Diag(Loc, DiagID); |
17463 | } |
17464 | } Diagnoser(DiagID); |
17465 | |
17466 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); |
17467 | } |
17468 | |
17469 | Sema::SemaDiagnosticBuilder |
17470 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, |
17471 | QualType T) { |
17472 | return diagnoseNotICE(S, Loc); |
17473 | } |
17474 | |
17475 | Sema::SemaDiagnosticBuilder |
17476 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { |
17477 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; |
17478 | } |
17479 | |
17480 | ExprResult |
17481 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
17482 | VerifyICEDiagnoser &Diagnoser, |
17483 | AllowFoldKind CanFold) { |
17484 | SourceLocation DiagLoc = E->getBeginLoc(); |
17485 | |
17486 | if (getLangOpts().CPlusPlus11) { |
17487 | // C++11 [expr.const]p5: |
17488 | // If an expression of literal class type is used in a context where an |
17489 | // integral constant expression is required, then that class type shall |
17490 | // have a single non-explicit conversion function to an integral or |
17491 | // unscoped enumeration type |
17492 | ExprResult Converted; |
17493 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { |
17494 | VerifyICEDiagnoser &BaseDiagnoser; |
17495 | public: |
17496 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) |
17497 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, |
17498 | BaseDiagnoser.Suppress, true), |
17499 | BaseDiagnoser(BaseDiagnoser) {} |
17500 | |
17501 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
17502 | QualType T) override { |
17503 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); |
17504 | } |
17505 | |
17506 | SemaDiagnosticBuilder diagnoseIncomplete( |
17507 | Sema &S, SourceLocation Loc, QualType T) override { |
17508 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; |
17509 | } |
17510 | |
17511 | SemaDiagnosticBuilder diagnoseExplicitConv( |
17512 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
17513 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; |
17514 | } |
17515 | |
17516 | SemaDiagnosticBuilder noteExplicitConv( |
17517 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
17518 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) |
17519 | << ConvTy->isEnumeralType() << ConvTy; |
17520 | } |
17521 | |
17522 | SemaDiagnosticBuilder diagnoseAmbiguous( |
17523 | Sema &S, SourceLocation Loc, QualType T) override { |
17524 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; |
17525 | } |
17526 | |
17527 | SemaDiagnosticBuilder noteAmbiguous( |
17528 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
17529 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) |
17530 | << ConvTy->isEnumeralType() << ConvTy; |
17531 | } |
17532 | |
17533 | SemaDiagnosticBuilder diagnoseConversion( |
17534 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
17535 | llvm_unreachable("conversion functions are permitted"); |
17536 | } |
17537 | } ConvertDiagnoser(Diagnoser); |
17538 | |
17539 | Converted = PerformContextualImplicitConversion(Loc: DiagLoc, FromE: E, |
17540 | Converter&: ConvertDiagnoser); |
17541 | if (Converted.isInvalid()) |
17542 | return Converted; |
17543 | E = Converted.get(); |
17544 | // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we |
17545 | // don't try to evaluate it later. We also don't want to return the |
17546 | // RecoveryExpr here, as it results in this call succeeding, thus callers of |
17547 | // this function will attempt to use 'Value'. |
17548 | if (isa<RecoveryExpr>(Val: E)) |
17549 | return ExprError(); |
17550 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) |
17551 | return ExprError(); |
17552 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { |
17553 | // An ICE must be of integral or unscoped enumeration type. |
17554 | if (!Diagnoser.Suppress) |
17555 | Diagnoser.diagnoseNotICEType(S&: *this, Loc: DiagLoc, T: E->getType()) |
17556 | << E->getSourceRange(); |
17557 | return ExprError(); |
17558 | } |
17559 | |
17560 | ExprResult RValueExpr = DefaultLvalueConversion(E); |
17561 | if (RValueExpr.isInvalid()) |
17562 | return ExprError(); |
17563 | |
17564 | E = RValueExpr.get(); |
17565 | |
17566 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice |
17567 | // in the non-ICE case. |
17568 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) { |
17569 | SmallVector<PartialDiagnosticAt, 8> Notes; |
17570 | if (Result) |
17571 | *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context, Diag: &Notes); |
17572 | if (!isa<ConstantExpr>(Val: E)) |
17573 | E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result)) |
17574 | : ConstantExpr::Create(Context, E); |
17575 | |
17576 | if (Notes.empty()) |
17577 | return E; |
17578 | |
17579 | // If our only note is the usual "invalid subexpression" note, just point |
17580 | // the caret at its location rather than producing an essentially |
17581 | // redundant note. |
17582 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
17583 | diag::note_invalid_subexpr_in_const_expr) { |
17584 | DiagLoc = Notes[0].first; |
17585 | Notes.clear(); |
17586 | } |
17587 | |
17588 | if (getLangOpts().CPlusPlus) { |
17589 | if (!Diagnoser.Suppress) { |
17590 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17591 | for (const PartialDiagnosticAt &Note : Notes) |
17592 | Diag(Note.first, Note.second); |
17593 | } |
17594 | return ExprError(); |
17595 | } |
17596 | |
17597 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17598 | for (const PartialDiagnosticAt &Note : Notes) |
17599 | Diag(Note.first, Note.second); |
17600 | |
17601 | return E; |
17602 | } |
17603 | |
17604 | Expr::EvalResult EvalResult; |
17605 | SmallVector<PartialDiagnosticAt, 8> Notes; |
17606 | EvalResult.Diag = &Notes; |
17607 | |
17608 | // Try to evaluate the expression, and produce diagnostics explaining why it's |
17609 | // not a constant expression as a side-effect. |
17610 | bool Folded = |
17611 | E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) && |
17612 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects && |
17613 | (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior); |
17614 | |
17615 | if (!isa<ConstantExpr>(Val: E)) |
17616 | E = ConstantExpr::Create(Context, E, Result: EvalResult.Val); |
17617 | |
17618 | // In C++11, we can rely on diagnostics being produced for any expression |
17619 | // which is not a constant expression. If no diagnostics were produced, then |
17620 | // this is a constant expression. |
17621 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { |
17622 | if (Result) |
17623 | *Result = EvalResult.Val.getInt(); |
17624 | return E; |
17625 | } |
17626 | |
17627 | // If our only note is the usual "invalid subexpression" note, just point |
17628 | // the caret at its location rather than producing an essentially |
17629 | // redundant note. |
17630 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
17631 | diag::note_invalid_subexpr_in_const_expr) { |
17632 | DiagLoc = Notes[0].first; |
17633 | Notes.clear(); |
17634 | } |
17635 | |
17636 | if (!Folded || CanFold == AllowFoldKind::No) { |
17637 | if (!Diagnoser.Suppress) { |
17638 | Diagnoser.diagnoseNotICE(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17639 | for (const PartialDiagnosticAt &Note : Notes) |
17640 | Diag(Note.first, Note.second); |
17641 | } |
17642 | |
17643 | return ExprError(); |
17644 | } |
17645 | |
17646 | Diagnoser.diagnoseFold(S&: *this, Loc: DiagLoc) << E->getSourceRange(); |
17647 | for (const PartialDiagnosticAt &Note : Notes) |
17648 | Diag(Note.first, Note.second); |
17649 | |
17650 | if (Result) |
17651 | *Result = EvalResult.Val.getInt(); |
17652 | return E; |
17653 | } |
17654 | |
17655 | namespace { |
17656 | // Handle the case where we conclude a expression which we speculatively |
17657 | // considered to be unevaluated is actually evaluated. |
17658 | class TransformToPE : public TreeTransform<TransformToPE> { |
17659 | typedef TreeTransform<TransformToPE> BaseTransform; |
17660 | |
17661 | public: |
17662 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } |
17663 | |
17664 | // Make sure we redo semantic analysis |
17665 | bool AlwaysRebuild() { return true; } |
17666 | bool ReplacingOriginal() { return true; } |
17667 | |
17668 | // We need to special-case DeclRefExprs referring to FieldDecls which |
17669 | // are not part of a member pointer formation; normal TreeTransforming |
17670 | // doesn't catch this case because of the way we represent them in the AST. |
17671 | // FIXME: This is a bit ugly; is it really the best way to handle this |
17672 | // case? |
17673 | // |
17674 | // Error on DeclRefExprs referring to FieldDecls. |
17675 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
17676 | if (isa<FieldDecl>(E->getDecl()) && |
17677 | !SemaRef.isUnevaluatedContext()) |
17678 | return SemaRef.Diag(E->getLocation(), |
17679 | diag::err_invalid_non_static_member_use) |
17680 | << E->getDecl() << E->getSourceRange(); |
17681 | |
17682 | return BaseTransform::TransformDeclRefExpr(E); |
17683 | } |
17684 | |
17685 | // Exception: filter out member pointer formation |
17686 | ExprResult TransformUnaryOperator(UnaryOperator *E) { |
17687 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) |
17688 | return E; |
17689 | |
17690 | return BaseTransform::TransformUnaryOperator(E); |
17691 | } |
17692 | |
17693 | // The body of a lambda-expression is in a separate expression evaluation |
17694 | // context so never needs to be transformed. |
17695 | // FIXME: Ideally we wouldn't transform the closure type either, and would |
17696 | // just recreate the capture expressions and lambda expression. |
17697 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
17698 | return SkipLambdaBody(E, Body); |
17699 | } |
17700 | }; |
17701 | } |
17702 | |
17703 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { |
17704 | assert(isUnevaluatedContext() && |
17705 | "Should only transform unevaluated expressions"); |
17706 | ExprEvalContexts.back().Context = |
17707 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; |
17708 | if (isUnevaluatedContext()) |
17709 | return E; |
17710 | return TransformToPE(*this).TransformExpr(E); |
17711 | } |
17712 | |
17713 | TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { |
17714 | assert(isUnevaluatedContext() && |
17715 | "Should only transform unevaluated expressions"); |
17716 | ExprEvalContexts.back().Context = parentEvaluationContext().Context; |
17717 | if (isUnevaluatedContext()) |
17718 | return TInfo; |
17719 | return TransformToPE(*this).TransformType(TInfo); |
17720 | } |
17721 | |
17722 | void |
17723 | Sema::PushExpressionEvaluationContext( |
17724 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, |
17725 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
17726 | ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup, |
17727 | Args&: LambdaContextDecl, Args&: ExprContext); |
17728 | |
17729 | // Discarded statements and immediate contexts nested in other |
17730 | // discarded statements or immediate context are themselves |
17731 | // a discarded statement or an immediate context, respectively. |
17732 | ExprEvalContexts.back().InDiscardedStatement = |
17733 | parentEvaluationContext().isDiscardedStatementContext(); |
17734 | |
17735 | // C++23 [expr.const]/p15 |
17736 | // An expression or conversion is in an immediate function context if [...] |
17737 | // it is a subexpression of a manifestly constant-evaluated expression or |
17738 | // conversion. |
17739 | const auto &Prev = parentEvaluationContext(); |
17740 | ExprEvalContexts.back().InImmediateFunctionContext = |
17741 | Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated(); |
17742 | |
17743 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext = |
17744 | Prev.InImmediateEscalatingFunctionContext; |
17745 | |
17746 | Cleanup.reset(); |
17747 | if (!MaybeODRUseExprs.empty()) |
17748 | std::swap(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs); |
17749 | } |
17750 | |
17751 | void |
17752 | Sema::PushExpressionEvaluationContext( |
17753 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
17754 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
17755 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
17756 | PushExpressionEvaluationContext(NewContext, LambdaContextDecl: ClosureContextDecl, ExprContext); |
17757 | } |
17758 | |
17759 | void Sema::PushExpressionEvaluationContextForFunction( |
17760 | ExpressionEvaluationContext NewContext, FunctionDecl *FD) { |
17761 | // [expr.const]/p14.1 |
17762 | // An expression or conversion is in an immediate function context if it is |
17763 | // potentially evaluated and either: its innermost enclosing non-block scope |
17764 | // is a function parameter scope of an immediate function. |
17765 | PushExpressionEvaluationContext( |
17766 | NewContext: FD && FD->isConsteval() |
17767 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
17768 | : NewContext); |
17769 | const Sema::ExpressionEvaluationContextRecord &Parent = |
17770 | parentEvaluationContext(); |
17771 | Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext(); |
17772 | |
17773 | Current.InDiscardedStatement = false; |
17774 | |
17775 | if (FD) { |
17776 | |
17777 | // Each ExpressionEvaluationContextRecord also keeps track of whether the |
17778 | // context is nested in an immediate function context, so smaller contexts |
17779 | // that appear inside immediate functions (like variable initializers) are |
17780 | // considered to be inside an immediate function context even though by |
17781 | // themselves they are not immediate function contexts. But when a new |
17782 | // function is entered, we need to reset this tracking, since the entered |
17783 | // function might be not an immediate function. |
17784 | |
17785 | Current.InImmediateEscalatingFunctionContext = |
17786 | getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); |
17787 | |
17788 | if (isLambdaMethod(FD)) |
17789 | Current.InImmediateFunctionContext = |
17790 | FD->isConsteval() || |
17791 | (isLambdaMethod(FD) && (Parent.isConstantEvaluated() || |
17792 | Parent.isImmediateFunctionContext())); |
17793 | else |
17794 | Current.InImmediateFunctionContext = FD->isConsteval(); |
17795 | } |
17796 | } |
17797 | |
17798 | namespace { |
17799 | |
17800 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { |
17801 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); |
17802 | if (const auto *E = dyn_cast<UnaryOperator>(Val: PossibleDeref)) { |
17803 | if (E->getOpcode() == UO_Deref) |
17804 | return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr()); |
17805 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) { |
17806 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
17807 | } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) { |
17808 | return CheckPossibleDeref(S, PossibleDeref: E->getBase()); |
17809 | } else if (const auto E = dyn_cast<DeclRefExpr>(Val: PossibleDeref)) { |
17810 | QualType Inner; |
17811 | QualType Ty = E->getType(); |
17812 | if (const auto *Ptr = Ty->getAs<PointerType>()) |
17813 | Inner = Ptr->getPointeeType(); |
17814 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) |
17815 | Inner = Arr->getElementType(); |
17816 | else |
17817 | return nullptr; |
17818 | |
17819 | if (Inner->hasAttr(attr::NoDeref)) |
17820 | return E; |
17821 | } |
17822 | return nullptr; |
17823 | } |
17824 | |
17825 | } // namespace |
17826 | |
17827 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { |
17828 | for (const Expr *E : Rec.PossibleDerefs) { |
17829 | const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: E); |
17830 | if (DeclRef) { |
17831 | const ValueDecl *Decl = DeclRef->getDecl(); |
17832 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) |
17833 | << Decl->getName() << E->getSourceRange(); |
17834 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); |
17835 | } else { |
17836 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) |
17837 | << E->getSourceRange(); |
17838 | } |
17839 | } |
17840 | Rec.PossibleDerefs.clear(); |
17841 | } |
17842 | |
17843 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { |
17844 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) |
17845 | return; |
17846 | |
17847 | // Note: ignoring parens here is not justified by the standard rules, but |
17848 | // ignoring parentheses seems like a more reasonable approach, and this only |
17849 | // drives a deprecation warning so doesn't affect conformance. |
17850 | if (auto *BO = dyn_cast<BinaryOperator>(Val: E->IgnoreParenImpCasts())) { |
17851 | if (BO->getOpcode() == BO_Assign) { |
17852 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; |
17853 | llvm::erase(C&: LHSs, V: BO->getLHS()); |
17854 | } |
17855 | } |
17856 | } |
17857 | |
17858 | void Sema::MarkExpressionAsImmediateEscalating(Expr *E) { |
17859 | assert(getLangOpts().CPlusPlus20 && |
17860 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
17861 | "Cannot mark an immediate escalating expression outside of an " |
17862 | "immediate escalating context"); |
17863 | if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreImplicit()); |
17864 | Call && Call->getCallee()) { |
17865 | if (auto *DeclRef = |
17866 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
17867 | DeclRef->setIsImmediateEscalating(true); |
17868 | } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) { |
17869 | Ctr->setIsImmediateEscalating(true); |
17870 | } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) { |
17871 | DeclRef->setIsImmediateEscalating(true); |
17872 | } else { |
17873 | assert(false && "expected an immediately escalating expression"); |
17874 | } |
17875 | if (FunctionScopeInfo *FI = getCurFunction()) |
17876 | FI->FoundImmediateEscalatingExpression = true; |
17877 | } |
17878 | |
17879 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { |
17880 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || |
17881 | !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() || |
17882 | isCheckingDefaultArgumentOrInitializer() || |
17883 | RebuildingImmediateInvocation || isImmediateFunctionContext()) |
17884 | return E; |
17885 | |
17886 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. |
17887 | /// It's OK if this fails; we'll also remove this in |
17888 | /// HandleImmediateInvocations, but catching it here allows us to avoid |
17889 | /// walking the AST looking for it in simple cases. |
17890 | if (auto *Call = dyn_cast<CallExpr>(Val: E.get()->IgnoreImplicit())) |
17891 | if (auto *DeclRef = |
17892 | dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit())) |
17893 | ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: DeclRef); |
17894 | |
17895 | // C++23 [expr.const]/p16 |
17896 | // An expression or conversion is immediate-escalating if it is not initially |
17897 | // in an immediate function context and it is [...] an immediate invocation |
17898 | // that is not a constant expression and is not a subexpression of an |
17899 | // immediate invocation. |
17900 | APValue Cached; |
17901 | auto CheckConstantExpressionAndKeepResult = [&]() { |
17902 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
17903 | Expr::EvalResult Eval; |
17904 | Eval.Diag = &Notes; |
17905 | bool Res = E.get()->EvaluateAsConstantExpr( |
17906 | Result&: Eval, Ctx: getASTContext(), Kind: ConstantExprKind::ImmediateInvocation); |
17907 | if (Res && Notes.empty()) { |
17908 | Cached = std::move(Eval.Val); |
17909 | return true; |
17910 | } |
17911 | return false; |
17912 | }; |
17913 | |
17914 | if (!E.get()->isValueDependent() && |
17915 | ExprEvalContexts.back().InImmediateEscalatingFunctionContext && |
17916 | !CheckConstantExpressionAndKeepResult()) { |
17917 | MarkExpressionAsImmediateEscalating(E: E.get()); |
17918 | return E; |
17919 | } |
17920 | |
17921 | if (Cleanup.exprNeedsCleanups()) { |
17922 | // Since an immediate invocation is a full expression itself - it requires |
17923 | // an additional ExprWithCleanups node, but it can participate to a bigger |
17924 | // full expression which actually requires cleanups to be run after so |
17925 | // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it |
17926 | // may discard cleanups for outer expression too early. |
17927 | |
17928 | // Note that ExprWithCleanups created here must always have empty cleanup |
17929 | // objects: |
17930 | // - compound literals do not create cleanup objects in C++ and immediate |
17931 | // invocations are C++-only. |
17932 | // - blocks are not allowed inside constant expressions and compiler will |
17933 | // issue an error if they appear there. |
17934 | // |
17935 | // Hence, in correct code any cleanup objects created inside current |
17936 | // evaluation context must be outside the immediate invocation. |
17937 | E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(), |
17938 | CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {}); |
17939 | } |
17940 | |
17941 | ConstantExpr *Res = ConstantExpr::Create( |
17942 | Context: getASTContext(), E: E.get(), |
17943 | Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(), |
17944 | Context: getASTContext()), |
17945 | /*IsImmediateInvocation*/ true); |
17946 | if (Cached.hasValue()) |
17947 | Res->MoveIntoResult(Value&: Cached, Context: getASTContext()); |
17948 | /// Value-dependent constant expressions should not be immediately |
17949 | /// evaluated until they are instantiated. |
17950 | if (!Res->isValueDependent()) |
17951 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Args&: Res, Args: 0); |
17952 | return Res; |
17953 | } |
17954 | |
17955 | static void EvaluateAndDiagnoseImmediateInvocation( |
17956 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { |
17957 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; |
17958 | Expr::EvalResult Eval; |
17959 | Eval.Diag = &Notes; |
17960 | ConstantExpr *CE = Candidate.getPointer(); |
17961 | bool Result = CE->EvaluateAsConstantExpr( |
17962 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); |
17963 | if (!Result || !Notes.empty()) { |
17964 | SemaRef.FailedImmediateInvocations.insert(Ptr: CE); |
17965 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); |
17966 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) |
17967 | InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit(); |
17968 | FunctionDecl *FD = nullptr; |
17969 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) |
17970 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); |
17971 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) |
17972 | FD = Call->getConstructor(); |
17973 | else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr)) |
17974 | FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction()); |
17975 | |
17976 | assert(FD && FD->isImmediateFunction() && |
17977 | "could not find an immediate function in this expression"); |
17978 | if (FD->isInvalidDecl()) |
17979 | return; |
17980 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) |
17981 | << FD << FD->isConsteval(); |
17982 | if (auto Context = |
17983 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
17984 | SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) |
17985 | << Context->Decl; |
17986 | SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); |
17987 | } |
17988 | if (!FD->isConsteval()) |
17989 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
17990 | for (auto &Note : Notes) |
17991 | SemaRef.Diag(Note.first, Note.second); |
17992 | return; |
17993 | } |
17994 | CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext()); |
17995 | } |
17996 | |
17997 | static void RemoveNestedImmediateInvocation( |
17998 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, |
17999 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { |
18000 | struct ComplexRemove : TreeTransform<ComplexRemove> { |
18001 | using Base = TreeTransform<ComplexRemove>; |
18002 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
18003 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; |
18004 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator |
18005 | CurrentII; |
18006 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, |
18007 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, |
18008 | SmallVector<Sema::ImmediateInvocationCandidate, |
18009 | 4>::reverse_iterator Current) |
18010 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} |
18011 | void RemoveImmediateInvocation(ConstantExpr* E) { |
18012 | auto It = std::find_if(first: CurrentII, last: IISet.rend(), |
18013 | pred: [E](Sema::ImmediateInvocationCandidate Elem) { |
18014 | return Elem.getPointer() == E; |
18015 | }); |
18016 | // It is possible that some subexpression of the current immediate |
18017 | // invocation was handled from another expression evaluation context. Do |
18018 | // not handle the current immediate invocation if some of its |
18019 | // subexpressions failed before. |
18020 | if (It == IISet.rend()) { |
18021 | if (SemaRef.FailedImmediateInvocations.contains(Ptr: E)) |
18022 | CurrentII->setInt(1); |
18023 | } else { |
18024 | It->setInt(1); // Mark as deleted |
18025 | } |
18026 | } |
18027 | ExprResult TransformConstantExpr(ConstantExpr *E) { |
18028 | if (!E->isImmediateInvocation()) |
18029 | return Base::TransformConstantExpr(E); |
18030 | RemoveImmediateInvocation(E); |
18031 | return Base::TransformExpr(E->getSubExpr()); |
18032 | } |
18033 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so |
18034 | /// we need to remove its DeclRefExpr from the DRSet. |
18035 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
18036 | DRSet.erase(Ptr: cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); |
18037 | return Base::TransformCXXOperatorCallExpr(E); |
18038 | } |
18039 | /// Base::TransformUserDefinedLiteral doesn't preserve the |
18040 | /// UserDefinedLiteral node. |
18041 | ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; } |
18042 | /// Base::TransformInitializer skips ConstantExpr so we need to visit them |
18043 | /// here. |
18044 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { |
18045 | if (!Init) |
18046 | return Init; |
18047 | |
18048 | // We cannot use IgnoreImpCasts because we need to preserve |
18049 | // full expressions. |
18050 | while (true) { |
18051 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init)) |
18052 | Init = ICE->getSubExpr(); |
18053 | else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) |
18054 | Init = ICE->getSubExpr(); |
18055 | else |
18056 | break; |
18057 | } |
18058 | /// ConstantExprs are the first layer of implicit node to be removed so if |
18059 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. |
18060 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Init); |
18061 | CE && CE->isImmediateInvocation()) |
18062 | RemoveImmediateInvocation(E: CE); |
18063 | return Base::TransformInitializer(Init, NotCopyInit); |
18064 | } |
18065 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
18066 | DRSet.erase(Ptr: E); |
18067 | return E; |
18068 | } |
18069 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
18070 | // Do not rebuild lambdas to avoid creating a new type. |
18071 | // Lambdas have already been processed inside their eval contexts. |
18072 | return E; |
18073 | } |
18074 | bool AlwaysRebuild() { return false; } |
18075 | bool ReplacingOriginal() { return true; } |
18076 | bool AllowSkippingCXXConstructExpr() { |
18077 | bool Res = AllowSkippingFirstCXXConstructExpr; |
18078 | AllowSkippingFirstCXXConstructExpr = true; |
18079 | return Res; |
18080 | } |
18081 | bool AllowSkippingFirstCXXConstructExpr = true; |
18082 | } Transformer(SemaRef, Rec.ReferenceToConsteval, |
18083 | Rec.ImmediateInvocationCandidates, It); |
18084 | |
18085 | /// CXXConstructExpr with a single argument are getting skipped by |
18086 | /// TreeTransform in some situtation because they could be implicit. This |
18087 | /// can only occur for the top-level CXXConstructExpr because it is used |
18088 | /// nowhere in the expression being transformed therefore will not be rebuilt. |
18089 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from |
18090 | /// skipping the first CXXConstructExpr. |
18091 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) |
18092 | Transformer.AllowSkippingFirstCXXConstructExpr = false; |
18093 | |
18094 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); |
18095 | // The result may not be usable in case of previous compilation errors. |
18096 | // In this case evaluation of the expression may result in crash so just |
18097 | // don't do anything further with the result. |
18098 | if (Res.isUsable()) { |
18099 | Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res); |
18100 | It->getPointer()->setSubExpr(Res.get()); |
18101 | } |
18102 | } |
18103 | |
18104 | static void |
18105 | HandleImmediateInvocations(Sema &SemaRef, |
18106 | Sema::ExpressionEvaluationContextRecord &Rec) { |
18107 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && |
18108 | Rec.ReferenceToConsteval.size() == 0) || |
18109 | Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation) |
18110 | return; |
18111 | |
18112 | /// When we have more than 1 ImmediateInvocationCandidates or previously |
18113 | /// failed immediate invocations, we need to check for nested |
18114 | /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics. |
18115 | /// Otherwise we only need to remove ReferenceToConsteval in the immediate |
18116 | /// invocation. |
18117 | if (Rec.ImmediateInvocationCandidates.size() > 1 || |
18118 | !SemaRef.FailedImmediateInvocations.empty()) { |
18119 | |
18120 | /// Prevent sema calls during the tree transform from adding pointers that |
18121 | /// are already in the sets. |
18122 | llvm::SaveAndRestore DisableIITracking( |
18123 | SemaRef.RebuildingImmediateInvocation, true); |
18124 | |
18125 | /// Prevent diagnostic during tree transfrom as they are duplicates |
18126 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); |
18127 | |
18128 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); |
18129 | It != Rec.ImmediateInvocationCandidates.rend(); It++) |
18130 | if (!It->getInt()) |
18131 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); |
18132 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && |
18133 | Rec.ReferenceToConsteval.size()) { |
18134 | struct SimpleRemove : DynamicRecursiveASTVisitor { |
18135 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; |
18136 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} |
18137 | bool VisitDeclRefExpr(DeclRefExpr *E) override { |
18138 | DRSet.erase(Ptr: E); |
18139 | return DRSet.size(); |
18140 | } |
18141 | } Visitor(Rec.ReferenceToConsteval); |
18142 | Visitor.TraverseStmt( |
18143 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); |
18144 | } |
18145 | for (auto CE : Rec.ImmediateInvocationCandidates) |
18146 | if (!CE.getInt()) |
18147 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE); |
18148 | for (auto *DR : Rec.ReferenceToConsteval) { |
18149 | // If the expression is immediate escalating, it is not an error; |
18150 | // The outer context itself becomes immediate and further errors, |
18151 | // if any, will be handled by DiagnoseImmediateEscalatingReason. |
18152 | if (DR->isImmediateEscalating()) |
18153 | continue; |
18154 | auto *FD = cast<FunctionDecl>(Val: DR->getDecl()); |
18155 | const NamedDecl *ND = FD; |
18156 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: ND); |
18157 | MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD))) |
18158 | ND = MD->getParent(); |
18159 | |
18160 | // C++23 [expr.const]/p16 |
18161 | // An expression or conversion is immediate-escalating if it is not |
18162 | // initially in an immediate function context and it is [...] a |
18163 | // potentially-evaluated id-expression that denotes an immediate function |
18164 | // that is not a subexpression of an immediate invocation. |
18165 | bool ImmediateEscalating = false; |
18166 | bool IsPotentiallyEvaluated = |
18167 | Rec.Context == |
18168 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated || |
18169 | Rec.Context == |
18170 | Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed; |
18171 | if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated) |
18172 | ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext; |
18173 | |
18174 | if (!Rec.InImmediateEscalatingFunctionContext || |
18175 | (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) { |
18176 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) |
18177 | << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval(); |
18178 | if (!FD->getBuiltinID()) |
18179 | SemaRef.Diag(ND->getLocation(), diag::note_declared_at); |
18180 | if (auto Context = |
18181 | SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { |
18182 | SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) |
18183 | << Context->Decl; |
18184 | SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); |
18185 | } |
18186 | if (FD->isImmediateEscalating() && !FD->isConsteval()) |
18187 | SemaRef.DiagnoseImmediateEscalatingReason(FD); |
18188 | |
18189 | } else { |
18190 | SemaRef.MarkExpressionAsImmediateEscalating(DR); |
18191 | } |
18192 | } |
18193 | } |
18194 | |
18195 | void Sema::PopExpressionEvaluationContext() { |
18196 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); |
18197 | unsigned NumTypos = Rec.NumTypos; |
18198 | |
18199 | if (!Rec.Lambdas.empty()) { |
18200 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; |
18201 | if (!getLangOpts().CPlusPlus20 && |
18202 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || |
18203 | Rec.isUnevaluated() || |
18204 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { |
18205 | unsigned D; |
18206 | if (Rec.isUnevaluated()) { |
18207 | // C++11 [expr.prim.lambda]p2: |
18208 | // A lambda-expression shall not appear in an unevaluated operand |
18209 | // (Clause 5). |
18210 | D = diag::err_lambda_unevaluated_operand; |
18211 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { |
18212 | // C++1y [expr.const]p2: |
18213 | // A conditional-expression e is a core constant expression unless the |
18214 | // evaluation of e, following the rules of the abstract machine, would |
18215 | // evaluate [...] a lambda-expression. |
18216 | D = diag::err_lambda_in_constant_expression; |
18217 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { |
18218 | // C++17 [expr.prim.lamda]p2: |
18219 | // A lambda-expression shall not appear [...] in a template-argument. |
18220 | D = diag::err_lambda_in_invalid_context; |
18221 | } else |
18222 | llvm_unreachable("Couldn't infer lambda error message."); |
18223 | |
18224 | for (const auto *L : Rec.Lambdas) |
18225 | Diag(L->getBeginLoc(), D); |
18226 | } |
18227 | } |
18228 | |
18229 | // Append the collected materialized temporaries into previous context before |
18230 | // exit if the previous also is a lifetime extending context. |
18231 | if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext && |
18232 | parentEvaluationContext().InLifetimeExtendingContext && |
18233 | !Rec.ForRangeLifetimeExtendTemps.empty()) { |
18234 | parentEvaluationContext().ForRangeLifetimeExtendTemps.append( |
18235 | RHS: Rec.ForRangeLifetimeExtendTemps); |
18236 | } |
18237 | |
18238 | WarnOnPendingNoDerefs(Rec); |
18239 | HandleImmediateInvocations(SemaRef&: *this, Rec); |
18240 | |
18241 | // Warn on any volatile-qualified simple-assignments that are not discarded- |
18242 | // value expressions nor unevaluated operands (those cases get removed from |
18243 | // this list by CheckUnusedVolatileAssignment). |
18244 | for (auto *BO : Rec.VolatileAssignmentLHSs) |
18245 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) |
18246 | << BO->getType(); |
18247 | |
18248 | // When are coming out of an unevaluated context, clear out any |
18249 | // temporaries that we may have created as part of the evaluation of |
18250 | // the expression in that context: they aren't relevant because they |
18251 | // will never be constructed. |
18252 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { |
18253 | ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects, |
18254 | CE: ExprCleanupObjects.end()); |
18255 | Cleanup = Rec.ParentCleanup; |
18256 | CleanupVarDeclMarking(); |
18257 | std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs); |
18258 | // Otherwise, merge the contexts together. |
18259 | } else { |
18260 | Cleanup.mergeFrom(Rhs: Rec.ParentCleanup); |
18261 | MaybeODRUseExprs.insert_range(R&: Rec.SavedMaybeODRUseExprs); |
18262 | } |
18263 | |
18264 | // Pop the current expression evaluation context off the stack. |
18265 | ExprEvalContexts.pop_back(); |
18266 | |
18267 | // The global expression evaluation context record is never popped. |
18268 | ExprEvalContexts.back().NumTypos += NumTypos; |
18269 | } |
18270 | |
18271 | void Sema::DiscardCleanupsInEvaluationContext() { |
18272 | ExprCleanupObjects.erase( |
18273 | CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, |
18274 | CE: ExprCleanupObjects.end()); |
18275 | Cleanup.reset(); |
18276 | MaybeODRUseExprs.clear(); |
18277 | } |
18278 | |
18279 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { |
18280 | ExprResult Result = CheckPlaceholderExpr(E); |
18281 | if (Result.isInvalid()) |
18282 | return ExprError(); |
18283 | E = Result.get(); |
18284 | if (!E->getType()->isVariablyModifiedType()) |
18285 | return E; |
18286 | return TransformToPotentiallyEvaluated(E); |
18287 | } |
18288 | |
18289 | /// Are we in a context that is potentially constant evaluated per C++20 |
18290 | /// [expr.const]p12? |
18291 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { |
18292 | /// C++2a [expr.const]p12: |
18293 | // An expression or conversion is potentially constant evaluated if it is |
18294 | switch (SemaRef.ExprEvalContexts.back().Context) { |
18295 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
18296 | case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: |
18297 | |
18298 | // -- a manifestly constant-evaluated expression, |
18299 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
18300 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
18301 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
18302 | // -- a potentially-evaluated expression, |
18303 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
18304 | // -- an immediate subexpression of a braced-init-list, |
18305 | |
18306 | // -- [FIXME] an expression of the form & cast-expression that occurs |
18307 | // within a templated entity |
18308 | // -- a subexpression of one of the above that is not a subexpression of |
18309 | // a nested unevaluated operand. |
18310 | return true; |
18311 | |
18312 | case Sema::ExpressionEvaluationContext::Unevaluated: |
18313 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
18314 | // Expressions in this context are never evaluated. |
18315 | return false; |
18316 | } |
18317 | llvm_unreachable("Invalid context"); |
18318 | } |
18319 | |
18320 | /// Return true if this function has a calling convention that requires mangling |
18321 | /// in the size of the parameter pack. |
18322 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { |
18323 | // These manglings are only applicable for targets whcih use Microsoft |
18324 | // mangling scheme for C. |
18325 | if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling()) |
18326 | return false; |
18327 | |
18328 | // If this is C++ and this isn't an extern "C" function, parameters do not |
18329 | // need to be complete. In this case, C++ mangling will apply, which doesn't |
18330 | // use the size of the parameters. |
18331 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) |
18332 | return false; |
18333 | |
18334 | // Stdcall, fastcall, and vectorcall need this special treatment. |
18335 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
18336 | switch (CC) { |
18337 | case CC_X86StdCall: |
18338 | case CC_X86FastCall: |
18339 | case CC_X86VectorCall: |
18340 | return true; |
18341 | default: |
18342 | break; |
18343 | } |
18344 | return false; |
18345 | } |
18346 | |
18347 | /// Require that all of the parameter types of function be complete. Normally, |
18348 | /// parameter types are only required to be complete when a function is called |
18349 | /// or defined, but to mangle functions with certain calling conventions, the |
18350 | /// mangler needs to know the size of the parameter list. In this situation, |
18351 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles |
18352 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually |
18353 | /// result in a linker error. Clang doesn't implement this behavior, and instead |
18354 | /// attempts to error at compile time. |
18355 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, |
18356 | SourceLocation Loc) { |
18357 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { |
18358 | FunctionDecl *FD; |
18359 | ParmVarDecl *Param; |
18360 | |
18361 | public: |
18362 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) |
18363 | : FD(FD), Param(Param) {} |
18364 | |
18365 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
18366 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
18367 | StringRef CCName; |
18368 | switch (CC) { |
18369 | case CC_X86StdCall: |
18370 | CCName = "stdcall"; |
18371 | break; |
18372 | case CC_X86FastCall: |
18373 | CCName = "fastcall"; |
18374 | break; |
18375 | case CC_X86VectorCall: |
18376 | CCName = "vectorcall"; |
18377 | break; |
18378 | default: |
18379 | llvm_unreachable("CC does not need mangling"); |
18380 | } |
18381 | |
18382 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) |
18383 | << Param->getDeclName() << FD->getDeclName() << CCName; |
18384 | } |
18385 | }; |
18386 | |
18387 | for (ParmVarDecl *Param : FD->parameters()) { |
18388 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); |
18389 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); |
18390 | } |
18391 | } |
18392 | |
18393 | namespace { |
18394 | enum class OdrUseContext { |
18395 | /// Declarations in this context are not odr-used. |
18396 | None, |
18397 | /// Declarations in this context are formally odr-used, but this is a |
18398 | /// dependent context. |
18399 | Dependent, |
18400 | /// Declarations in this context are odr-used but not actually used (yet). |
18401 | FormallyOdrUsed, |
18402 | /// Declarations in this context are used. |
18403 | Used |
18404 | }; |
18405 | } |
18406 | |
18407 | /// Are we within a context in which references to resolved functions or to |
18408 | /// variables result in odr-use? |
18409 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { |
18410 | const Sema::ExpressionEvaluationContextRecord &Context = |
18411 | SemaRef.currentEvaluationContext(); |
18412 | |
18413 | if (Context.isUnevaluated()) |
18414 | return OdrUseContext::None; |
18415 | |
18416 | if (SemaRef.CurContext->isDependentContext()) |
18417 | return OdrUseContext::Dependent; |
18418 | |
18419 | if (Context.isDiscardedStatementContext()) |
18420 | return OdrUseContext::FormallyOdrUsed; |
18421 | |
18422 | else if (Context.Context == |
18423 | Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) |
18424 | return OdrUseContext::FormallyOdrUsed; |
18425 | |
18426 | return OdrUseContext::Used; |
18427 | } |
18428 | |
18429 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { |
18430 | if (!Func->isConstexpr()) |
18431 | return false; |
18432 | |
18433 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) |
18434 | return true; |
18435 | auto *CCD = dyn_cast<CXXConstructorDecl>(Val: Func); |
18436 | return CCD && CCD->getInheritedConstructor(); |
18437 | } |
18438 | |
18439 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
18440 | bool MightBeOdrUse) { |
18441 | assert(Func && "No function?"); |
18442 | |
18443 | Func->setReferenced(); |
18444 | |
18445 | // Recursive functions aren't really used until they're used from some other |
18446 | // context. |
18447 | bool IsRecursiveCall = CurContext == Func; |
18448 | |
18449 | // C++11 [basic.def.odr]p3: |
18450 | // A function whose name appears as a potentially-evaluated expression is |
18451 | // odr-used if it is the unique lookup result or the selected member of a |
18452 | // set of overloaded functions [...]. |
18453 | // |
18454 | // We (incorrectly) mark overload resolution as an unevaluated context, so we |
18455 | // can just check that here. |
18456 | OdrUseContext OdrUse = |
18457 | MightBeOdrUse ? isOdrUseContext(SemaRef&: *this) : OdrUseContext::None; |
18458 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) |
18459 | OdrUse = OdrUseContext::FormallyOdrUsed; |
18460 | |
18461 | // Trivial default constructors and destructors are never actually used. |
18462 | // FIXME: What about other special members? |
18463 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && |
18464 | OdrUse == OdrUseContext::Used) { |
18465 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) |
18466 | if (Constructor->isDefaultConstructor()) |
18467 | OdrUse = OdrUseContext::FormallyOdrUsed; |
18468 | if (isa<CXXDestructorDecl>(Val: Func)) |
18469 | OdrUse = OdrUseContext::FormallyOdrUsed; |
18470 | } |
18471 | |
18472 | // C++20 [expr.const]p12: |
18473 | // A function [...] is needed for constant evaluation if it is [...] a |
18474 | // constexpr function that is named by an expression that is potentially |
18475 | // constant evaluated |
18476 | bool NeededForConstantEvaluation = |
18477 | isPotentiallyConstantEvaluatedContext(SemaRef&: *this) && |
18478 | isImplicitlyDefinableConstexprFunction(Func); |
18479 | |
18480 | // Determine whether we require a function definition to exist, per |
18481 | // C++11 [temp.inst]p3: |
18482 | // Unless a function template specialization has been explicitly |
18483 | // instantiated or explicitly specialized, the function template |
18484 | // specialization is implicitly instantiated when the specialization is |
18485 | // referenced in a context that requires a function definition to exist. |
18486 | // C++20 [temp.inst]p7: |
18487 | // The existence of a definition of a [...] function is considered to |
18488 | // affect the semantics of the program if the [...] function is needed for |
18489 | // constant evaluation by an expression |
18490 | // C++20 [basic.def.odr]p10: |
18491 | // Every program shall contain exactly one definition of every non-inline |
18492 | // function or variable that is odr-used in that program outside of a |
18493 | // discarded statement |
18494 | // C++20 [special]p1: |
18495 | // The implementation will implicitly define [defaulted special members] |
18496 | // if they are odr-used or needed for constant evaluation. |
18497 | // |
18498 | // Note that we skip the implicit instantiation of templates that are only |
18499 | // used in unused default arguments or by recursive calls to themselves. |
18500 | // This is formally non-conforming, but seems reasonable in practice. |
18501 | bool NeedDefinition = |
18502 | !IsRecursiveCall && |
18503 | (OdrUse == OdrUseContext::Used || |
18504 | (NeededForConstantEvaluation && !Func->isPureVirtual())); |
18505 | |
18506 | // C++14 [temp.expl.spec]p6: |
18507 | // If a template [...] is explicitly specialized then that specialization |
18508 | // shall be declared before the first use of that specialization that would |
18509 | // cause an implicit instantiation to take place, in every translation unit |
18510 | // in which such a use occurs |
18511 | if (NeedDefinition && |
18512 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || |
18513 | Func->getMemberSpecializationInfo())) |
18514 | checkSpecializationReachability(Loc, Func); |
18515 | |
18516 | if (getLangOpts().CUDA) |
18517 | CUDA().CheckCall(Loc, Callee: Func); |
18518 | |
18519 | // If we need a definition, try to create one. |
18520 | if (NeedDefinition && !Func->getBody()) { |
18521 | runWithSufficientStackSpace(Loc, Fn: [&] { |
18522 | if (CXXConstructorDecl *Constructor = |
18523 | dyn_cast<CXXConstructorDecl>(Val: Func)) { |
18524 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); |
18525 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { |
18526 | if (Constructor->isDefaultConstructor()) { |
18527 | if (Constructor->isTrivial() && |
18528 | !Constructor->hasAttr<DLLExportAttr>()) |
18529 | return; |
18530 | DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
18531 | } else if (Constructor->isCopyConstructor()) { |
18532 | DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor); |
18533 | } else if (Constructor->isMoveConstructor()) { |
18534 | DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor); |
18535 | } |
18536 | } else if (Constructor->getInheritedConstructor()) { |
18537 | DefineInheritingConstructor(UseLoc: Loc, Constructor); |
18538 | } |
18539 | } else if (CXXDestructorDecl *Destructor = |
18540 | dyn_cast<CXXDestructorDecl>(Val: Func)) { |
18541 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); |
18542 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { |
18543 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) |
18544 | return; |
18545 | DefineImplicitDestructor(CurrentLocation: Loc, Destructor); |
18546 | } |
18547 | if (Destructor->isVirtual() && getLangOpts().AppleKext) |
18548 | MarkVTableUsed(Loc, Class: Destructor->getParent()); |
18549 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: Func)) { |
18550 | if (MethodDecl->isOverloadedOperator() && |
18551 | MethodDecl->getOverloadedOperator() == OO_Equal) { |
18552 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); |
18553 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { |
18554 | if (MethodDecl->isCopyAssignmentOperator()) |
18555 | DefineImplicitCopyAssignment(CurrentLocation: Loc, MethodDecl); |
18556 | else if (MethodDecl->isMoveAssignmentOperator()) |
18557 | DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl); |
18558 | } |
18559 | } else if (isa<CXXConversionDecl>(Val: MethodDecl) && |
18560 | MethodDecl->getParent()->isLambda()) { |
18561 | CXXConversionDecl *Conversion = |
18562 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); |
18563 | if (Conversion->isLambdaToBlockPointerConversion()) |
18564 | DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
18565 | else |
18566 | DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion); |
18567 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) |
18568 | MarkVTableUsed(Loc, Class: MethodDecl->getParent()); |
18569 | } |
18570 | |
18571 | if (Func->isDefaulted() && !Func->isDeleted()) { |
18572 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func); |
18573 | if (DCK != DefaultedComparisonKind::None) |
18574 | DefineDefaultedComparison(Loc, FD: Func, DCK); |
18575 | } |
18576 | |
18577 | // Implicit instantiation of function templates and member functions of |
18578 | // class templates. |
18579 | if (Func->isImplicitlyInstantiable()) { |
18580 | TemplateSpecializationKind TSK = |
18581 | Func->getTemplateSpecializationKindForInstantiation(); |
18582 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); |
18583 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
18584 | if (FirstInstantiation) { |
18585 | PointOfInstantiation = Loc; |
18586 | if (auto *MSI = Func->getMemberSpecializationInfo()) |
18587 | MSI->setPointOfInstantiation(Loc); |
18588 | // FIXME: Notify listener. |
18589 | else |
18590 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
18591 | } else if (TSK != TSK_ImplicitInstantiation) { |
18592 | // Use the point of use as the point of instantiation, instead of the |
18593 | // point of explicit instantiation (which we track as the actual point |
18594 | // of instantiation). This gives better backtraces in diagnostics. |
18595 | PointOfInstantiation = Loc; |
18596 | } |
18597 | |
18598 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || |
18599 | Func->isConstexpr()) { |
18600 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && |
18601 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && |
18602 | CodeSynthesisContexts.size()) |
18603 | PendingLocalImplicitInstantiations.push_back( |
18604 | std::make_pair(x&: Func, y&: PointOfInstantiation)); |
18605 | else if (Func->isConstexpr()) |
18606 | // Do not defer instantiations of constexpr functions, to avoid the |
18607 | // expression evaluator needing to call back into Sema if it sees a |
18608 | // call to such a function. |
18609 | InstantiateFunctionDefinition(PointOfInstantiation, Function: Func); |
18610 | else { |
18611 | Func->setInstantiationIsPending(true); |
18612 | PendingInstantiations.push_back( |
18613 | std::make_pair(x&: Func, y&: PointOfInstantiation)); |
18614 | if (llvm::isTimeTraceVerbose()) { |
18615 | llvm::timeTraceAddInstantEvent(Name: "DeferInstantiation", Detail: [&] { |
18616 | std::string Name; |
18617 | llvm::raw_string_ostream OS(Name); |
18618 | Func->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
18619 | /*Qualified=*/true); |
18620 | return Name; |
18621 | }); |
18622 | } |
18623 | // Notify the consumer that a function was implicitly instantiated. |
18624 | Consumer.HandleCXXImplicitFunctionInstantiation(D: Func); |
18625 | } |
18626 | } |
18627 | } else { |
18628 | // Walk redefinitions, as some of them may be instantiable. |
18629 | for (auto *i : Func->redecls()) { |
18630 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) |
18631 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); |
18632 | } |
18633 | } |
18634 | }); |
18635 | } |
18636 | |
18637 | // If a constructor was defined in the context of a default parameter |
18638 | // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed |
18639 | // context), its initializers may not be referenced yet. |
18640 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Func)) { |
18641 | EnterExpressionEvaluationContext EvalContext( |
18642 | *this, |
18643 | Constructor->isImmediateFunction() |
18644 | ? ExpressionEvaluationContext::ImmediateFunctionContext |
18645 | : ExpressionEvaluationContext::PotentiallyEvaluated, |
18646 | Constructor); |
18647 | for (CXXCtorInitializer *Init : Constructor->inits()) { |
18648 | if (Init->isInClassMemberInitializer()) |
18649 | runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() { |
18650 | MarkDeclarationsReferencedInExpr(E: Init->getInit()); |
18651 | }); |
18652 | } |
18653 | } |
18654 | |
18655 | // C++14 [except.spec]p17: |
18656 | // An exception-specification is considered to be needed when: |
18657 | // - the function is odr-used or, if it appears in an unevaluated operand, |
18658 | // would be odr-used if the expression were potentially-evaluated; |
18659 | // |
18660 | // Note, we do this even if MightBeOdrUse is false. That indicates that the |
18661 | // function is a pure virtual function we're calling, and in that case the |
18662 | // function was selected by overload resolution and we need to resolve its |
18663 | // exception specification for a different reason. |
18664 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); |
18665 | if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) |
18666 | ResolveExceptionSpec(Loc, FPT); |
18667 | |
18668 | // A callee could be called by a host function then by a device function. |
18669 | // If we only try recording once, we will miss recording the use on device |
18670 | // side. Therefore keep trying until it is recorded. |
18671 | if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice && |
18672 | !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func)) |
18673 | CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func); |
18674 | |
18675 | // If this is the first "real" use, act on that. |
18676 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { |
18677 | // Keep track of used but undefined functions. |
18678 | if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) { |
18679 | if (mightHaveNonExternalLinkage(Func)) |
18680 | UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18681 | else if (Func->getMostRecentDecl()->isInlined() && |
18682 | !LangOpts.GNUInline && |
18683 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) |
18684 | UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18685 | else if (isExternalWithNoLinkageType(Func)) |
18686 | UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc)); |
18687 | } |
18688 | |
18689 | // Some x86 Windows calling conventions mangle the size of the parameter |
18690 | // pack into the name. Computing the size of the parameters requires the |
18691 | // parameter types to be complete. Check that now. |
18692 | if (funcHasParameterSizeMangling(S&: *this, FD: Func)) |
18693 | CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc); |
18694 | |
18695 | // In the MS C++ ABI, the compiler emits destructor variants where they are |
18696 | // used. If the destructor is used here but defined elsewhere, mark the |
18697 | // virtual base destructors referenced. If those virtual base destructors |
18698 | // are inline, this will ensure they are defined when emitting the complete |
18699 | // destructor variant. This checking may be redundant if the destructor is |
18700 | // provided later in this TU. |
18701 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
18702 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) { |
18703 | CXXRecordDecl *Parent = Dtor->getParent(); |
18704 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) |
18705 | CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor); |
18706 | } |
18707 | } |
18708 | |
18709 | Func->markUsed(Context); |
18710 | } |
18711 | } |
18712 | |
18713 | /// Directly mark a variable odr-used. Given a choice, prefer to use |
18714 | /// MarkVariableReferenced since it does additional checks and then |
18715 | /// calls MarkVarDeclODRUsed. |
18716 | /// If the variable must be captured: |
18717 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext |
18718 | /// - else capture it in the DeclContext that maps to the |
18719 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. |
18720 | static void |
18721 | MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, |
18722 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { |
18723 | // Keep track of used but undefined variables. |
18724 | // FIXME: We shouldn't suppress this warning for static data members. |
18725 | VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); |
18726 | assert(Var && "expected a capturable variable"); |
18727 | |
18728 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && |
18729 | (!Var->isExternallyVisible() || Var->isInline() || |
18730 | SemaRef.isExternalWithNoLinkageType(Var)) && |
18731 | !(Var->isStaticDataMember() && Var->hasInit())) { |
18732 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; |
18733 | if (old.isInvalid()) |
18734 | old = Loc; |
18735 | } |
18736 | QualType CaptureType, DeclRefType; |
18737 | if (SemaRef.LangOpts.OpenMP) |
18738 | SemaRef.OpenMP().tryCaptureOpenMPLambdas(V); |
18739 | SemaRef.tryCaptureVariable(Var: V, Loc, Kind: TryCaptureKind::Implicit, |
18740 | /*EllipsisLoc*/ SourceLocation(), |
18741 | /*BuildAndDiagnose*/ true, CaptureType, |
18742 | DeclRefType, FunctionScopeIndexToStopAt); |
18743 | |
18744 | if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { |
18745 | auto *FD = dyn_cast_or_null<FunctionDecl>(Val: SemaRef.CurContext); |
18746 | auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var); |
18747 | auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: FD); |
18748 | if (VarTarget == SemaCUDA::CVT_Host && |
18749 | (UserTarget == CUDAFunctionTarget::Device || |
18750 | UserTarget == CUDAFunctionTarget::HostDevice || |
18751 | UserTarget == CUDAFunctionTarget::Global)) { |
18752 | // Diagnose ODR-use of host global variables in device functions. |
18753 | // Reference of device global variables in host functions is allowed |
18754 | // through shadow variables therefore it is not diagnosed. |
18755 | if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) { |
18756 | SemaRef.targetDiag(Loc, diag::err_ref_bad_target) |
18757 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; |
18758 | SemaRef.targetDiag(Var->getLocation(), |
18759 | Var->getType().isConstQualified() |
18760 | ? diag::note_cuda_const_var_unpromoted |
18761 | : diag::note_cuda_host_var); |
18762 | } |
18763 | } else if (VarTarget == SemaCUDA::CVT_Device && |
18764 | !Var->hasAttr<CUDASharedAttr>() && |
18765 | (UserTarget == CUDAFunctionTarget::Host || |
18766 | UserTarget == CUDAFunctionTarget::HostDevice)) { |
18767 | // Record a CUDA/HIP device side variable if it is ODR-used |
18768 | // by host code. This is done conservatively, when the variable is |
18769 | // referenced in any of the following contexts: |
18770 | // - a non-function context |
18771 | // - a host function |
18772 | // - a host device function |
18773 | // This makes the ODR-use of the device side variable by host code to |
18774 | // be visible in the device compilation for the compiler to be able to |
18775 | // emit template variables instantiated by host code only and to |
18776 | // externalize the static device side variable ODR-used by host code. |
18777 | if (!Var->hasExternalStorage()) |
18778 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); |
18779 | else if (SemaRef.LangOpts.GPURelocatableDeviceCode && |
18780 | (!FD || (!FD->getDescribedFunctionTemplate() && |
18781 | SemaRef.getASTContext().GetGVALinkageForFunction(FD) == |
18782 | GVA_StrongExternal))) |
18783 | SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); |
18784 | } |
18785 | } |
18786 | |
18787 | V->markUsed(SemaRef.Context); |
18788 | } |
18789 | |
18790 | void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, |
18791 | SourceLocation Loc, |
18792 | unsigned CapturingScopeIndex) { |
18793 | MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex); |
18794 | } |
18795 | |
18796 | void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, |
18797 | ValueDecl *var) { |
18798 | DeclContext *VarDC = var->getDeclContext(); |
18799 | |
18800 | // If the parameter still belongs to the translation unit, then |
18801 | // we're actually just using one parameter in the declaration of |
18802 | // the next. |
18803 | if (isa<ParmVarDecl>(Val: var) && |
18804 | isa<TranslationUnitDecl>(Val: VarDC)) |
18805 | return; |
18806 | |
18807 | // For C code, don't diagnose about capture if we're not actually in code |
18808 | // right now; it's impossible to write a non-constant expression outside of |
18809 | // function context, so we'll get other (more useful) diagnostics later. |
18810 | // |
18811 | // For C++, things get a bit more nasty... it would be nice to suppress this |
18812 | // diagnostic for certain cases like using a local variable in an array bound |
18813 | // for a member of a local class, but the correct predicate is not obvious. |
18814 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) |
18815 | return; |
18816 | |
18817 | unsigned ValueKind = isa<BindingDecl>(Val: var) ? 1 : 0; |
18818 | unsigned ContextKind = 3; // unknown |
18819 | if (isa<CXXMethodDecl>(Val: VarDC) && |
18820 | cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) { |
18821 | ContextKind = 2; |
18822 | } else if (isa<FunctionDecl>(Val: VarDC)) { |
18823 | ContextKind = 0; |
18824 | } else if (isa<BlockDecl>(Val: VarDC)) { |
18825 | ContextKind = 1; |
18826 | } |
18827 | |
18828 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) |
18829 | << var << ValueKind << ContextKind << VarDC; |
18830 | S.Diag(var->getLocation(), diag::note_entity_declared_at) |
18831 | << var; |
18832 | |
18833 | // FIXME: Add additional diagnostic info about class etc. which prevents |
18834 | // capture. |
18835 | } |
18836 | |
18837 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, |
18838 | ValueDecl *Var, |
18839 | bool &SubCapturesAreNested, |
18840 | QualType &CaptureType, |
18841 | QualType &DeclRefType) { |
18842 | // Check whether we've already captured it. |
18843 | if (CSI->CaptureMap.count(Val: Var)) { |
18844 | // If we found a capture, any subcaptures are nested. |
18845 | SubCapturesAreNested = true; |
18846 | |
18847 | // Retrieve the capture type for this variable. |
18848 | CaptureType = CSI->getCapture(Var).getCaptureType(); |
18849 | |
18850 | // Compute the type of an expression that refers to this variable. |
18851 | DeclRefType = CaptureType.getNonReferenceType(); |
18852 | |
18853 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy |
18854 | // are mutable in the sense that user can change their value - they are |
18855 | // private instances of the captured declarations. |
18856 | const Capture &Cap = CSI->getCapture(Var); |
18857 | // C++ [expr.prim.lambda]p10: |
18858 | // The type of such a data member is [...] an lvalue reference to the |
18859 | // referenced function type if the entity is a reference to a function. |
18860 | // [...] |
18861 | if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() && |
18862 | !(isa<LambdaScopeInfo>(Val: CSI) && |
18863 | !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) && |
18864 | !(isa<CapturedRegionScopeInfo>(Val: CSI) && |
18865 | cast<CapturedRegionScopeInfo>(Val: CSI)->CapRegionKind == CR_OpenMP)) |
18866 | DeclRefType.addConst(); |
18867 | return true; |
18868 | } |
18869 | return false; |
18870 | } |
18871 | |
18872 | // Only block literals, captured statements, and lambda expressions can |
18873 | // capture; other scopes don't work. |
18874 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, |
18875 | ValueDecl *Var, |
18876 | SourceLocation Loc, |
18877 | const bool Diagnose, |
18878 | Sema &S) { |
18879 | if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC)) |
18880 | return getLambdaAwareParentOfDeclContext(DC); |
18881 | |
18882 | VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); |
18883 | if (Underlying) { |
18884 | if (Underlying->hasLocalStorage() && Diagnose) |
18885 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
18886 | } |
18887 | return nullptr; |
18888 | } |
18889 | |
18890 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
18891 | // certain types of variables (unnamed, variably modified types etc.) |
18892 | // so check for eligibility. |
18893 | static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, |
18894 | SourceLocation Loc, const bool Diagnose, |
18895 | Sema &S) { |
18896 | |
18897 | assert((isa<VarDecl, BindingDecl>(Var)) && |
18898 | "Only variables and structured bindings can be captured"); |
18899 | |
18900 | bool IsBlock = isa<BlockScopeInfo>(Val: CSI); |
18901 | bool IsLambda = isa<LambdaScopeInfo>(Val: CSI); |
18902 | |
18903 | // Lambdas are not allowed to capture unnamed variables |
18904 | // (e.g. anonymous unions). |
18905 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm |
18906 | // assuming that's the intent. |
18907 | if (IsLambda && !Var->getDeclName()) { |
18908 | if (Diagnose) { |
18909 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); |
18910 | S.Diag(Var->getLocation(), diag::note_declared_at); |
18911 | } |
18912 | return false; |
18913 | } |
18914 | |
18915 | // Prohibit variably-modified types in blocks; they're difficult to deal with. |
18916 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { |
18917 | if (Diagnose) { |
18918 | S.Diag(Loc, diag::err_ref_vm_type); |
18919 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
18920 | } |
18921 | return false; |
18922 | } |
18923 | // Prohibit structs with flexible array members too. |
18924 | // We cannot capture what is in the tail end of the struct. |
18925 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { |
18926 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { |
18927 | if (Diagnose) { |
18928 | if (IsBlock) |
18929 | S.Diag(Loc, diag::err_ref_flexarray_type); |
18930 | else |
18931 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; |
18932 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
18933 | } |
18934 | return false; |
18935 | } |
18936 | } |
18937 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
18938 | // Lambdas and captured statements are not allowed to capture __block |
18939 | // variables; they don't support the expected semantics. |
18940 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(Val: CSI))) { |
18941 | if (Diagnose) { |
18942 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; |
18943 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
18944 | } |
18945 | return false; |
18946 | } |
18947 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks |
18948 | if (S.getLangOpts().OpenCL && IsBlock && |
18949 | Var->getType()->isBlockPointerType()) { |
18950 | if (Diagnose) |
18951 | S.Diag(Loc, diag::err_opencl_block_ref_block); |
18952 | return false; |
18953 | } |
18954 | |
18955 | if (isa<BindingDecl>(Val: Var)) { |
18956 | if (!IsLambda || !S.getLangOpts().CPlusPlus) { |
18957 | if (Diagnose) |
18958 | diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var); |
18959 | return false; |
18960 | } else if (Diagnose && S.getLangOpts().CPlusPlus) { |
18961 | S.Diag(Loc, S.LangOpts.CPlusPlus20 |
18962 | ? diag::warn_cxx17_compat_capture_binding |
18963 | : diag::ext_capture_binding) |
18964 | << Var; |
18965 | S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; |
18966 | } |
18967 | } |
18968 | |
18969 | return true; |
18970 | } |
18971 | |
18972 | // Returns true if the capture by block was successful. |
18973 | static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, |
18974 | SourceLocation Loc, const bool BuildAndDiagnose, |
18975 | QualType &CaptureType, QualType &DeclRefType, |
18976 | const bool Nested, Sema &S, bool Invalid) { |
18977 | bool ByRef = false; |
18978 | |
18979 | // Blocks are not allowed to capture arrays, excepting OpenCL. |
18980 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference |
18981 | // (decayed to pointers). |
18982 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { |
18983 | if (BuildAndDiagnose) { |
18984 | S.Diag(Loc, diag::err_ref_array_type); |
18985 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
18986 | Invalid = true; |
18987 | } else { |
18988 | return false; |
18989 | } |
18990 | } |
18991 | |
18992 | // Forbid the block-capture of autoreleasing variables. |
18993 | if (!Invalid && |
18994 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
18995 | if (BuildAndDiagnose) { |
18996 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) |
18997 | << /*block*/ 0; |
18998 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
18999 | Invalid = true; |
19000 | } else { |
19001 | return false; |
19002 | } |
19003 | } |
19004 | |
19005 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. |
19006 | if (const auto *PT = CaptureType->getAs<PointerType>()) { |
19007 | QualType PointeeTy = PT->getPointeeType(); |
19008 | |
19009 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && |
19010 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && |
19011 | !S.Context.hasDirectOwnershipQualifier(Ty: PointeeTy)) { |
19012 | if (BuildAndDiagnose) { |
19013 | SourceLocation VarLoc = Var->getLocation(); |
19014 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); |
19015 | S.Diag(VarLoc, diag::note_declare_parameter_strong); |
19016 | } |
19017 | } |
19018 | } |
19019 | |
19020 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
19021 | if (HasBlocksAttr || CaptureType->isReferenceType() || |
19022 | (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(D: Var))) { |
19023 | // Block capture by reference does not change the capture or |
19024 | // declaration reference types. |
19025 | ByRef = true; |
19026 | } else { |
19027 | // Block capture by copy introduces 'const'. |
19028 | CaptureType = CaptureType.getNonReferenceType().withConst(); |
19029 | DeclRefType = CaptureType; |
19030 | } |
19031 | |
19032 | // Actually capture the variable. |
19033 | if (BuildAndDiagnose) |
19034 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), |
19035 | CaptureType, Invalid); |
19036 | |
19037 | return !Invalid; |
19038 | } |
19039 | |
19040 | /// Capture the given variable in the captured region. |
19041 | static bool captureInCapturedRegion( |
19042 | CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, |
19043 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, |
19044 | const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, |
19045 | Sema &S, bool Invalid) { |
19046 | // By default, capture variables by reference. |
19047 | bool ByRef = true; |
19048 | if (IsTopScope && Kind != TryCaptureKind::Implicit) { |
19049 | ByRef = (Kind == TryCaptureKind::ExplicitByRef); |
19050 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { |
19051 | // Using an LValue reference type is consistent with Lambdas (see below). |
19052 | if (S.OpenMP().isOpenMPCapturedDecl(D: Var)) { |
19053 | bool HasConst = DeclRefType.isConstQualified(); |
19054 | DeclRefType = DeclRefType.getUnqualifiedType(); |
19055 | // Don't lose diagnostics about assignments to const. |
19056 | if (HasConst) |
19057 | DeclRefType.addConst(); |
19058 | } |
19059 | // Do not capture firstprivates in tasks. |
19060 | if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, |
19061 | RSI->OpenMPCaptureLevel) != OMPC_unknown) |
19062 | return true; |
19063 | ByRef = S.OpenMP().isOpenMPCapturedByRef(D: Var, Level: RSI->OpenMPLevel, |
19064 | OpenMPCaptureLevel: RSI->OpenMPCaptureLevel); |
19065 | } |
19066 | |
19067 | if (ByRef) |
19068 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
19069 | else |
19070 | CaptureType = DeclRefType; |
19071 | |
19072 | // Actually capture the variable. |
19073 | if (BuildAndDiagnose) |
19074 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, |
19075 | Loc, SourceLocation(), CaptureType, Invalid); |
19076 | |
19077 | return !Invalid; |
19078 | } |
19079 | |
19080 | /// Capture the given variable in the lambda. |
19081 | static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, |
19082 | SourceLocation Loc, const bool BuildAndDiagnose, |
19083 | QualType &CaptureType, QualType &DeclRefType, |
19084 | const bool RefersToCapturedVariable, |
19085 | const TryCaptureKind Kind, |
19086 | SourceLocation EllipsisLoc, const bool IsTopScope, |
19087 | Sema &S, bool Invalid) { |
19088 | // Determine whether we are capturing by reference or by value. |
19089 | bool ByRef = false; |
19090 | if (IsTopScope && Kind != TryCaptureKind::Implicit) { |
19091 | ByRef = (Kind == TryCaptureKind::ExplicitByRef); |
19092 | } else { |
19093 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); |
19094 | } |
19095 | |
19096 | if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() && |
19097 | CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) { |
19098 | S.Diag(Loc, diag::err_wasm_ca_reference) << 0; |
19099 | Invalid = true; |
19100 | } |
19101 | |
19102 | // Compute the type of the field that will capture this variable. |
19103 | if (ByRef) { |
19104 | // C++11 [expr.prim.lambda]p15: |
19105 | // An entity is captured by reference if it is implicitly or |
19106 | // explicitly captured but not captured by copy. It is |
19107 | // unspecified whether additional unnamed non-static data |
19108 | // members are declared in the closure type for entities |
19109 | // captured by reference. |
19110 | // |
19111 | // FIXME: It is not clear whether we want to build an lvalue reference |
19112 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears |
19113 | // to do the former, while EDG does the latter. Core issue 1249 will |
19114 | // clarify, but for now we follow GCC because it's a more permissive and |
19115 | // easily defensible position. |
19116 | CaptureType = S.Context.getLValueReferenceType(T: DeclRefType); |
19117 | } else { |
19118 | // C++11 [expr.prim.lambda]p14: |
19119 | // For each entity captured by copy, an unnamed non-static |
19120 | // data member is declared in the closure type. The |
19121 | // declaration order of these members is unspecified. The type |
19122 | // of such a data member is the type of the corresponding |
19123 | // captured entity if the entity is not a reference to an |
19124 | // object, or the referenced type otherwise. [Note: If the |
19125 | // captured entity is a reference to a function, the |
19126 | // corresponding data member is also a reference to a |
19127 | // function. - end note ] |
19128 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ |
19129 | if (!RefType->getPointeeType()->isFunctionType()) |
19130 | CaptureType = RefType->getPointeeType(); |
19131 | } |
19132 | |
19133 | // Forbid the lambda copy-capture of autoreleasing variables. |
19134 | if (!Invalid && |
19135 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
19136 | if (BuildAndDiagnose) { |
19137 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; |
19138 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
19139 | << Var->getDeclName(); |
19140 | Invalid = true; |
19141 | } else { |
19142 | return false; |
19143 | } |
19144 | } |
19145 | |
19146 | // Make sure that by-copy captures are of a complete and non-abstract type. |
19147 | if (!Invalid && BuildAndDiagnose) { |
19148 | if (!CaptureType->isDependentType() && |
19149 | S.RequireCompleteSizedType( |
19150 | Loc, CaptureType, |
19151 | diag::err_capture_of_incomplete_or_sizeless_type, |
19152 | Var->getDeclName())) |
19153 | Invalid = true; |
19154 | else if (S.RequireNonAbstractType(Loc, CaptureType, |
19155 | diag::err_capture_of_abstract_type)) |
19156 | Invalid = true; |
19157 | } |
19158 | } |
19159 | |
19160 | // Compute the type of a reference to this captured variable. |
19161 | if (ByRef) |
19162 | DeclRefType = CaptureType.getNonReferenceType(); |
19163 | else { |
19164 | // C++ [expr.prim.lambda]p5: |
19165 | // The closure type for a lambda-expression has a public inline |
19166 | // function call operator [...]. This function call operator is |
19167 | // declared const (9.3.1) if and only if the lambda-expression's |
19168 | // parameter-declaration-clause is not followed by mutable. |
19169 | DeclRefType = CaptureType.getNonReferenceType(); |
19170 | bool Const = LSI->lambdaCaptureShouldBeConst(); |
19171 | // C++ [expr.prim.lambda]p10: |
19172 | // The type of such a data member is [...] an lvalue reference to the |
19173 | // referenced function type if the entity is a reference to a function. |
19174 | // [...] |
19175 | if (Const && !CaptureType->isReferenceType() && |
19176 | !DeclRefType->isFunctionType()) |
19177 | DeclRefType.addConst(); |
19178 | } |
19179 | |
19180 | // Add the capture. |
19181 | if (BuildAndDiagnose) |
19182 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, |
19183 | Loc, EllipsisLoc, CaptureType, Invalid); |
19184 | |
19185 | return !Invalid; |
19186 | } |
19187 | |
19188 | static bool canCaptureVariableByCopy(ValueDecl *Var, |
19189 | const ASTContext &Context) { |
19190 | // Offer a Copy fix even if the type is dependent. |
19191 | if (Var->getType()->isDependentType()) |
19192 | return true; |
19193 | QualType T = Var->getType().getNonReferenceType(); |
19194 | if (T.isTriviallyCopyableType(Context)) |
19195 | return true; |
19196 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
19197 | |
19198 | if (!(RD = RD->getDefinition())) |
19199 | return false; |
19200 | if (RD->hasSimpleCopyConstructor()) |
19201 | return true; |
19202 | if (RD->hasUserDeclaredCopyConstructor()) |
19203 | for (CXXConstructorDecl *Ctor : RD->ctors()) |
19204 | if (Ctor->isCopyConstructor()) |
19205 | return !Ctor->isDeleted(); |
19206 | } |
19207 | return false; |
19208 | } |
19209 | |
19210 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or |
19211 | /// default capture. Fixes may be omitted if they aren't allowed by the |
19212 | /// standard, for example we can't emit a default copy capture fix-it if we |
19213 | /// already explicitly copy capture capture another variable. |
19214 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, |
19215 | ValueDecl *Var) { |
19216 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); |
19217 | // Don't offer Capture by copy of default capture by copy fixes if Var is |
19218 | // known not to be copy constructible. |
19219 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Context: Sema.getASTContext()); |
19220 | |
19221 | SmallString<32> FixBuffer; |
19222 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", ": ""; |
19223 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { |
19224 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); |
19225 | if (ShouldOfferCopyFix) { |
19226 | // Offer fixes to insert an explicit capture for the variable. |
19227 | // [] -> [VarName] |
19228 | // [OtherCapture] -> [OtherCapture, VarName] |
19229 | FixBuffer.assign({Separator, Var->getName()}); |
19230 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) |
19231 | << Var << /*value*/ 0 |
19232 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); |
19233 | } |
19234 | // As above but capture by reference. |
19235 | FixBuffer.assign({Separator, "&", Var->getName()}); |
19236 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) |
19237 | << Var << /*reference*/ 1 |
19238 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); |
19239 | } |
19240 | |
19241 | // Only try to offer default capture if there are no captures excluding this |
19242 | // and init captures. |
19243 | // [this]: OK. |
19244 | // [X = Y]: OK. |
19245 | // [&A, &B]: Don't offer. |
19246 | // [A, B]: Don't offer. |
19247 | if (llvm::any_of(Range&: LSI->Captures, P: [](Capture &C) { |
19248 | return !C.isThisCapture() && !C.isInitCapture(); |
19249 | })) |
19250 | return; |
19251 | |
19252 | // The default capture specifiers, '=' or '&', must appear first in the |
19253 | // capture body. |
19254 | SourceLocation DefaultInsertLoc = |
19255 | LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1); |
19256 | |
19257 | if (ShouldOfferCopyFix) { |
19258 | bool CanDefaultCopyCapture = true; |
19259 | // [=, *this] OK since c++17 |
19260 | // [=, this] OK since c++20 |
19261 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) |
19262 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 |
19263 | ? LSI->getCXXThisCapture().isCopyCapture() |
19264 | : false; |
19265 | // We can't use default capture by copy if any captures already specified |
19266 | // capture by copy. |
19267 | if (CanDefaultCopyCapture && llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
19268 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); |
19269 | })) { |
19270 | FixBuffer.assign(Refs: {"=", Separator}); |
19271 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) |
19272 | << /*value*/ 0 |
19273 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); |
19274 | } |
19275 | } |
19276 | |
19277 | // We can't use default capture by reference if any captures already specified |
19278 | // capture by reference. |
19279 | if (llvm::none_of(Range&: LSI->Captures, P: [](Capture &C) { |
19280 | return !C.isInitCapture() && C.isReferenceCapture() && |
19281 | !C.isThisCapture(); |
19282 | })) { |
19283 | FixBuffer.assign(Refs: {"&", Separator}); |
19284 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) |
19285 | << /*reference*/ 1 |
19286 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); |
19287 | } |
19288 | } |
19289 | |
19290 | bool Sema::tryCaptureVariable( |
19291 | ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, |
19292 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, |
19293 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { |
19294 | // An init-capture is notionally from the context surrounding its |
19295 | // declaration, but its parent DC is the lambda class. |
19296 | DeclContext *VarDC = Var->getDeclContext(); |
19297 | DeclContext *DC = CurContext; |
19298 | |
19299 | // Skip past RequiresExprBodys because they don't constitute function scopes. |
19300 | while (DC->isRequiresExprBody()) |
19301 | DC = DC->getParent(); |
19302 | |
19303 | // tryCaptureVariable is called every time a DeclRef is formed, |
19304 | // it can therefore have non-negigible impact on performances. |
19305 | // For local variables and when there is no capturing scope, |
19306 | // we can bailout early. |
19307 | if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC)) |
19308 | return true; |
19309 | |
19310 | // Exception: Function parameters are not tied to the function's DeclContext |
19311 | // until we enter the function definition. Capturing them anyway would result |
19312 | // in an out-of-bounds error while traversing DC and its parents. |
19313 | if (isa<ParmVarDecl>(Val: Var) && !VarDC->isFunctionOrMethod()) |
19314 | return true; |
19315 | |
19316 | const auto *VD = dyn_cast<VarDecl>(Val: Var); |
19317 | if (VD) { |
19318 | if (VD->isInitCapture()) |
19319 | VarDC = VarDC->getParent(); |
19320 | } else { |
19321 | VD = Var->getPotentiallyDecomposedVarDecl(); |
19322 | } |
19323 | assert(VD && "Cannot capture a null variable"); |
19324 | |
19325 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
19326 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; |
19327 | // We need to sync up the Declaration Context with the |
19328 | // FunctionScopeIndexToStopAt |
19329 | if (FunctionScopeIndexToStopAt) { |
19330 | assert(!FunctionScopes.empty() && "No function scopes to stop at?"); |
19331 | unsigned FSIndex = FunctionScopes.size() - 1; |
19332 | // When we're parsing the lambda parameter list, the current DeclContext is |
19333 | // NOT the lambda but its parent. So move away the current LSI before |
19334 | // aligning DC and FunctionScopeIndexToStopAt. |
19335 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FunctionScopes[FSIndex]); |
19336 | FSIndex && LSI && !LSI->AfterParameterList) |
19337 | --FSIndex; |
19338 | assert(MaxFunctionScopesIndex <= FSIndex && |
19339 | "FunctionScopeIndexToStopAt should be no greater than FSIndex into " |
19340 | "FunctionScopes."); |
19341 | while (FSIndex != MaxFunctionScopesIndex) { |
19342 | DC = getLambdaAwareParentOfDeclContext(DC); |
19343 | --FSIndex; |
19344 | } |
19345 | } |
19346 | |
19347 | // Capture global variables if it is required to use private copy of this |
19348 | // variable. |
19349 | bool IsGlobal = !VD->hasLocalStorage(); |
19350 | if (IsGlobal && !(LangOpts.OpenMP && |
19351 | OpenMP().isOpenMPCapturedDecl(D: Var, /*CheckScopeInfo=*/true, |
19352 | StopAt: MaxFunctionScopesIndex))) |
19353 | return true; |
19354 | |
19355 | if (isa<VarDecl>(Val: Var)) |
19356 | Var = cast<VarDecl>(Var->getCanonicalDecl()); |
19357 | |
19358 | // Walk up the stack to determine whether we can capture the variable, |
19359 | // performing the "simple" checks that don't depend on type. We stop when |
19360 | // we've either hit the declared scope of the variable or find an existing |
19361 | // capture of that variable. We start from the innermost capturing-entity |
19362 | // (the DC) and ensure that all intervening capturing-entities |
19363 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s |
19364 | // declcontext can either capture the variable or have already captured |
19365 | // the variable. |
19366 | CaptureType = Var->getType(); |
19367 | DeclRefType = CaptureType.getNonReferenceType(); |
19368 | bool Nested = false; |
19369 | bool Explicit = (Kind != TryCaptureKind::Implicit); |
19370 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; |
19371 | do { |
19372 | |
19373 | LambdaScopeInfo *LSI = nullptr; |
19374 | if (!FunctionScopes.empty()) |
19375 | LSI = dyn_cast_or_null<LambdaScopeInfo>( |
19376 | Val: FunctionScopes[FunctionScopesIndex]); |
19377 | |
19378 | bool IsInScopeDeclarationContext = |
19379 | !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator; |
19380 | |
19381 | if (LSI && !LSI->AfterParameterList) { |
19382 | // This allows capturing parameters from a default value which does not |
19383 | // seems correct |
19384 | if (isa<ParmVarDecl>(Val: Var) && !Var->getDeclContext()->isFunctionOrMethod()) |
19385 | return true; |
19386 | } |
19387 | // If the variable is declared in the current context, there is no need to |
19388 | // capture it. |
19389 | if (IsInScopeDeclarationContext && |
19390 | FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC) |
19391 | return true; |
19392 | |
19393 | // Only block literals, captured statements, and lambda expressions can |
19394 | // capture; other scopes don't work. |
19395 | DeclContext *ParentDC = |
19396 | !IsInScopeDeclarationContext |
19397 | ? DC->getParent() |
19398 | : getParentOfCapturingContextOrNull(DC, Var, Loc: ExprLoc, |
19399 | Diagnose: BuildAndDiagnose, S&: *this); |
19400 | // We need to check for the parent *first* because, if we *have* |
19401 | // private-captured a global variable, we need to recursively capture it in |
19402 | // intermediate blocks, lambdas, etc. |
19403 | if (!ParentDC) { |
19404 | if (IsGlobal) { |
19405 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; |
19406 | break; |
19407 | } |
19408 | return true; |
19409 | } |
19410 | |
19411 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; |
19412 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FSI); |
19413 | |
19414 | // Check whether we've already captured it. |
19415 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType, |
19416 | DeclRefType)) { |
19417 | CSI->getCapture(Var).markUsed(IsODRUse: BuildAndDiagnose); |
19418 | break; |
19419 | } |
19420 | |
19421 | // When evaluating some attributes (like enable_if) we might refer to a |
19422 | // function parameter appertaining to the same declaration as that |
19423 | // attribute. |
19424 | if (const auto *Parm = dyn_cast<ParmVarDecl>(Val: Var); |
19425 | Parm && Parm->getDeclContext() == DC) |
19426 | return true; |
19427 | |
19428 | // If we are instantiating a generic lambda call operator body, |
19429 | // we do not want to capture new variables. What was captured |
19430 | // during either a lambdas transformation or initial parsing |
19431 | // should be used. |
19432 | if (isGenericLambdaCallOperatorSpecialization(DC)) { |
19433 | if (BuildAndDiagnose) { |
19434 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
19435 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { |
19436 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; |
19437 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
19438 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); |
19439 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
19440 | } else |
19441 | diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var); |
19442 | } |
19443 | return true; |
19444 | } |
19445 | |
19446 | // Try to capture variable-length arrays types. |
19447 | if (Var->getType()->isVariablyModifiedType()) { |
19448 | // We're going to walk down into the type and look for VLA |
19449 | // expressions. |
19450 | QualType QTy = Var->getType(); |
19451 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
19452 | QTy = PVD->getOriginalType(); |
19453 | captureVariablyModifiedType(Context, T: QTy, CSI); |
19454 | } |
19455 | |
19456 | if (getLangOpts().OpenMP) { |
19457 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
19458 | // OpenMP private variables should not be captured in outer scope, so |
19459 | // just break here. Similarly, global variables that are captured in a |
19460 | // target region should not be captured outside the scope of the region. |
19461 | if (RSI->CapRegionKind == CR_OpenMP) { |
19462 | // FIXME: We should support capturing structured bindings in OpenMP. |
19463 | if (isa<BindingDecl>(Val: Var)) { |
19464 | if (BuildAndDiagnose) { |
19465 | Diag(ExprLoc, diag::err_capture_binding_openmp) << Var; |
19466 | Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; |
19467 | } |
19468 | return true; |
19469 | } |
19470 | OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl( |
19471 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); |
19472 | // If the variable is private (i.e. not captured) and has variably |
19473 | // modified type, we still need to capture the type for correct |
19474 | // codegen in all regions, associated with the construct. Currently, |
19475 | // it is captured in the innermost captured region only. |
19476 | if (IsOpenMPPrivateDecl != OMPC_unknown && |
19477 | Var->getType()->isVariablyModifiedType()) { |
19478 | QualType QTy = Var->getType(); |
19479 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Val: Var)) |
19480 | QTy = PVD->getOriginalType(); |
19481 | for (int I = 1, |
19482 | E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel); |
19483 | I < E; ++I) { |
19484 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( |
19485 | Val: FunctionScopes[FunctionScopesIndex - I]); |
19486 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && |
19487 | "Wrong number of captured regions associated with the " |
19488 | "OpenMP construct."); |
19489 | captureVariablyModifiedType(Context, QTy, OuterRSI); |
19490 | } |
19491 | } |
19492 | bool IsTargetCap = |
19493 | IsOpenMPPrivateDecl != OMPC_private && |
19494 | OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, |
19495 | RSI->OpenMPCaptureLevel); |
19496 | // Do not capture global if it is not privatized in outer regions. |
19497 | bool IsGlobalCap = |
19498 | IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl( |
19499 | D: Var, Level: RSI->OpenMPLevel, CaptureLevel: RSI->OpenMPCaptureLevel); |
19500 | |
19501 | // When we detect target captures we are looking from inside the |
19502 | // target region, therefore we need to propagate the capture from the |
19503 | // enclosing region. Therefore, the capture is not initially nested. |
19504 | if (IsTargetCap) |
19505 | OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex, |
19506 | Level: RSI->OpenMPLevel); |
19507 | |
19508 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || |
19509 | (IsGlobal && !IsGlobalCap)) { |
19510 | Nested = !IsTargetCap; |
19511 | bool HasConst = DeclRefType.isConstQualified(); |
19512 | DeclRefType = DeclRefType.getUnqualifiedType(); |
19513 | // Don't lose diagnostics about assignments to const. |
19514 | if (HasConst) |
19515 | DeclRefType.addConst(); |
19516 | CaptureType = Context.getLValueReferenceType(T: DeclRefType); |
19517 | break; |
19518 | } |
19519 | } |
19520 | } |
19521 | } |
19522 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { |
19523 | // No capture-default, and this is not an explicit capture |
19524 | // so cannot capture this variable. |
19525 | if (BuildAndDiagnose) { |
19526 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; |
19527 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; |
19528 | auto *LSI = cast<LambdaScopeInfo>(Val: CSI); |
19529 | if (LSI->Lambda) { |
19530 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); |
19531 | buildLambdaCaptureFixit(Sema&: *this, LSI, Var); |
19532 | } |
19533 | // FIXME: If we error out because an outer lambda can not implicitly |
19534 | // capture a variable that an inner lambda explicitly captures, we |
19535 | // should have the inner lambda do the explicit capture - because |
19536 | // it makes for cleaner diagnostics later. This would purely be done |
19537 | // so that the diagnostic does not misleadingly claim that a variable |
19538 | // can not be captured by a lambda implicitly even though it is captured |
19539 | // explicitly. Suggestion: |
19540 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit |
19541 | // at the function head |
19542 | // - cache the StartingDeclContext - this must be a lambda |
19543 | // - captureInLambda in the innermost lambda the variable. |
19544 | } |
19545 | return true; |
19546 | } |
19547 | Explicit = false; |
19548 | FunctionScopesIndex--; |
19549 | if (IsInScopeDeclarationContext) |
19550 | DC = ParentDC; |
19551 | } while (!VarDC->Equals(DC)); |
19552 | |
19553 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) |
19554 | // computing the type of the capture at each step, checking type-specific |
19555 | // requirements, and adding captures if requested. |
19556 | // If the variable had already been captured previously, we start capturing |
19557 | // at the lambda nested within that one. |
19558 | bool Invalid = false; |
19559 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; |
19560 | ++I) { |
19561 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[I]); |
19562 | |
19563 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
19564 | // certain types of variables (unnamed, variably modified types etc.) |
19565 | // so check for eligibility. |
19566 | if (!Invalid) |
19567 | Invalid = |
19568 | !isVariableCapturable(CSI, Var, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *this); |
19569 | |
19570 | // After encountering an error, if we're actually supposed to capture, keep |
19571 | // capturing in nested contexts to suppress any follow-on diagnostics. |
19572 | if (Invalid && !BuildAndDiagnose) |
19573 | return true; |
19574 | |
19575 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(Val: CSI)) { |
19576 | Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
19577 | DeclRefType, Nested, S&: *this, Invalid); |
19578 | Nested = true; |
19579 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) { |
19580 | Invalid = !captureInCapturedRegion( |
19581 | RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested, |
19582 | Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
19583 | Nested = true; |
19584 | } else { |
19585 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI); |
19586 | Invalid = |
19587 | !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, |
19588 | DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc, |
19589 | /*IsTopScope*/ I == N - 1, S&: *this, Invalid); |
19590 | Nested = true; |
19591 | } |
19592 | |
19593 | if (Invalid && !BuildAndDiagnose) |
19594 | return true; |
19595 | } |
19596 | return Invalid; |
19597 | } |
19598 | |
19599 | bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, |
19600 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { |
19601 | QualType CaptureType; |
19602 | QualType DeclRefType; |
19603 | return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc, |
19604 | /*BuildAndDiagnose=*/true, CaptureType, |
19605 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
19606 | } |
19607 | |
19608 | bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { |
19609 | QualType CaptureType; |
19610 | QualType DeclRefType; |
19611 | return !tryCaptureVariable( |
19612 | Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(), |
19613 | /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
19614 | } |
19615 | |
19616 | QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { |
19617 | assert(Var && "Null value cannot be captured"); |
19618 | |
19619 | QualType CaptureType; |
19620 | QualType DeclRefType; |
19621 | |
19622 | // Determine whether we can capture this variable. |
19623 | if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCaptureKind::Implicit, EllipsisLoc: SourceLocation(), |
19624 | /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, |
19625 | FunctionScopeIndexToStopAt: nullptr)) |
19626 | return QualType(); |
19627 | |
19628 | return DeclRefType; |
19629 | } |
19630 | |
19631 | namespace { |
19632 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. |
19633 | // The produced TemplateArgumentListInfo* points to data stored within this |
19634 | // object, so should only be used in contexts where the pointer will not be |
19635 | // used after the CopiedTemplateArgs object is destroyed. |
19636 | class CopiedTemplateArgs { |
19637 | bool HasArgs; |
19638 | TemplateArgumentListInfo TemplateArgStorage; |
19639 | public: |
19640 | template<typename RefExpr> |
19641 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { |
19642 | if (HasArgs) |
19643 | E->copyTemplateArgumentsInto(TemplateArgStorage); |
19644 | } |
19645 | operator TemplateArgumentListInfo*() |
19646 | #ifdef __has_cpp_attribute |
19647 | #if __has_cpp_attribute(clang::lifetimebound) |
19648 | [[clang::lifetimebound]] |
19649 | #endif |
19650 | #endif |
19651 | { |
19652 | return HasArgs ? &TemplateArgStorage : nullptr; |
19653 | } |
19654 | }; |
19655 | } |
19656 | |
19657 | /// Walk the set of potential results of an expression and mark them all as |
19658 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. |
19659 | /// |
19660 | /// \return A new expression if we found any potential results, ExprEmpty() if |
19661 | /// not, and ExprError() if we diagnosed an error. |
19662 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, |
19663 | NonOdrUseReason NOUR) { |
19664 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is |
19665 | // an object that satisfies the requirements for appearing in a |
19666 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) |
19667 | // is immediately applied." This function handles the lvalue-to-rvalue |
19668 | // conversion part. |
19669 | // |
19670 | // If we encounter a node that claims to be an odr-use but shouldn't be, we |
19671 | // transform it into the relevant kind of non-odr-use node and rebuild the |
19672 | // tree of nodes leading to it. |
19673 | // |
19674 | // This is a mini-TreeTransform that only transforms a restricted subset of |
19675 | // nodes (and only certain operands of them). |
19676 | |
19677 | // Rebuild a subexpression. |
19678 | auto Rebuild = [&](Expr *Sub) { |
19679 | return rebuildPotentialResultsAsNonOdrUsed(S, E: Sub, NOUR); |
19680 | }; |
19681 | |
19682 | // Check whether a potential result satisfies the requirements of NOUR. |
19683 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { |
19684 | // Any entity other than a VarDecl is always odr-used whenever it's named |
19685 | // in a potentially-evaluated expression. |
19686 | auto *VD = dyn_cast<VarDecl>(Val: D); |
19687 | if (!VD) |
19688 | return true; |
19689 | |
19690 | // C++2a [basic.def.odr]p4: |
19691 | // A variable x whose name appears as a potentially-evalauted expression |
19692 | // e is odr-used by e unless |
19693 | // -- x is a reference that is usable in constant expressions, or |
19694 | // -- x is a variable of non-reference type that is usable in constant |
19695 | // expressions and has no mutable subobjects, and e is an element of |
19696 | // the set of potential results of an expression of |
19697 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
19698 | // conversion is applied, or |
19699 | // -- x is a variable of non-reference type, and e is an element of the |
19700 | // set of potential results of a discarded-value expression to which |
19701 | // the lvalue-to-rvalue conversion is not applied |
19702 | // |
19703 | // We check the first bullet and the "potentially-evaluated" condition in |
19704 | // BuildDeclRefExpr. We check the type requirements in the second bullet |
19705 | // in CheckLValueToRValueConversionOperand below. |
19706 | switch (NOUR) { |
19707 | case NOUR_None: |
19708 | case NOUR_Unevaluated: |
19709 | llvm_unreachable("unexpected non-odr-use-reason"); |
19710 | |
19711 | case NOUR_Constant: |
19712 | // Constant references were handled when they were built. |
19713 | if (VD->getType()->isReferenceType()) |
19714 | return true; |
19715 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) |
19716 | if (RD->hasDefinition() && RD->hasMutableFields()) |
19717 | return true; |
19718 | if (!VD->isUsableInConstantExpressions(C: S.Context)) |
19719 | return true; |
19720 | break; |
19721 | |
19722 | case NOUR_Discarded: |
19723 | if (VD->getType()->isReferenceType()) |
19724 | return true; |
19725 | break; |
19726 | } |
19727 | return false; |
19728 | }; |
19729 | |
19730 | // Check whether this expression may be odr-used in CUDA/HIP. |
19731 | auto MaybeCUDAODRUsed = [&]() -> bool { |
19732 | if (!S.LangOpts.CUDA) |
19733 | return false; |
19734 | LambdaScopeInfo *LSI = S.getCurLambda(); |
19735 | if (!LSI) |
19736 | return false; |
19737 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
19738 | if (!DRE) |
19739 | return false; |
19740 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
19741 | if (!VD) |
19742 | return false; |
19743 | return LSI->CUDAPotentialODRUsedVars.count(Ptr: VD); |
19744 | }; |
19745 | |
19746 | // Mark that this expression does not constitute an odr-use. |
19747 | auto MarkNotOdrUsed = [&] { |
19748 | if (!MaybeCUDAODRUsed()) { |
19749 | S.MaybeODRUseExprs.remove(X: E); |
19750 | if (LambdaScopeInfo *LSI = S.getCurLambda()) |
19751 | LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: E); |
19752 | } |
19753 | }; |
19754 | |
19755 | // C++2a [basic.def.odr]p2: |
19756 | // The set of potential results of an expression e is defined as follows: |
19757 | switch (E->getStmtClass()) { |
19758 | // -- If e is an id-expression, ... |
19759 | case Expr::DeclRefExprClass: { |
19760 | auto *DRE = cast<DeclRefExpr>(Val: E); |
19761 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) |
19762 | break; |
19763 | |
19764 | // Rebuild as a non-odr-use DeclRefExpr. |
19765 | MarkNotOdrUsed(); |
19766 | return DeclRefExpr::Create( |
19767 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), |
19768 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), |
19769 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), |
19770 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); |
19771 | } |
19772 | |
19773 | case Expr::FunctionParmPackExprClass: { |
19774 | auto *FPPE = cast<FunctionParmPackExpr>(Val: E); |
19775 | // If any of the declarations in the pack is odr-used, then the expression |
19776 | // as a whole constitutes an odr-use. |
19777 | for (ValueDecl *D : *FPPE) |
19778 | if (IsPotentialResultOdrUsed(D)) |
19779 | return ExprEmpty(); |
19780 | |
19781 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, |
19782 | // nothing cares about whether we marked this as an odr-use, but it might |
19783 | // be useful for non-compiler tools. |
19784 | MarkNotOdrUsed(); |
19785 | break; |
19786 | } |
19787 | |
19788 | // -- If e is a subscripting operation with an array operand... |
19789 | case Expr::ArraySubscriptExprClass: { |
19790 | auto *ASE = cast<ArraySubscriptExpr>(Val: E); |
19791 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); |
19792 | if (!OldBase->getType()->isArrayType()) |
19793 | break; |
19794 | ExprResult Base = Rebuild(OldBase); |
19795 | if (!Base.isUsable()) |
19796 | return Base; |
19797 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); |
19798 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); |
19799 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. |
19800 | return S.ActOnArraySubscriptExpr(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS, |
19801 | rbLoc: ASE->getRBracketLoc()); |
19802 | } |
19803 | |
19804 | case Expr::MemberExprClass: { |
19805 | auto *ME = cast<MemberExpr>(Val: E); |
19806 | // -- If e is a class member access expression [...] naming a non-static |
19807 | // data member... |
19808 | if (isa<FieldDecl>(Val: ME->getMemberDecl())) { |
19809 | ExprResult Base = Rebuild(ME->getBase()); |
19810 | if (!Base.isUsable()) |
19811 | return Base; |
19812 | return MemberExpr::Create( |
19813 | C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
19814 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), |
19815 | MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), |
19816 | TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(), |
19817 | OK: ME->getObjectKind(), NOUR: ME->isNonOdrUse()); |
19818 | } |
19819 | |
19820 | if (ME->getMemberDecl()->isCXXInstanceMember()) |
19821 | break; |
19822 | |
19823 | // -- If e is a class member access expression naming a static data member, |
19824 | // ... |
19825 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) |
19826 | break; |
19827 | |
19828 | // Rebuild as a non-odr-use MemberExpr. |
19829 | MarkNotOdrUsed(); |
19830 | return MemberExpr::Create( |
19831 | C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(), |
19832 | QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(), |
19833 | FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME), |
19834 | T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR); |
19835 | } |
19836 | |
19837 | case Expr::BinaryOperatorClass: { |
19838 | auto *BO = cast<BinaryOperator>(Val: E); |
19839 | Expr *LHS = BO->getLHS(); |
19840 | Expr *RHS = BO->getRHS(); |
19841 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... |
19842 | if (BO->getOpcode() == BO_PtrMemD) { |
19843 | ExprResult Sub = Rebuild(LHS); |
19844 | if (!Sub.isUsable()) |
19845 | return Sub; |
19846 | BO->setLHS(Sub.get()); |
19847 | // -- If e is a comma expression, ... |
19848 | } else if (BO->getOpcode() == BO_Comma) { |
19849 | ExprResult Sub = Rebuild(RHS); |
19850 | if (!Sub.isUsable()) |
19851 | return Sub; |
19852 | BO->setRHS(Sub.get()); |
19853 | } else { |
19854 | break; |
19855 | } |
19856 | return ExprResult(BO); |
19857 | } |
19858 | |
19859 | // -- If e has the form (e1)... |
19860 | case Expr::ParenExprClass: { |
19861 | auto *PE = cast<ParenExpr>(Val: E); |
19862 | ExprResult Sub = Rebuild(PE->getSubExpr()); |
19863 | if (!Sub.isUsable()) |
19864 | return Sub; |
19865 | return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: Sub.get()); |
19866 | } |
19867 | |
19868 | // -- If e is a glvalue conditional expression, ... |
19869 | // We don't apply this to a binary conditional operator. FIXME: Should we? |
19870 | case Expr::ConditionalOperatorClass: { |
19871 | auto *CO = cast<ConditionalOperator>(Val: E); |
19872 | ExprResult LHS = Rebuild(CO->getLHS()); |
19873 | if (LHS.isInvalid()) |
19874 | return ExprError(); |
19875 | ExprResult RHS = Rebuild(CO->getRHS()); |
19876 | if (RHS.isInvalid()) |
19877 | return ExprError(); |
19878 | if (!LHS.isUsable() && !RHS.isUsable()) |
19879 | return ExprEmpty(); |
19880 | if (!LHS.isUsable()) |
19881 | LHS = CO->getLHS(); |
19882 | if (!RHS.isUsable()) |
19883 | RHS = CO->getRHS(); |
19884 | return S.ActOnConditionalOp(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(), |
19885 | CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
19886 | } |
19887 | |
19888 | // [Clang extension] |
19889 | // -- If e has the form __extension__ e1... |
19890 | case Expr::UnaryOperatorClass: { |
19891 | auto *UO = cast<UnaryOperator>(Val: E); |
19892 | if (UO->getOpcode() != UO_Extension) |
19893 | break; |
19894 | ExprResult Sub = Rebuild(UO->getSubExpr()); |
19895 | if (!Sub.isUsable()) |
19896 | return Sub; |
19897 | return S.BuildUnaryOp(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension, |
19898 | Input: Sub.get()); |
19899 | } |
19900 | |
19901 | // [Clang extension] |
19902 | // -- If e has the form _Generic(...), the set of potential results is the |
19903 | // union of the sets of potential results of the associated expressions. |
19904 | case Expr::GenericSelectionExprClass: { |
19905 | auto *GSE = cast<GenericSelectionExpr>(Val: E); |
19906 | |
19907 | SmallVector<Expr *, 4> AssocExprs; |
19908 | bool AnyChanged = false; |
19909 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { |
19910 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); |
19911 | if (AssocExpr.isInvalid()) |
19912 | return ExprError(); |
19913 | if (AssocExpr.isUsable()) { |
19914 | AssocExprs.push_back(Elt: AssocExpr.get()); |
19915 | AnyChanged = true; |
19916 | } else { |
19917 | AssocExprs.push_back(Elt: OrigAssocExpr); |
19918 | } |
19919 | } |
19920 | |
19921 | void *ExOrTy = nullptr; |
19922 | bool IsExpr = GSE->isExprPredicate(); |
19923 | if (IsExpr) |
19924 | ExOrTy = GSE->getControllingExpr(); |
19925 | else |
19926 | ExOrTy = GSE->getControllingType(); |
19927 | return AnyChanged ? S.CreateGenericSelectionExpr( |
19928 | KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(), |
19929 | RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy, |
19930 | Types: GSE->getAssocTypeSourceInfos(), Exprs: AssocExprs) |
19931 | : ExprEmpty(); |
19932 | } |
19933 | |
19934 | // [Clang extension] |
19935 | // -- If e has the form __builtin_choose_expr(...), the set of potential |
19936 | // results is the union of the sets of potential results of the |
19937 | // second and third subexpressions. |
19938 | case Expr::ChooseExprClass: { |
19939 | auto *CE = cast<ChooseExpr>(Val: E); |
19940 | |
19941 | ExprResult LHS = Rebuild(CE->getLHS()); |
19942 | if (LHS.isInvalid()) |
19943 | return ExprError(); |
19944 | |
19945 | ExprResult RHS = Rebuild(CE->getLHS()); |
19946 | if (RHS.isInvalid()) |
19947 | return ExprError(); |
19948 | |
19949 | if (!LHS.get() && !RHS.get()) |
19950 | return ExprEmpty(); |
19951 | if (!LHS.isUsable()) |
19952 | LHS = CE->getLHS(); |
19953 | if (!RHS.isUsable()) |
19954 | RHS = CE->getRHS(); |
19955 | |
19956 | return S.ActOnChooseExpr(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(), |
19957 | RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc()); |
19958 | } |
19959 | |
19960 | // Step through non-syntactic nodes. |
19961 | case Expr::ConstantExprClass: { |
19962 | auto *CE = cast<ConstantExpr>(Val: E); |
19963 | ExprResult Sub = Rebuild(CE->getSubExpr()); |
19964 | if (!Sub.isUsable()) |
19965 | return Sub; |
19966 | return ConstantExpr::Create(Context: S.Context, E: Sub.get()); |
19967 | } |
19968 | |
19969 | // We could mostly rely on the recursive rebuilding to rebuild implicit |
19970 | // casts, but not at the top level, so rebuild them here. |
19971 | case Expr::ImplicitCastExprClass: { |
19972 | auto *ICE = cast<ImplicitCastExpr>(Val: E); |
19973 | // Only step through the narrow set of cast kinds we expect to encounter. |
19974 | // Anything else suggests we've left the region in which potential results |
19975 | // can be found. |
19976 | switch (ICE->getCastKind()) { |
19977 | case CK_NoOp: |
19978 | case CK_DerivedToBase: |
19979 | case CK_UncheckedDerivedToBase: { |
19980 | ExprResult Sub = Rebuild(ICE->getSubExpr()); |
19981 | if (!Sub.isUsable()) |
19982 | return Sub; |
19983 | CXXCastPath Path(ICE->path()); |
19984 | return S.ImpCastExprToType(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(), |
19985 | VK: ICE->getValueKind(), BasePath: &Path); |
19986 | } |
19987 | |
19988 | default: |
19989 | break; |
19990 | } |
19991 | break; |
19992 | } |
19993 | |
19994 | default: |
19995 | break; |
19996 | } |
19997 | |
19998 | // Can't traverse through this node. Nothing to do. |
19999 | return ExprEmpty(); |
20000 | } |
20001 | |
20002 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { |
20003 | // Check whether the operand is or contains an object of non-trivial C union |
20004 | // type. |
20005 | if (E->getType().isVolatileQualified() && |
20006 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || |
20007 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) |
20008 | checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(), |
20009 | UseContext: NonTrivialCUnionContext::LValueToRValueVolatile, |
20010 | NonTrivialKind: NTCUK_Destruct | NTCUK_Copy); |
20011 | |
20012 | // C++2a [basic.def.odr]p4: |
20013 | // [...] an expression of non-volatile-qualified non-class type to which |
20014 | // the lvalue-to-rvalue conversion is applied [...] |
20015 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) |
20016 | return E; |
20017 | |
20018 | ExprResult Result = |
20019 | rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant); |
20020 | if (Result.isInvalid()) |
20021 | return ExprError(); |
20022 | return Result.get() ? Result : E; |
20023 | } |
20024 | |
20025 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { |
20026 | Res = CorrectDelayedTyposInExpr(ER: Res); |
20027 | |
20028 | if (!Res.isUsable()) |
20029 | return Res; |
20030 | |
20031 | // If a constant-expression is a reference to a variable where we delay |
20032 | // deciding whether it is an odr-use, just assume we will apply the |
20033 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen |
20034 | // (a non-type template argument), we have special handling anyway. |
20035 | return CheckLValueToRValueConversionOperand(E: Res.get()); |
20036 | } |
20037 | |
20038 | void Sema::CleanupVarDeclMarking() { |
20039 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive |
20040 | // call. |
20041 | MaybeODRUseExprSet LocalMaybeODRUseExprs; |
20042 | std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs); |
20043 | |
20044 | for (Expr *E : LocalMaybeODRUseExprs) { |
20045 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) { |
20046 | MarkVarDeclODRUsed(cast<VarDecl>(Val: DRE->getDecl()), |
20047 | DRE->getLocation(), *this); |
20048 | } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) { |
20049 | MarkVarDeclODRUsed(cast<VarDecl>(Val: ME->getMemberDecl()), ME->getMemberLoc(), |
20050 | *this); |
20051 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: E)) { |
20052 | for (ValueDecl *VD : *FP) |
20053 | MarkVarDeclODRUsed(V: VD, Loc: FP->getParameterPackLocation(), SemaRef&: *this); |
20054 | } else { |
20055 | llvm_unreachable("Unexpected expression"); |
20056 | } |
20057 | } |
20058 | |
20059 | assert(MaybeODRUseExprs.empty() && |
20060 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); |
20061 | } |
20062 | |
20063 | static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, |
20064 | ValueDecl *Var, Expr *E) { |
20065 | VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); |
20066 | if (!VD) |
20067 | return; |
20068 | |
20069 | const bool RefersToEnclosingScope = |
20070 | (SemaRef.CurContext != VD->getDeclContext() && |
20071 | VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); |
20072 | if (RefersToEnclosingScope) { |
20073 | LambdaScopeInfo *const LSI = |
20074 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); |
20075 | if (LSI && (!LSI->CallOperator || |
20076 | !LSI->CallOperator->Encloses(DC: Var->getDeclContext()))) { |
20077 | // If a variable could potentially be odr-used, defer marking it so |
20078 | // until we finish analyzing the full expression for any |
20079 | // lvalue-to-rvalue |
20080 | // or discarded value conversions that would obviate odr-use. |
20081 | // Add it to the list of potential captures that will be analyzed |
20082 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking |
20083 | // unless the variable is a reference that was initialized by a constant |
20084 | // expression (this will never need to be captured or odr-used). |
20085 | // |
20086 | // FIXME: We can simplify this a lot after implementing P0588R1. |
20087 | assert(E && "Capture variable should be used in an expression."); |
20088 | if (!Var->getType()->isReferenceType() || |
20089 | !VD->isUsableInConstantExpressions(C: SemaRef.Context)) |
20090 | LSI->addPotentialCapture(VarExpr: E->IgnoreParens()); |
20091 | } |
20092 | } |
20093 | } |
20094 | |
20095 | static void DoMarkVarDeclReferenced( |
20096 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, |
20097 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
20098 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || |
20099 | isa<FunctionParmPackExpr>(E)) && |
20100 | "Invalid Expr argument to DoMarkVarDeclReferenced"); |
20101 | Var->setReferenced(); |
20102 | |
20103 | if (Var->isInvalidDecl()) |
20104 | return; |
20105 | |
20106 | auto *MSI = Var->getMemberSpecializationInfo(); |
20107 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() |
20108 | : Var->getTemplateSpecializationKind(); |
20109 | |
20110 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
20111 | bool UsableInConstantExpr = |
20112 | Var->mightBeUsableInConstantExpressions(C: SemaRef.Context); |
20113 | |
20114 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { |
20115 | RefsMinusAssignments.insert(KV: {Var, 0}).first->getSecond()++; |
20116 | } |
20117 | |
20118 | // C++20 [expr.const]p12: |
20119 | // A variable [...] is needed for constant evaluation if it is [...] a |
20120 | // variable whose name appears as a potentially constant evaluated |
20121 | // expression that is either a contexpr variable or is of non-volatile |
20122 | // const-qualified integral type or of reference type |
20123 | bool NeededForConstantEvaluation = |
20124 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; |
20125 | |
20126 | bool NeedDefinition = |
20127 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; |
20128 | |
20129 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && |
20130 | "Can't instantiate a partial template specialization."); |
20131 | |
20132 | // If this might be a member specialization of a static data member, check |
20133 | // the specialization is visible. We already did the checks for variable |
20134 | // template specializations when we created them. |
20135 | if (NeedDefinition && TSK != TSK_Undeclared && |
20136 | !isa<VarTemplateSpecializationDecl>(Val: Var)) |
20137 | SemaRef.checkSpecializationVisibility(Loc, Var); |
20138 | |
20139 | // Perform implicit instantiation of static data members, static data member |
20140 | // templates of class templates, and variable template specializations. Delay |
20141 | // instantiations of variable templates, except for those that could be used |
20142 | // in a constant expression. |
20143 | if (NeedDefinition && isTemplateInstantiation(Kind: TSK)) { |
20144 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit |
20145 | // instantiation declaration if a variable is usable in a constant |
20146 | // expression (among other cases). |
20147 | bool TryInstantiating = |
20148 | TSK == TSK_ImplicitInstantiation || |
20149 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); |
20150 | |
20151 | if (TryInstantiating) { |
20152 | SourceLocation PointOfInstantiation = |
20153 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); |
20154 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
20155 | if (FirstInstantiation) { |
20156 | PointOfInstantiation = Loc; |
20157 | if (MSI) |
20158 | MSI->setPointOfInstantiation(PointOfInstantiation); |
20159 | // FIXME: Notify listener. |
20160 | else |
20161 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
20162 | } |
20163 | |
20164 | if (UsableInConstantExpr || Var->getType()->isUndeducedType()) { |
20165 | // Do not defer instantiations of variables that could be used in a |
20166 | // constant expression. |
20167 | // The type deduction also needs a complete initializer. |
20168 | SemaRef.runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] { |
20169 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); |
20170 | }); |
20171 | |
20172 | // The size of an incomplete array type can be updated by |
20173 | // instantiating the initializer. The DeclRefExpr's type should be |
20174 | // updated accordingly too, or users of it would be confused! |
20175 | if (E) |
20176 | SemaRef.getCompletedType(E); |
20177 | |
20178 | // Re-set the member to trigger a recomputation of the dependence bits |
20179 | // for the expression. |
20180 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
20181 | DRE->setDecl(DRE->getDecl()); |
20182 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
20183 | ME->setMemberDecl(ME->getMemberDecl()); |
20184 | } else if (FirstInstantiation) { |
20185 | SemaRef.PendingInstantiations |
20186 | .push_back(std::make_pair(x&: Var, y&: PointOfInstantiation)); |
20187 | } else { |
20188 | bool Inserted = false; |
20189 | for (auto &I : SemaRef.SavedPendingInstantiations) { |
20190 | auto Iter = llvm::find_if( |
20191 | Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) { |
20192 | return P.first == Var; |
20193 | }); |
20194 | if (Iter != I.end()) { |
20195 | SemaRef.PendingInstantiations.push_back(x: *Iter); |
20196 | I.erase(position: Iter); |
20197 | Inserted = true; |
20198 | break; |
20199 | } |
20200 | } |
20201 | |
20202 | // FIXME: For a specialization of a variable template, we don't |
20203 | // distinguish between "declaration and type implicitly instantiated" |
20204 | // and "implicit instantiation of definition requested", so we have |
20205 | // no direct way to avoid enqueueing the pending instantiation |
20206 | // multiple times. |
20207 | if (isa<VarTemplateSpecializationDecl>(Val: Var) && !Inserted) |
20208 | SemaRef.PendingInstantiations |
20209 | .push_back(std::make_pair(x&: Var, y&: PointOfInstantiation)); |
20210 | } |
20211 | } |
20212 | } |
20213 | |
20214 | // C++2a [basic.def.odr]p4: |
20215 | // A variable x whose name appears as a potentially-evaluated expression e |
20216 | // is odr-used by e unless |
20217 | // -- x is a reference that is usable in constant expressions |
20218 | // -- x is a variable of non-reference type that is usable in constant |
20219 | // expressions and has no mutable subobjects [FIXME], and e is an |
20220 | // element of the set of potential results of an expression of |
20221 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
20222 | // conversion is applied |
20223 | // -- x is a variable of non-reference type, and e is an element of the set |
20224 | // of potential results of a discarded-value expression to which the |
20225 | // lvalue-to-rvalue conversion is not applied [FIXME] |
20226 | // |
20227 | // We check the first part of the second bullet here, and |
20228 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. |
20229 | // FIXME: To get the third bullet right, we need to delay this even for |
20230 | // variables that are not usable in constant expressions. |
20231 | |
20232 | // If we already know this isn't an odr-use, there's nothing more to do. |
20233 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E)) |
20234 | if (DRE->isNonOdrUse()) |
20235 | return; |
20236 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: E)) |
20237 | if (ME->isNonOdrUse()) |
20238 | return; |
20239 | |
20240 | switch (OdrUse) { |
20241 | case OdrUseContext::None: |
20242 | // In some cases, a variable may not have been marked unevaluated, if it |
20243 | // appears in a defaukt initializer. |
20244 | assert((!E || isa<FunctionParmPackExpr>(E) || |
20245 | SemaRef.isUnevaluatedContext()) && |
20246 | "missing non-odr-use marking for unevaluated decl ref"); |
20247 | break; |
20248 | |
20249 | case OdrUseContext::FormallyOdrUsed: |
20250 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture |
20251 | // behavior. |
20252 | break; |
20253 | |
20254 | case OdrUseContext::Used: |
20255 | // If we might later find that this expression isn't actually an odr-use, |
20256 | // delay the marking. |
20257 | if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context)) |
20258 | SemaRef.MaybeODRUseExprs.insert(X: E); |
20259 | else |
20260 | MarkVarDeclODRUsed(Var, Loc, SemaRef); |
20261 | break; |
20262 | |
20263 | case OdrUseContext::Dependent: |
20264 | // If this is a dependent context, we don't need to mark variables as |
20265 | // odr-used, but we may still need to track them for lambda capture. |
20266 | // FIXME: Do we also need to do this inside dependent typeid expressions |
20267 | // (which are modeled as unevaluated at this point)? |
20268 | DoMarkPotentialCapture(SemaRef, Loc, Var, E); |
20269 | break; |
20270 | } |
20271 | } |
20272 | |
20273 | static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, |
20274 | BindingDecl *BD, Expr *E) { |
20275 | BD->setReferenced(); |
20276 | |
20277 | if (BD->isInvalidDecl()) |
20278 | return; |
20279 | |
20280 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
20281 | if (OdrUse == OdrUseContext::Used) { |
20282 | QualType CaptureType, DeclRefType; |
20283 | SemaRef.tryCaptureVariable(BD, Loc, TryCaptureKind::Implicit, |
20284 | /*EllipsisLoc*/ SourceLocation(), |
20285 | /*BuildAndDiagnose*/ true, CaptureType, |
20286 | DeclRefType, |
20287 | /*FunctionScopeIndexToStopAt*/ nullptr); |
20288 | } else if (OdrUse == OdrUseContext::Dependent) { |
20289 | DoMarkPotentialCapture(SemaRef, Loc, BD, E); |
20290 | } |
20291 | } |
20292 | |
20293 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { |
20294 | DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: nullptr, RefsMinusAssignments); |
20295 | } |
20296 | |
20297 | // C++ [temp.dep.expr]p3: |
20298 | // An id-expression is type-dependent if it contains: |
20299 | // - an identifier associated by name lookup with an entity captured by copy |
20300 | // in a lambda-expression that has an explicit object parameter whose type |
20301 | // is dependent ([dcl.fct]), |
20302 | static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter( |
20303 | Sema &SemaRef, ValueDecl *D, Expr *E) { |
20304 | auto *ID = dyn_cast<DeclRefExpr>(Val: E); |
20305 | if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture()) |
20306 | return; |
20307 | |
20308 | // If any enclosing lambda with a dependent explicit object parameter either |
20309 | // explicitly captures the variable by value, or has a capture default of '=' |
20310 | // and does not capture the variable by reference, then the type of the DRE |
20311 | // is dependent on the type of that lambda's explicit object parameter. |
20312 | auto IsDependent = [&]() { |
20313 | for (auto *Scope : llvm::reverse(C&: SemaRef.FunctionScopes)) { |
20314 | auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope); |
20315 | if (!LSI) |
20316 | continue; |
20317 | |
20318 | if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) && |
20319 | LSI->AfterParameterList) |
20320 | return false; |
20321 | |
20322 | const auto *MD = LSI->CallOperator; |
20323 | if (MD->getType().isNull()) |
20324 | continue; |
20325 | |
20326 | const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
20327 | if (!Ty || !MD->isExplicitObjectMemberFunction() || |
20328 | !Ty->getParamType(0)->isDependentType()) |
20329 | continue; |
20330 | |
20331 | if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) { |
20332 | if (C->isCopyCapture()) |
20333 | return true; |
20334 | continue; |
20335 | } |
20336 | |
20337 | if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval) |
20338 | return true; |
20339 | } |
20340 | return false; |
20341 | }(); |
20342 | |
20343 | ID->setCapturedByCopyInLambdaWithExplicitObjectParameter( |
20344 | Set: IsDependent, Context: SemaRef.getASTContext()); |
20345 | } |
20346 | |
20347 | static void |
20348 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, |
20349 | bool MightBeOdrUse, |
20350 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
20351 | if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext()) |
20352 | SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D); |
20353 | |
20354 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) { |
20355 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); |
20356 | if (SemaRef.getLangOpts().CPlusPlus) |
20357 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
20358 | Var, E); |
20359 | return; |
20360 | } |
20361 | |
20362 | if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) { |
20363 | DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E); |
20364 | if (SemaRef.getLangOpts().CPlusPlus) |
20365 | FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, |
20366 | Decl, E); |
20367 | return; |
20368 | } |
20369 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); |
20370 | |
20371 | // If this is a call to a method via a cast, also mark the method in the |
20372 | // derived class used in case codegen can devirtualize the call. |
20373 | const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E); |
20374 | if (!ME) |
20375 | return; |
20376 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl()); |
20377 | if (!MD) |
20378 | return; |
20379 | // Only attempt to devirtualize if this is truly a virtual call. |
20380 | bool IsVirtualCall = MD->isVirtual() && |
20381 | ME->performsVirtualDispatch(LO: SemaRef.getLangOpts()); |
20382 | if (!IsVirtualCall) |
20383 | return; |
20384 | |
20385 | // If it's possible to devirtualize the call, mark the called function |
20386 | // referenced. |
20387 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( |
20388 | Base: ME->getBase(), IsAppleKext: SemaRef.getLangOpts().AppleKext); |
20389 | if (DM) |
20390 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); |
20391 | } |
20392 | |
20393 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { |
20394 | // [basic.def.odr] (CWG 1614) |
20395 | // A function is named by an expression or conversion [...] |
20396 | // unless it is a pure virtual function and either the expression is not an |
20397 | // id-expression naming the function with an explicitly qualified name or |
20398 | // the expression forms a pointer to member |
20399 | bool OdrUse = true; |
20400 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getDecl())) |
20401 | if (Method->isVirtual() && |
20402 | !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext)) |
20403 | OdrUse = false; |
20404 | |
20405 | if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) { |
20406 | if (!isUnevaluatedContext() && !isConstantEvaluatedContext() && |
20407 | !isImmediateFunctionContext() && |
20408 | !isCheckingDefaultArgumentOrInitializer() && |
20409 | FD->isImmediateFunction() && !RebuildingImmediateInvocation && |
20410 | !FD->isDependentContext()) |
20411 | ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E); |
20412 | } |
20413 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, |
20414 | RefsMinusAssignments); |
20415 | } |
20416 | |
20417 | void Sema::MarkMemberReferenced(MemberExpr *E) { |
20418 | // C++11 [basic.def.odr]p2: |
20419 | // A non-overloaded function whose name appears as a potentially-evaluated |
20420 | // expression or a member of a set of candidate functions, if selected by |
20421 | // overload resolution when referred to from a potentially-evaluated |
20422 | // expression, is odr-used, unless it is a pure virtual function and its |
20423 | // name is not explicitly qualified. |
20424 | bool MightBeOdrUse = true; |
20425 | if (E->performsVirtualDispatch(LO: getLangOpts())) { |
20426 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl())) |
20427 | if (Method->isPureVirtual()) |
20428 | MightBeOdrUse = false; |
20429 | } |
20430 | SourceLocation Loc = |
20431 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); |
20432 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, |
20433 | RefsMinusAssignments); |
20434 | } |
20435 | |
20436 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { |
20437 | for (ValueDecl *VD : *E) |
20438 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, |
20439 | RefsMinusAssignments); |
20440 | } |
20441 | |
20442 | /// Perform marking for a reference to an arbitrary declaration. It |
20443 | /// marks the declaration referenced, and performs odr-use checking for |
20444 | /// functions and variables. This method should not be used when building a |
20445 | /// normal expression which refers to a variable. |
20446 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, |
20447 | bool MightBeOdrUse) { |
20448 | if (MightBeOdrUse) { |
20449 | if (auto *VD = dyn_cast<VarDecl>(Val: D)) { |
20450 | MarkVariableReferenced(Loc, Var: VD); |
20451 | return; |
20452 | } |
20453 | } |
20454 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
20455 | MarkFunctionReferenced(Loc, Func: FD, MightBeOdrUse); |
20456 | return; |
20457 | } |
20458 | D->setReferenced(); |
20459 | } |
20460 | |
20461 | namespace { |
20462 | // Mark all of the declarations used by a type as referenced. |
20463 | // FIXME: Not fully implemented yet! We need to have a better understanding |
20464 | // of when we're entering a context we should not recurse into. |
20465 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to |
20466 | // TreeTransforms rebuilding the type in a new context. Rather than |
20467 | // duplicating the TreeTransform logic, we should consider reusing it here. |
20468 | // Currently that causes problems when rebuilding LambdaExprs. |
20469 | class MarkReferencedDecls : public DynamicRecursiveASTVisitor { |
20470 | Sema &S; |
20471 | SourceLocation Loc; |
20472 | |
20473 | public: |
20474 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {} |
20475 | |
20476 | bool TraverseTemplateArgument(const TemplateArgument &Arg) override; |
20477 | }; |
20478 | } |
20479 | |
20480 | bool MarkReferencedDecls::TraverseTemplateArgument( |
20481 | const TemplateArgument &Arg) { |
20482 | { |
20483 | // A non-type template argument is a constant-evaluated context. |
20484 | EnterExpressionEvaluationContext Evaluated( |
20485 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
20486 | if (Arg.getKind() == TemplateArgument::Declaration) { |
20487 | if (Decl *D = Arg.getAsDecl()) |
20488 | S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true); |
20489 | } else if (Arg.getKind() == TemplateArgument::Expression) { |
20490 | S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false); |
20491 | } |
20492 | } |
20493 | |
20494 | return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg); |
20495 | } |
20496 | |
20497 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { |
20498 | MarkReferencedDecls Marker(*this, Loc); |
20499 | Marker.TraverseType(T); |
20500 | } |
20501 | |
20502 | namespace { |
20503 | /// Helper class that marks all of the declarations referenced by |
20504 | /// potentially-evaluated subexpressions as "referenced". |
20505 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { |
20506 | public: |
20507 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; |
20508 | bool SkipLocalVariables; |
20509 | ArrayRef<const Expr *> StopAt; |
20510 | |
20511 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, |
20512 | ArrayRef<const Expr *> StopAt) |
20513 | : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} |
20514 | |
20515 | void visitUsedDecl(SourceLocation Loc, Decl *D) { |
20516 | S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D)); |
20517 | } |
20518 | |
20519 | void Visit(Expr *E) { |
20520 | if (llvm::is_contained(Range&: StopAt, Element: E)) |
20521 | return; |
20522 | Inherited::Visit(E); |
20523 | } |
20524 | |
20525 | void VisitConstantExpr(ConstantExpr *E) { |
20526 | // Don't mark declarations within a ConstantExpression, as this expression |
20527 | // will be evaluated and folded to a value. |
20528 | } |
20529 | |
20530 | void VisitDeclRefExpr(DeclRefExpr *E) { |
20531 | // If we were asked not to visit local variables, don't. |
20532 | if (SkipLocalVariables) { |
20533 | if (VarDecl *VD = dyn_cast<VarDecl>(Val: E->getDecl())) |
20534 | if (VD->hasLocalStorage()) |
20535 | return; |
20536 | } |
20537 | |
20538 | // FIXME: This can trigger the instantiation of the initializer of a |
20539 | // variable, which can cause the expression to become value-dependent |
20540 | // or error-dependent. Do we need to propagate the new dependence bits? |
20541 | S.MarkDeclRefReferenced(E); |
20542 | } |
20543 | |
20544 | void VisitMemberExpr(MemberExpr *E) { |
20545 | S.MarkMemberReferenced(E); |
20546 | Visit(E: E->getBase()); |
20547 | } |
20548 | }; |
20549 | } // namespace |
20550 | |
20551 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, |
20552 | bool SkipLocalVariables, |
20553 | ArrayRef<const Expr*> StopAt) { |
20554 | EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); |
20555 | } |
20556 | |
20557 | /// Emit a diagnostic when statements are reachable. |
20558 | /// FIXME: check for reachability even in expressions for which we don't build a |
20559 | /// CFG (eg, in the initializer of a global or in a constant expression). |
20560 | /// For example, |
20561 | /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } |
20562 | bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, |
20563 | const PartialDiagnostic &PD) { |
20564 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { |
20565 | if (!FunctionScopes.empty()) |
20566 | FunctionScopes.back()->PossiblyUnreachableDiags.push_back( |
20567 | Elt: sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); |
20568 | return true; |
20569 | } |
20570 | |
20571 | // The initializer of a constexpr variable or of the first declaration of a |
20572 | // static data member is not syntactically a constant evaluated constant, |
20573 | // but nonetheless is always required to be a constant expression, so we |
20574 | // can skip diagnosing. |
20575 | // FIXME: Using the mangling context here is a hack. |
20576 | if (auto *VD = dyn_cast_or_null<VarDecl>( |
20577 | Val: ExprEvalContexts.back().ManglingContextDecl)) { |
20578 | if (VD->isConstexpr() || |
20579 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) |
20580 | return false; |
20581 | // FIXME: For any other kind of variable, we should build a CFG for its |
20582 | // initializer and check whether the context in question is reachable. |
20583 | } |
20584 | |
20585 | Diag(Loc, PD); |
20586 | return true; |
20587 | } |
20588 | |
20589 | /// Emit a diagnostic that describes an effect on the run-time behavior |
20590 | /// of the program being compiled. |
20591 | /// |
20592 | /// This routine emits the given diagnostic when the code currently being |
20593 | /// type-checked is "potentially evaluated", meaning that there is a |
20594 | /// possibility that the code will actually be executable. Code in sizeof() |
20595 | /// expressions, code used only during overload resolution, etc., are not |
20596 | /// potentially evaluated. This routine will suppress such diagnostics or, |
20597 | /// in the absolutely nutty case of potentially potentially evaluated |
20598 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it |
20599 | /// later. |
20600 | /// |
20601 | /// This routine should be used for all diagnostics that describe the run-time |
20602 | /// behavior of a program, such as passing a non-POD value through an ellipsis. |
20603 | /// Failure to do so will likely result in spurious diagnostics or failures |
20604 | /// during overload resolution or within sizeof/alignof/typeof/typeid. |
20605 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, |
20606 | const PartialDiagnostic &PD) { |
20607 | |
20608 | if (ExprEvalContexts.back().isDiscardedStatementContext()) |
20609 | return false; |
20610 | |
20611 | switch (ExprEvalContexts.back().Context) { |
20612 | case ExpressionEvaluationContext::Unevaluated: |
20613 | case ExpressionEvaluationContext::UnevaluatedList: |
20614 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
20615 | case ExpressionEvaluationContext::DiscardedStatement: |
20616 | // The argument will never be evaluated, so don't complain. |
20617 | break; |
20618 | |
20619 | case ExpressionEvaluationContext::ConstantEvaluated: |
20620 | case ExpressionEvaluationContext::ImmediateFunctionContext: |
20621 | // Relevant diagnostics should be produced by constant evaluation. |
20622 | break; |
20623 | |
20624 | case ExpressionEvaluationContext::PotentiallyEvaluated: |
20625 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
20626 | return DiagIfReachable(Loc, Stmts, PD); |
20627 | } |
20628 | |
20629 | return false; |
20630 | } |
20631 | |
20632 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
20633 | const PartialDiagnostic &PD) { |
20634 | return DiagRuntimeBehavior( |
20635 | Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(), |
20636 | PD); |
20637 | } |
20638 | |
20639 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
20640 | CallExpr *CE, FunctionDecl *FD) { |
20641 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) |
20642 | return false; |
20643 | |
20644 | // If we're inside a decltype's expression, don't check for a valid return |
20645 | // type or construct temporaries until we know whether this is the last call. |
20646 | if (ExprEvalContexts.back().ExprContext == |
20647 | ExpressionEvaluationContextRecord::EK_Decltype) { |
20648 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: CE); |
20649 | return false; |
20650 | } |
20651 | |
20652 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { |
20653 | FunctionDecl *FD; |
20654 | CallExpr *CE; |
20655 | |
20656 | public: |
20657 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) |
20658 | : FD(FD), CE(CE) { } |
20659 | |
20660 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
20661 | if (!FD) { |
20662 | S.Diag(Loc, diag::err_call_incomplete_return) |
20663 | << T << CE->getSourceRange(); |
20664 | return; |
20665 | } |
20666 | |
20667 | S.Diag(Loc, diag::err_call_function_incomplete_return) |
20668 | << CE->getSourceRange() << FD << T; |
20669 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) |
20670 | << FD->getDeclName(); |
20671 | } |
20672 | } Diagnoser(FD, CE); |
20673 | |
20674 | if (RequireCompleteType(Loc, T: ReturnType, Diagnoser)) |
20675 | return true; |
20676 | |
20677 | return false; |
20678 | } |
20679 | |
20680 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses |
20681 | // will prevent this condition from triggering, which is what we want. |
20682 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { |
20683 | SourceLocation Loc; |
20684 | |
20685 | unsigned diagnostic = diag::warn_condition_is_assignment; |
20686 | bool IsOrAssign = false; |
20687 | |
20688 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: E)) { |
20689 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) |
20690 | return; |
20691 | |
20692 | IsOrAssign = Op->getOpcode() == BO_OrAssign; |
20693 | |
20694 | // Greylist some idioms by putting them into a warning subcategory. |
20695 | if (ObjCMessageExpr *ME |
20696 | = dyn_cast<ObjCMessageExpr>(Val: Op->getRHS()->IgnoreParenCasts())) { |
20697 | Selector Sel = ME->getSelector(); |
20698 | |
20699 | // self = [<foo> init...] |
20700 | if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) |
20701 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
20702 | |
20703 | // <foo> = [<bar> nextObject] |
20704 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") |
20705 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
20706 | } |
20707 | |
20708 | Loc = Op->getOperatorLoc(); |
20709 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
20710 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) |
20711 | return; |
20712 | |
20713 | IsOrAssign = Op->getOperator() == OO_PipeEqual; |
20714 | Loc = Op->getOperatorLoc(); |
20715 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) |
20716 | return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm()); |
20717 | else { |
20718 | // Not an assignment. |
20719 | return; |
20720 | } |
20721 | |
20722 | Diag(Loc, diagnostic) << E->getSourceRange(); |
20723 | |
20724 | SourceLocation Open = E->getBeginLoc(); |
20725 | SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd()); |
20726 | Diag(Loc, diag::note_condition_assign_silence) |
20727 | << FixItHint::CreateInsertion(Open, "(") |
20728 | << FixItHint::CreateInsertion(Close, ")"); |
20729 | |
20730 | if (IsOrAssign) |
20731 | Diag(Loc, diag::note_condition_or_assign_to_comparison) |
20732 | << FixItHint::CreateReplacement(Loc, "!="); |
20733 | else |
20734 | Diag(Loc, diag::note_condition_assign_to_comparison) |
20735 | << FixItHint::CreateReplacement(Loc, "=="); |
20736 | } |
20737 | |
20738 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { |
20739 | // Don't warn if the parens came from a macro. |
20740 | SourceLocation parenLoc = ParenE->getBeginLoc(); |
20741 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) |
20742 | return; |
20743 | // Don't warn for dependent expressions. |
20744 | if (ParenE->isTypeDependent()) |
20745 | return; |
20746 | |
20747 | Expr *E = ParenE->IgnoreParens(); |
20748 | if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E) |
20749 | return; |
20750 | |
20751 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(Val: E)) |
20752 | if (opE->getOpcode() == BO_EQ && |
20753 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: Context) |
20754 | == Expr::MLV_Valid) { |
20755 | SourceLocation Loc = opE->getOperatorLoc(); |
20756 | |
20757 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); |
20758 | SourceRange ParenERange = ParenE->getSourceRange(); |
20759 | Diag(Loc, diag::note_equality_comparison_silence) |
20760 | << FixItHint::CreateRemoval(ParenERange.getBegin()) |
20761 | << FixItHint::CreateRemoval(ParenERange.getEnd()); |
20762 | Diag(Loc, diag::note_equality_comparison_to_assign) |
20763 | << FixItHint::CreateReplacement(Loc, "="); |
20764 | } |
20765 | } |
20766 | |
20767 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, |
20768 | bool IsConstexpr) { |
20769 | DiagnoseAssignmentAsCondition(E); |
20770 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E)) |
20771 | DiagnoseEqualityWithExtraParens(ParenE: parenE); |
20772 | |
20773 | ExprResult result = CheckPlaceholderExpr(E); |
20774 | if (result.isInvalid()) return ExprError(); |
20775 | E = result.get(); |
20776 | |
20777 | if (!E->isTypeDependent()) { |
20778 | if (getLangOpts().CPlusPlus) |
20779 | return CheckCXXBooleanCondition(CondExpr: E, IsConstexpr); // C++ 6.4p4 |
20780 | |
20781 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); |
20782 | if (ERes.isInvalid()) |
20783 | return ExprError(); |
20784 | E = ERes.get(); |
20785 | |
20786 | QualType T = E->getType(); |
20787 | if (!T->isScalarType()) { // C99 6.8.4.1p1 |
20788 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) |
20789 | << T << E->getSourceRange(); |
20790 | return ExprError(); |
20791 | } |
20792 | CheckBoolLikeConversion(E, CC: Loc); |
20793 | } |
20794 | |
20795 | return E; |
20796 | } |
20797 | |
20798 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, |
20799 | Expr *SubExpr, ConditionKind CK, |
20800 | bool MissingOK) { |
20801 | // MissingOK indicates whether having no condition expression is valid |
20802 | // (for loop) or invalid (e.g. while loop). |
20803 | if (!SubExpr) |
20804 | return MissingOK ? ConditionResult() : ConditionError(); |
20805 | |
20806 | ExprResult Cond; |
20807 | switch (CK) { |
20808 | case ConditionKind::Boolean: |
20809 | Cond = CheckBooleanCondition(Loc, E: SubExpr); |
20810 | break; |
20811 | |
20812 | case ConditionKind::ConstexprIf: |
20813 | Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true); |
20814 | break; |
20815 | |
20816 | case ConditionKind::Switch: |
20817 | Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr); |
20818 | break; |
20819 | } |
20820 | if (Cond.isInvalid()) { |
20821 | Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(), |
20822 | SubExprs: {SubExpr}, T: PreferredConditionType(K: CK)); |
20823 | if (!Cond.get()) |
20824 | return ConditionError(); |
20825 | } |
20826 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. |
20827 | FullExprArg FullExpr = MakeFullExpr(Arg: Cond.get(), CC: Loc); |
20828 | if (!FullExpr.get()) |
20829 | return ConditionError(); |
20830 | |
20831 | return ConditionResult(*this, nullptr, FullExpr, |
20832 | CK == ConditionKind::ConstexprIf); |
20833 | } |
20834 | |
20835 | namespace { |
20836 | /// A visitor for rebuilding a call to an __unknown_any expression |
20837 | /// to have an appropriate type. |
20838 | struct RebuildUnknownAnyFunction |
20839 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { |
20840 | |
20841 | Sema &S; |
20842 | |
20843 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} |
20844 | |
20845 | ExprResult VisitStmt(Stmt *S) { |
20846 | llvm_unreachable("unexpected statement!"); |
20847 | } |
20848 | |
20849 | ExprResult VisitExpr(Expr *E) { |
20850 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) |
20851 | << E->getSourceRange(); |
20852 | return ExprError(); |
20853 | } |
20854 | |
20855 | /// Rebuild an expression which simply semantically wraps another |
20856 | /// expression which it shares the type and value kind of. |
20857 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
20858 | ExprResult SubResult = Visit(E->getSubExpr()); |
20859 | if (SubResult.isInvalid()) return ExprError(); |
20860 | |
20861 | Expr *SubExpr = SubResult.get(); |
20862 | E->setSubExpr(SubExpr); |
20863 | E->setType(SubExpr->getType()); |
20864 | E->setValueKind(SubExpr->getValueKind()); |
20865 | assert(E->getObjectKind() == OK_Ordinary); |
20866 | return E; |
20867 | } |
20868 | |
20869 | ExprResult VisitParenExpr(ParenExpr *E) { |
20870 | return rebuildSugarExpr(E); |
20871 | } |
20872 | |
20873 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
20874 | return rebuildSugarExpr(E); |
20875 | } |
20876 | |
20877 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
20878 | ExprResult SubResult = Visit(E->getSubExpr()); |
20879 | if (SubResult.isInvalid()) return ExprError(); |
20880 | |
20881 | Expr *SubExpr = SubResult.get(); |
20882 | E->setSubExpr(SubExpr); |
20883 | E->setType(S.Context.getPointerType(T: SubExpr->getType())); |
20884 | assert(E->isPRValue()); |
20885 | assert(E->getObjectKind() == OK_Ordinary); |
20886 | return E; |
20887 | } |
20888 | |
20889 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { |
20890 | if (!isa<FunctionDecl>(Val: VD)) return VisitExpr(E); |
20891 | |
20892 | E->setType(VD->getType()); |
20893 | |
20894 | assert(E->isPRValue()); |
20895 | if (S.getLangOpts().CPlusPlus && |
20896 | !(isa<CXXMethodDecl>(Val: VD) && |
20897 | cast<CXXMethodDecl>(Val: VD)->isInstance())) |
20898 | E->setValueKind(VK_LValue); |
20899 | |
20900 | return E; |
20901 | } |
20902 | |
20903 | ExprResult VisitMemberExpr(MemberExpr *E) { |
20904 | return resolveDecl(E, E->getMemberDecl()); |
20905 | } |
20906 | |
20907 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
20908 | return resolveDecl(E, E->getDecl()); |
20909 | } |
20910 | }; |
20911 | } |
20912 | |
20913 | /// Given a function expression of unknown-any type, try to rebuild it |
20914 | /// to have a function type. |
20915 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { |
20916 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); |
20917 | if (Result.isInvalid()) return ExprError(); |
20918 | return S.DefaultFunctionArrayConversion(E: Result.get()); |
20919 | } |
20920 | |
20921 | namespace { |
20922 | /// A visitor for rebuilding an expression of type __unknown_anytype |
20923 | /// into one which resolves the type directly on the referring |
20924 | /// expression. Strict preservation of the original source |
20925 | /// structure is not a goal. |
20926 | struct RebuildUnknownAnyExpr |
20927 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { |
20928 | |
20929 | Sema &S; |
20930 | |
20931 | /// The current destination type. |
20932 | QualType DestType; |
20933 | |
20934 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) |
20935 | : S(S), DestType(CastType) {} |
20936 | |
20937 | ExprResult VisitStmt(Stmt *S) { |
20938 | llvm_unreachable("unexpected statement!"); |
20939 | } |
20940 | |
20941 | ExprResult VisitExpr(Expr *E) { |
20942 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) |
20943 | << E->getSourceRange(); |
20944 | return ExprError(); |
20945 | } |
20946 | |
20947 | ExprResult VisitCallExpr(CallExpr *E); |
20948 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); |
20949 | |
20950 | /// Rebuild an expression which simply semantically wraps another |
20951 | /// expression which it shares the type and value kind of. |
20952 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
20953 | ExprResult SubResult = Visit(E->getSubExpr()); |
20954 | if (SubResult.isInvalid()) return ExprError(); |
20955 | Expr *SubExpr = SubResult.get(); |
20956 | E->setSubExpr(SubExpr); |
20957 | E->setType(SubExpr->getType()); |
20958 | E->setValueKind(SubExpr->getValueKind()); |
20959 | assert(E->getObjectKind() == OK_Ordinary); |
20960 | return E; |
20961 | } |
20962 | |
20963 | ExprResult VisitParenExpr(ParenExpr *E) { |
20964 | return rebuildSugarExpr(E); |
20965 | } |
20966 | |
20967 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
20968 | return rebuildSugarExpr(E); |
20969 | } |
20970 | |
20971 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
20972 | const PointerType *Ptr = DestType->getAs<PointerType>(); |
20973 | if (!Ptr) { |
20974 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) |
20975 | << E->getSourceRange(); |
20976 | return ExprError(); |
20977 | } |
20978 | |
20979 | if (isa<CallExpr>(Val: E->getSubExpr())) { |
20980 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) |
20981 | << E->getSourceRange(); |
20982 | return ExprError(); |
20983 | } |
20984 | |
20985 | assert(E->isPRValue()); |
20986 | assert(E->getObjectKind() == OK_Ordinary); |
20987 | E->setType(DestType); |
20988 | |
20989 | // Build the sub-expression as if it were an object of the pointee type. |
20990 | DestType = Ptr->getPointeeType(); |
20991 | ExprResult SubResult = Visit(E->getSubExpr()); |
20992 | if (SubResult.isInvalid()) return ExprError(); |
20993 | E->setSubExpr(SubResult.get()); |
20994 | return E; |
20995 | } |
20996 | |
20997 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); |
20998 | |
20999 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); |
21000 | |
21001 | ExprResult VisitMemberExpr(MemberExpr *E) { |
21002 | return resolveDecl(E, E->getMemberDecl()); |
21003 | } |
21004 | |
21005 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
21006 | return resolveDecl(E, E->getDecl()); |
21007 | } |
21008 | }; |
21009 | } |
21010 | |
21011 | /// Rebuilds a call expression which yielded __unknown_anytype. |
21012 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { |
21013 | Expr *CalleeExpr = E->getCallee(); |
21014 | |
21015 | enum FnKind { |
21016 | FK_MemberFunction, |
21017 | FK_FunctionPointer, |
21018 | FK_BlockPointer |
21019 | }; |
21020 | |
21021 | FnKind Kind; |
21022 | QualType CalleeType = CalleeExpr->getType(); |
21023 | if (CalleeType == S.Context.BoundMemberTy) { |
21024 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); |
21025 | Kind = FK_MemberFunction; |
21026 | CalleeType = Expr::findBoundMemberType(expr: CalleeExpr); |
21027 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { |
21028 | CalleeType = Ptr->getPointeeType(); |
21029 | Kind = FK_FunctionPointer; |
21030 | } else { |
21031 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); |
21032 | Kind = FK_BlockPointer; |
21033 | } |
21034 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); |
21035 | |
21036 | // Verify that this is a legal result type of a function. |
21037 | if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) || |
21038 | DestType->isFunctionType()) { |
21039 | unsigned diagID = diag::err_func_returning_array_function; |
21040 | if (Kind == FK_BlockPointer) |
21041 | diagID = diag::err_block_returning_array_function; |
21042 | |
21043 | S.Diag(E->getExprLoc(), diagID) |
21044 | << DestType->isFunctionType() << DestType; |
21045 | return ExprError(); |
21046 | } |
21047 | |
21048 | // Otherwise, go ahead and set DestType as the call's result. |
21049 | E->setType(DestType.getNonLValueExprType(S.Context)); |
21050 | E->setValueKind(Expr::getValueKindForType(DestType)); |
21051 | assert(E->getObjectKind() == OK_Ordinary); |
21052 | |
21053 | // Rebuild the function type, replacing the result type with DestType. |
21054 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FnType); |
21055 | if (Proto) { |
21056 | // __unknown_anytype(...) is a special case used by the debugger when |
21057 | // it has no idea what a function's signature is. |
21058 | // |
21059 | // We want to build this call essentially under the K&R |
21060 | // unprototyped rules, but making a FunctionNoProtoType in C++ |
21061 | // would foul up all sorts of assumptions. However, we cannot |
21062 | // simply pass all arguments as variadic arguments, nor can we |
21063 | // portably just call the function under a non-variadic type; see |
21064 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. |
21065 | // However, it turns out that in practice it is generally safe to |
21066 | // call a function declared as "A foo(B,C,D);" under the prototype |
21067 | // "A foo(B,C,D,...);". The only known exception is with the |
21068 | // Windows ABI, where any variadic function is implicitly cdecl |
21069 | // regardless of its normal CC. Therefore we change the parameter |
21070 | // types to match the types of the arguments. |
21071 | // |
21072 | // This is a hack, but it is far superior to moving the |
21073 | // corresponding target-specific code from IR-gen to Sema/AST. |
21074 | |
21075 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); |
21076 | SmallVector<QualType, 8> ArgTypes; |
21077 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case |
21078 | ArgTypes.reserve(N: E->getNumArgs()); |
21079 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { |
21080 | ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: i))); |
21081 | } |
21082 | ParamTypes = ArgTypes; |
21083 | } |
21084 | DestType = S.Context.getFunctionType(DestType, ParamTypes, |
21085 | Proto->getExtProtoInfo()); |
21086 | } else { |
21087 | DestType = S.Context.getFunctionNoProtoType(DestType, |
21088 | FnType->getExtInfo()); |
21089 | } |
21090 | |
21091 | // Rebuild the appropriate pointer-to-function type. |
21092 | switch (Kind) { |
21093 | case FK_MemberFunction: |
21094 | // Nothing to do. |
21095 | break; |
21096 | |
21097 | case FK_FunctionPointer: |
21098 | DestType = S.Context.getPointerType(DestType); |
21099 | break; |
21100 | |
21101 | case FK_BlockPointer: |
21102 | DestType = S.Context.getBlockPointerType(DestType); |
21103 | break; |
21104 | } |
21105 | |
21106 | // Finally, we can recurse. |
21107 | ExprResult CalleeResult = Visit(CalleeExpr); |
21108 | if (!CalleeResult.isUsable()) return ExprError(); |
21109 | E->setCallee(CalleeResult.get()); |
21110 | |
21111 | // Bind a temporary if necessary. |
21112 | return S.MaybeBindToTemporary(E); |
21113 | } |
21114 | |
21115 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { |
21116 | // Verify that this is a legal result type of a call. |
21117 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
21118 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) |
21119 | << DestType->isFunctionType() << DestType; |
21120 | return ExprError(); |
21121 | } |
21122 | |
21123 | // Rewrite the method result type if available. |
21124 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { |
21125 | assert(Method->getReturnType() == S.Context.UnknownAnyTy); |
21126 | Method->setReturnType(DestType); |
21127 | } |
21128 | |
21129 | // Change the type of the message. |
21130 | E->setType(DestType.getNonReferenceType()); |
21131 | E->setValueKind(Expr::getValueKindForType(DestType)); |
21132 | |
21133 | return S.MaybeBindToTemporary(E); |
21134 | } |
21135 | |
21136 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { |
21137 | // The only case we should ever see here is a function-to-pointer decay. |
21138 | if (E->getCastKind() == CK_FunctionToPointerDecay) { |
21139 | assert(E->isPRValue()); |
21140 | assert(E->getObjectKind() == OK_Ordinary); |
21141 | |
21142 | E->setType(DestType); |
21143 | |
21144 | // Rebuild the sub-expression as the pointee (function) type. |
21145 | DestType = DestType->castAs<PointerType>()->getPointeeType(); |
21146 | |
21147 | ExprResult Result = Visit(E->getSubExpr()); |
21148 | if (!Result.isUsable()) return ExprError(); |
21149 | |
21150 | E->setSubExpr(Result.get()); |
21151 | return E; |
21152 | } else if (E->getCastKind() == CK_LValueToRValue) { |
21153 | assert(E->isPRValue()); |
21154 | assert(E->getObjectKind() == OK_Ordinary); |
21155 | |
21156 | assert(isa<BlockPointerType>(E->getType())); |
21157 | |
21158 | E->setType(DestType); |
21159 | |
21160 | // The sub-expression has to be a lvalue reference, so rebuild it as such. |
21161 | DestType = S.Context.getLValueReferenceType(DestType); |
21162 | |
21163 | ExprResult Result = Visit(E->getSubExpr()); |
21164 | if (!Result.isUsable()) return ExprError(); |
21165 | |
21166 | E->setSubExpr(Result.get()); |
21167 | return E; |
21168 | } else { |
21169 | llvm_unreachable("Unhandled cast type!"); |
21170 | } |
21171 | } |
21172 | |
21173 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { |
21174 | ExprValueKind ValueKind = VK_LValue; |
21175 | QualType Type = DestType; |
21176 | |
21177 | // We know how to make this work for certain kinds of decls: |
21178 | |
21179 | // - functions |
21180 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: VD)) { |
21181 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { |
21182 | DestType = Ptr->getPointeeType(); |
21183 | ExprResult Result = resolveDecl(E, VD); |
21184 | if (Result.isInvalid()) return ExprError(); |
21185 | return S.ImpCastExprToType(E: Result.get(), Type, CK: CK_FunctionToPointerDecay, |
21186 | VK: VK_PRValue); |
21187 | } |
21188 | |
21189 | if (!Type->isFunctionType()) { |
21190 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) |
21191 | << VD << E->getSourceRange(); |
21192 | return ExprError(); |
21193 | } |
21194 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { |
21195 | // We must match the FunctionDecl's type to the hack introduced in |
21196 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown |
21197 | // type. See the lengthy commentary in that routine. |
21198 | QualType FDT = FD->getType(); |
21199 | const FunctionType *FnType = FDT->castAs<FunctionType>(); |
21200 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(Val: FnType); |
21201 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E); |
21202 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { |
21203 | SourceLocation Loc = FD->getLocation(); |
21204 | FunctionDecl *NewFD = FunctionDecl::Create( |
21205 | S.Context, FD->getDeclContext(), Loc, Loc, |
21206 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), |
21207 | SC_None, S.getCurFPFeatures().isFPConstrained(), |
21208 | false /*isInlineSpecified*/, FD->hasPrototype(), |
21209 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); |
21210 | |
21211 | if (FD->getQualifier()) |
21212 | NewFD->setQualifierInfo(FD->getQualifierLoc()); |
21213 | |
21214 | SmallVector<ParmVarDecl*, 16> Params; |
21215 | for (const auto &AI : FT->param_types()) { |
21216 | ParmVarDecl *Param = |
21217 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); |
21218 | Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size()); |
21219 | Params.push_back(Elt: Param); |
21220 | } |
21221 | NewFD->setParams(Params); |
21222 | DRE->setDecl(NewFD); |
21223 | VD = DRE->getDecl(); |
21224 | } |
21225 | } |
21226 | |
21227 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
21228 | if (MD->isInstance()) { |
21229 | ValueKind = VK_PRValue; |
21230 | Type = S.Context.BoundMemberTy; |
21231 | } |
21232 | |
21233 | // Function references aren't l-values in C. |
21234 | if (!S.getLangOpts().CPlusPlus) |
21235 | ValueKind = VK_PRValue; |
21236 | |
21237 | // - variables |
21238 | } else if (isa<VarDecl>(Val: VD)) { |
21239 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { |
21240 | Type = RefTy->getPointeeType(); |
21241 | } else if (Type->isFunctionType()) { |
21242 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) |
21243 | << VD << E->getSourceRange(); |
21244 | return ExprError(); |
21245 | } |
21246 | |
21247 | // - nothing else |
21248 | } else { |
21249 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) |
21250 | << VD << E->getSourceRange(); |
21251 | return ExprError(); |
21252 | } |
21253 | |
21254 | // Modifying the declaration like this is friendly to IR-gen but |
21255 | // also really dangerous. |
21256 | VD->setType(DestType); |
21257 | E->setType(Type); |
21258 | E->setValueKind(ValueKind); |
21259 | return E; |
21260 | } |
21261 | |
21262 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
21263 | Expr *CastExpr, CastKind &CastKind, |
21264 | ExprValueKind &VK, CXXCastPath &Path) { |
21265 | // The type we're casting to must be either void or complete. |
21266 | if (!CastType->isVoidType() && |
21267 | RequireCompleteType(TypeRange.getBegin(), CastType, |
21268 | diag::err_typecheck_cast_to_incomplete)) |
21269 | return ExprError(); |
21270 | |
21271 | // Rewrite the casted expression from scratch. |
21272 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); |
21273 | if (!result.isUsable()) return ExprError(); |
21274 | |
21275 | CastExpr = result.get(); |
21276 | VK = CastExpr->getValueKind(); |
21277 | CastKind = CK_NoOp; |
21278 | |
21279 | return CastExpr; |
21280 | } |
21281 | |
21282 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { |
21283 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); |
21284 | } |
21285 | |
21286 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, |
21287 | Expr *arg, QualType ¶mType) { |
21288 | // If the syntactic form of the argument is not an explicit cast of |
21289 | // any sort, just do default argument promotion. |
21290 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(Val: arg->IgnoreParens()); |
21291 | if (!castArg) { |
21292 | ExprResult result = DefaultArgumentPromotion(E: arg); |
21293 | if (result.isInvalid()) return ExprError(); |
21294 | paramType = result.get()->getType(); |
21295 | return result; |
21296 | } |
21297 | |
21298 | // Otherwise, use the type that was written in the explicit cast. |
21299 | assert(!arg->hasPlaceholderType()); |
21300 | paramType = castArg->getTypeAsWritten(); |
21301 | |
21302 | // Copy-initialize a parameter of that type. |
21303 | InitializedEntity entity = |
21304 | InitializedEntity::InitializeParameter(Context, Type: paramType, |
21305 | /*consumed*/ Consumed: false); |
21306 | return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg); |
21307 | } |
21308 | |
21309 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { |
21310 | Expr *orig = E; |
21311 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; |
21312 | while (true) { |
21313 | E = E->IgnoreParenImpCasts(); |
21314 | if (CallExpr *call = dyn_cast<CallExpr>(Val: E)) { |
21315 | E = call->getCallee(); |
21316 | diagID = diag::err_uncasted_call_of_unknown_any; |
21317 | } else { |
21318 | break; |
21319 | } |
21320 | } |
21321 | |
21322 | SourceLocation loc; |
21323 | NamedDecl *d; |
21324 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: E)) { |
21325 | loc = ref->getLocation(); |
21326 | d = ref->getDecl(); |
21327 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) { |
21328 | loc = mem->getMemberLoc(); |
21329 | d = mem->getMemberDecl(); |
21330 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: E)) { |
21331 | diagID = diag::err_uncasted_call_of_unknown_any; |
21332 | loc = msg->getSelectorStartLoc(); |
21333 | d = msg->getMethodDecl(); |
21334 | if (!d) { |
21335 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) |
21336 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() |
21337 | << orig->getSourceRange(); |
21338 | return ExprError(); |
21339 | } |
21340 | } else { |
21341 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) |
21342 | << E->getSourceRange(); |
21343 | return ExprError(); |
21344 | } |
21345 | |
21346 | S.Diag(loc, diagID) << d << orig->getSourceRange(); |
21347 | |
21348 | // Never recoverable. |
21349 | return ExprError(); |
21350 | } |
21351 | |
21352 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { |
21353 | if (!Context.isDependenceAllowed()) { |
21354 | // C cannot handle TypoExpr nodes on either side of a binop because it |
21355 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
21356 | // been dealt with before checking the operands. |
21357 | ExprResult Result = CorrectDelayedTyposInExpr(E); |
21358 | if (!Result.isUsable()) return ExprError(); |
21359 | E = Result.get(); |
21360 | } |
21361 | |
21362 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); |
21363 | if (!placeholderType) return E; |
21364 | |
21365 | switch (placeholderType->getKind()) { |
21366 | case BuiltinType::UnresolvedTemplate: { |
21367 | auto *ULE = cast<UnresolvedLookupExpr>(Val: E); |
21368 | const DeclarationNameInfo &NameInfo = ULE->getNameInfo(); |
21369 | // There's only one FoundDecl for UnresolvedTemplate type. See |
21370 | // BuildTemplateIdExpr. |
21371 | NamedDecl *Temp = *ULE->decls_begin(); |
21372 | const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Val: Temp); |
21373 | |
21374 | NestedNameSpecifier *NNS = ULE->getQualifierLoc().getNestedNameSpecifier(); |
21375 | // FIXME: AssumedTemplate is not very appropriate for error recovery here, |
21376 | // as it models only the unqualified-id case, where this case can clearly be |
21377 | // qualified. Thus we can't just qualify an assumed template. |
21378 | TemplateName TN; |
21379 | if (auto *TD = dyn_cast<TemplateDecl>(Temp)) |
21380 | TN = Context.getQualifiedTemplateName(NNS, TemplateKeyword: ULE->hasTemplateKeyword(), |
21381 | Template: TemplateName(TD)); |
21382 | else |
21383 | TN = Context.getAssumedTemplateName(Name: NameInfo.getName()); |
21384 | |
21385 | Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template) |
21386 | << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl; |
21387 | Diag(Temp->getLocation(), diag::note_referenced_type_template) |
21388 | << IsTypeAliasTemplateDecl; |
21389 | |
21390 | TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc()); |
21391 | bool HasAnyDependentTA = false; |
21392 | for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) { |
21393 | HasAnyDependentTA |= Arg.getArgument().isDependent(); |
21394 | TAL.addArgument(Arg); |
21395 | } |
21396 | |
21397 | QualType TST; |
21398 | { |
21399 | SFINAETrap Trap(*this); |
21400 | TST = CheckTemplateIdType(Template: TN, TemplateLoc: NameInfo.getBeginLoc(), TemplateArgs&: TAL); |
21401 | } |
21402 | if (TST.isNull()) |
21403 | TST = Context.getTemplateSpecializationType( |
21404 | TN, ULE->template_arguments(), /*CanonicalArgs=*/std::nullopt, |
21405 | HasAnyDependentTA ? Context.DependentTy : Context.IntTy); |
21406 | QualType ET = |
21407 | Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS, NamedType: TST); |
21408 | return CreateRecoveryExpr(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {}, |
21409 | T: ET); |
21410 | } |
21411 | |
21412 | // Overloaded expressions. |
21413 | case BuiltinType::Overload: { |
21414 | // Try to resolve a single function template specialization. |
21415 | // This is obligatory. |
21416 | ExprResult Result = E; |
21417 | if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false)) |
21418 | return Result; |
21419 | |
21420 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization |
21421 | // leaves Result unchanged on failure. |
21422 | Result = E; |
21423 | if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result)) |
21424 | return Result; |
21425 | |
21426 | // If that failed, try to recover with a call. |
21427 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), |
21428 | /*complain*/ true); |
21429 | return Result; |
21430 | } |
21431 | |
21432 | // Bound member functions. |
21433 | case BuiltinType::BoundMember: { |
21434 | ExprResult result = E; |
21435 | const Expr *BME = E->IgnoreParens(); |
21436 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); |
21437 | // Try to give a nicer diagnostic if it is a bound member that we recognize. |
21438 | if (isa<CXXPseudoDestructorExpr>(Val: BME)) { |
21439 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; |
21440 | } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) { |
21441 | if (ME->getMemberNameInfo().getName().getNameKind() == |
21442 | DeclarationName::CXXDestructorName) |
21443 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; |
21444 | } |
21445 | tryToRecoverWithCall(E&: result, PD, |
21446 | /*complain*/ ForceComplain: true); |
21447 | return result; |
21448 | } |
21449 | |
21450 | // ARC unbridged casts. |
21451 | case BuiltinType::ARCUnbridgedCast: { |
21452 | Expr *realCast = ObjC().stripARCUnbridgedCast(e: E); |
21453 | ObjC().diagnoseARCUnbridgedCast(e: realCast); |
21454 | return realCast; |
21455 | } |
21456 | |
21457 | // Expressions of unknown type. |
21458 | case BuiltinType::UnknownAny: |
21459 | return diagnoseUnknownAnyExpr(S&: *this, E); |
21460 | |
21461 | // Pseudo-objects. |
21462 | case BuiltinType::PseudoObject: |
21463 | return PseudoObject().checkRValue(E); |
21464 | |
21465 | case BuiltinType::BuiltinFn: { |
21466 | // Accept __noop without parens by implicitly converting it to a call expr. |
21467 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()); |
21468 | if (DRE) { |
21469 | auto *FD = cast<FunctionDecl>(Val: DRE->getDecl()); |
21470 | unsigned BuiltinID = FD->getBuiltinID(); |
21471 | if (BuiltinID == Builtin::BI__noop) { |
21472 | E = ImpCastExprToType(E, Type: Context.getPointerType(FD->getType()), |
21473 | CK: CK_BuiltinFnToFnPtr) |
21474 | .get(); |
21475 | return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy, |
21476 | VK: VK_PRValue, RParenLoc: SourceLocation(), |
21477 | FPFeatures: FPOptionsOverride()); |
21478 | } |
21479 | |
21480 | if (Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID)) { |
21481 | // Any use of these other than a direct call is ill-formed as of C++20, |
21482 | // because they are not addressable functions. In earlier language |
21483 | // modes, warn and force an instantiation of the real body. |
21484 | Diag(E->getBeginLoc(), |
21485 | getLangOpts().CPlusPlus20 |
21486 | ? diag::err_use_of_unaddressable_function |
21487 | : diag::warn_cxx20_compat_use_of_unaddressable_function); |
21488 | if (FD->isImplicitlyInstantiable()) { |
21489 | // Require a definition here because a normal attempt at |
21490 | // instantiation for a builtin will be ignored, and we won't try |
21491 | // again later. We assume that the definition of the template |
21492 | // precedes this use. |
21493 | InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD, |
21494 | /*Recursive=*/false, |
21495 | /*DefinitionRequired=*/true, |
21496 | /*AtEndOfTU=*/false); |
21497 | } |
21498 | // Produce a properly-typed reference to the function. |
21499 | CXXScopeSpec SS; |
21500 | SS.Adopt(Other: DRE->getQualifierLoc()); |
21501 | TemplateArgumentListInfo TemplateArgs; |
21502 | DRE->copyTemplateArgumentsInto(List&: TemplateArgs); |
21503 | return BuildDeclRefExpr( |
21504 | FD, FD->getType(), VK_LValue, DRE->getNameInfo(), |
21505 | DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), |
21506 | DRE->getTemplateKeywordLoc(), |
21507 | DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); |
21508 | } |
21509 | } |
21510 | |
21511 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); |
21512 | return ExprError(); |
21513 | } |
21514 | |
21515 | case BuiltinType::IncompleteMatrixIdx: |
21516 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) |
21517 | ->getRowIdx() |
21518 | ->getBeginLoc(), |
21519 | diag::err_matrix_incomplete_index); |
21520 | return ExprError(); |
21521 | |
21522 | // Expressions of unknown type. |
21523 | case BuiltinType::ArraySection: |
21524 | Diag(E->getBeginLoc(), diag::err_array_section_use) |
21525 | << cast<ArraySectionExpr>(E)->isOMPArraySection(); |
21526 | return ExprError(); |
21527 | |
21528 | // Expressions of unknown type. |
21529 | case BuiltinType::OMPArrayShaping: |
21530 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); |
21531 | |
21532 | case BuiltinType::OMPIterator: |
21533 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); |
21534 | |
21535 | // Everything else should be impossible. |
21536 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
21537 | case BuiltinType::Id: |
21538 | #include "clang/Basic/OpenCLImageTypes.def" |
21539 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
21540 | case BuiltinType::Id: |
21541 | #include "clang/Basic/OpenCLExtensionTypes.def" |
21542 | #define SVE_TYPE(Name, Id, SingletonId) \ |
21543 | case BuiltinType::Id: |
21544 | #include "clang/Basic/AArch64ACLETypes.def" |
21545 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
21546 | case BuiltinType::Id: |
21547 | #include "clang/Basic/PPCTypes.def" |
21548 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
21549 | #include "clang/Basic/RISCVVTypes.def" |
21550 | #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
21551 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
21552 | #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id: |
21553 | #include "clang/Basic/AMDGPUTypes.def" |
21554 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
21555 | #include "clang/Basic/HLSLIntangibleTypes.def" |
21556 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: |
21557 | #define PLACEHOLDER_TYPE(Id, SingletonId) |
21558 | #include "clang/AST/BuiltinTypes.def" |
21559 | break; |
21560 | } |
21561 | |
21562 | llvm_unreachable("invalid placeholder type!"); |
21563 | } |
21564 | |
21565 | bool Sema::CheckCaseExpression(Expr *E) { |
21566 | if (E->isTypeDependent()) |
21567 | return true; |
21568 | if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context)) |
21569 | return E->getType()->isIntegralOrEnumerationType(); |
21570 | return false; |
21571 | } |
21572 | |
21573 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, |
21574 | ArrayRef<Expr *> SubExprs, QualType T) { |
21575 | if (!Context.getLangOpts().RecoveryAST) |
21576 | return ExprError(); |
21577 | |
21578 | if (isSFINAEContext()) |
21579 | return ExprError(); |
21580 | |
21581 | if (T.isNull() || T->isUndeducedType() || |
21582 | !Context.getLangOpts().RecoveryASTType) |
21583 | // We don't know the concrete type, fallback to dependent type. |
21584 | T = Context.DependentTy; |
21585 | |
21586 | return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs); |
21587 | } |
21588 |
Definitions
- CanUseDecl
- DiagnoseUnusedOfDecl
- NoteDeletedFunction
- hasAnyExplicitStorageClass
- diagnoseUseOfInternalDeclInInlineFunction
- MaybeSuggestAddingStaticToDecl
- DiagnoseUseOfDecl
- DiagnoseSentinelCalls
- getExprRange
- DefaultFunctionArrayConversion
- CheckForNullPointerDereference
- DiagnoseDirectIsaAccess
- DefaultLvalueConversion
- DefaultFunctionArrayLvalueConversion
- CallExprUnaryConversions
- UsualUnaryFPConversions
- UsualUnaryConversions
- DefaultArgumentPromotion
- isValidVarArgType
- checkVariadicArgument
- DefaultVariadicArgumentPromotion
- handleComplexIntegerToFloatConversion
- handleComplexFloatConversion
- handleComplexConversion
- handleIntToFloatConversion
- handleFloatConversion
- unsupportedTypeConversion
- doIntegralCast
- doComplexIntegralCast
- handleIntegerConversion
- handleComplexIntConversion
- GetFixedPointRank
- handleFixedPointConversion
- checkEnumArithmeticConversions
- CheckUnicodeArithmeticConversions
- UsualArithmeticConversions
- ActOnGenericSelectionExpr
- CreateGenericSelectionExpr
- getPredefinedExprKind
- getPredefinedExprDecl
- getUDSuffixLoc
- BuildCookedLiteralOperatorCall
- ActOnUnevaluatedStringLiteral
- ExpandFunctionLocalPredefinedMacros
- ActOnStringLiteral
- BuildDeclRefExpr
- BuildDeclRefExpr
- isCapturingReferenceToHostVarInCUDADeviceLambda
- getNonOdrUseReasonInCurrentContext
- BuildDeclRefExpr
- DecomposeUnqualifiedId
- emitEmptyLookupTypoDiagnostic
- DiagnoseDependentMemberLookup
- DiagnoseEmptyLookup
- recoverFromMSUnqualifiedLookup
- ActOnIdExpression
- BuildQualifiedDeclarationNameExpr
- PerformObjectMemberConversion
- UseArgumentDependentLookup
- CheckDeclInExpr
- ShouldLookupResultBeMultiVersionOverload
- BuildDeclarationNameExpr
- BuildDeclarationNameExpr
- ConvertUTF8ToWideString
- BuildPredefinedExpr
- ActOnPredefinedExpr
- ActOnCharacterConstant
- ActOnIntegerConstant
- BuildFloatingLiteral
- CheckLoopHintExpr
- ActOnNumericConstant
- ActOnParenExpr
- CheckVecStepTraitOperandType
- CheckVectorElementsTraitOperandType
- checkPtrAuthTypeDiscriminatorOperandType
- CheckExtensionTraitOperandType
- CheckObjCTraitOperandConstraints
- warnOnSizeofOnArrayDecay
- CheckUnaryExprOrTypeTraitOperand
- CheckAlignOfExpr
- CheckVecStepExpr
- captureVariablyModifiedType
- CheckUnaryExprOrTypeTraitOperand
- CreateUnaryExprOrTypeTraitExpr
- CreateUnaryExprOrTypeTraitExpr
- ActOnUnaryExprOrTypeTraitExpr
- CheckAlignasTypeArgument
- ActOnAlignasTypeArgument
- CheckRealImagOperand
- ActOnPostfixUnaryOp
- checkArithmeticOnObjCPointer
- isMSPropertySubscriptExpr
- getDependentArraySubscriptType
- ActOnArraySubscriptExpr
- tryConvertExprToType
- CreateBuiltinMatrixSubscriptExpr
- CheckAddressOfNoDeref
- CheckSubscriptAccessOfNoDeref
- CreateBuiltinArraySubscriptExpr
- CheckCXXDefaultArgExpr
- ImmediateCallVisitor
- ImmediateCallVisitor
- VisitCallExpr
- VisitCXXConstructExpr
- VisitSourceLocExpr
- VisitLambdaExpr
- VisitCXXDefaultArgExpr
- VisitCXXDefaultInitExpr
- EnsureImmediateInvocationInDefaultArgs
- EnsureImmediateInvocationInDefaultArgs
- AlwaysRebuild
- TransformLambdaExpr
- TransformBlockExpr
- TransformCXXThisExpr
- TransformSourceLocExpr
- BuildCXXDefaultArgExpr
- FindFieldDeclInstantiationPattern
- BuildCXXDefaultInitExpr
- getVariadicCallType
- FunctionCallCCC
- FunctionCallCCC
- ValidateCandidate
- clone
- TryTypoCorrectionForCall
- isParenthetizedAndQualifiedAddressOfExpr
- ConvertArgumentsForCall
- GatherArgumentsForCall
- DiagnoseCalleeStaticArrayParam
- CheckStaticArrayArgument
- isPlaceholderToRemoveAsArg
- CheckArgsForPlaceholders
- rewriteBuiltinFunctionDecl
- checkDirectCallValidity
- enclosingClassIsRelatedToClassInWhichMembersWereFound
- tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs
- DiagnosedUnqualifiedCallsToStdFunctions
- ActOnCallExpr
- MayBeFunctionType
- BuildCallExpr
- BuildBuiltinCallExpr
- ActOnAsTypeExpr
- BuildAsTypeExpr
- ActOnConvertVectorExpr
- BuildResolvedCallExpr
- ActOnCompoundLiteral
- BuildCompoundLiteralExpr
- ActOnInitList
- BuildInitList
- maybeExtendBlockObject
- PrepareScalarCast
- breakDownVectorType
- isValidSveBitcast
- areMatrixTypesOfTheSameDimension
- areVectorTypesSameSize
- anyAltivecTypes
- areLaxCompatibleVectorTypes
- isLaxVectorConversion
- CheckMatrixCast
- CheckVectorCast
- prepareVectorSplat
- CheckExtVectorCast
- ActOnCastExpr
- BuildVectorLiteral
- MaybeConvertParenListExprToParenExpr
- ActOnParenListExpr
- ActOnCXXParenListInitExpr
- DiagnoseConditionalForNull
- checkCondition
- checkConditionalNullPointer
- checkConditionalPointerCompatibility
- checkConditionalBlockPointerCompatibility
- checkConditionalObjectPointersCompatibility
- checkPointerIntegerMismatch
- OpenCLArithmeticConversions
- OpenCLConvertScalarsToVectors
- checkOpenCLConditionVector
- checkVectorResult
- OpenCLCheckVectorConditional
- checkBlockType
- CheckConditionalOperands
- SuggestParentheses
- IsArithmeticOp
- IsArithmeticBinaryExpr
- ExprLooksBoolean
- DiagnoseConditionalPrecedence
- computeConditionalNullability
- ActOnConditionalOp
- IsInvalidSMECallConversion
- IsInvalidCmseNSCallConversion
- checkPointerTypesForAssignment
- checkBlockPointerTypesForAssignment
- checkObjCPointerTypesForAssignment
- CheckAssignmentConstraints
- isVector
- CheckAssignmentConstraints
- ConstructTransparentUnion
- CheckTransparentUnionArgumentConstraints
- CheckSingleAssignmentConstraints
- OriginalOperand
- OriginalOperand
- getType
- InvalidOperands
- InvalidLogicalVectorOperands
- tryVectorConvertAndSplat
- convertVector
- canConvertIntToOtherIntTy
- canConvertIntTyToFloatTy
- tryGCCVectorConvertAndSplat
- CheckVectorOperands
- CheckSizelessVectorOperands
- checkArithmeticNull
- DetectPrecisionLossInComplexDivision
- DiagnoseDivisionSizeofPointerOrArray
- DiagnoseBadDivideOrRemainderValues
- CheckMultiplyDivideOperands
- CheckRemainderOperands
- diagnoseArithmeticOnTwoVoidPointers
- diagnoseArithmeticOnVoidPointer
- diagnoseArithmeticOnNullPointer
- diagnoseSubtractionOnNullPointer
- diagnoseArithmeticOnTwoFunctionPointers
- diagnoseArithmeticOnFunctionPointer
- checkArithmeticIncompletePointerType
- checkArithmeticOpPointerOperand
- checkArithmeticBinOpPointerOperands
- diagnoseStringPlusInt
- diagnoseStringPlusChar
- diagnosePointerIncompatibility
- CheckAdditionOperands
- CheckSubtractionOperands
- isScopedEnumerationType
- DiagnoseBadShiftValues
- checkVectorShift
- checkSizelessVectorShift
- CheckShiftOperands
- diagnoseDistinctPointerComparison
- convertPointersToCompositeType
- diagnoseFunctionPointerToVoidComparison
- isObjCObjectLiteral
- hasIsEqualMethod
- diagnoseObjCLiteralComparison
- diagnoseLogicalNotOnLHSofCheck
- checkForArray
- isTautologicalBoundsCheck
- diagnoseTautologicalComparison
- castKindToImplicitConversionKind
- checkThreeWayNarrowingConversion
- checkArithmeticOrEnumeralThreeWayCompare
- checkArithmeticOrEnumeralCompare
- CheckPtrComparisonWithNullChar
- CheckCompareOperands
- GetSignedVectorType
- GetSignedSizelessVectorType
- CheckVectorCompareOperands
- CheckSizelessVectorCompareOperands
- diagnoseXorMisusedAsPow
- CheckVectorLogicalOperands
- CheckMatrixElementwiseOperands
- CheckMatrixMultiplyOperands
- isLegalBoolVectorBinaryOp
- CheckBitwiseOperands
- CheckLogicalOperands
- IsReadonlyMessage
- NonConstCaptureKind
- isReferenceToNonConstCapture
- IsTypeModifiable
- DiagnoseConstAssignment
- OriginalExprKind
- DiagnoseRecursiveConstFields
- DiagnoseRecursiveConstFields
- CheckForModifiableLvalue
- CheckIdentityFieldAssignment
- CheckAssignmentOperands
- IgnoreCommaOperand
- DiagnoseCommaOperator
- CheckCommaOperands
- CheckIncrementDecrementOperand
- getPrimaryDecl
- diagnoseAddressOfInvalidType
- CheckUseOfCXXMethodAsAddressOfOperand
- CheckAddressOfOperand
- RecordModifiableNonNullParam
- CheckIndirectionOperand
- ConvertTokenKindToBinaryOpcode
- ConvertTokenKindToUnaryOpcode
- getSelfAssignmentClassMemberCandidate
- DiagnoseSelfAssignment
- checkObjCPointerIntrospection
- getDeclFromExpr
- convertHalfVecBinOp
- CorrectDelayedTyposInBinOp
- needsConversionOfHalfVec
- CreateBuiltinBinOp
- DiagnoseBitwisePrecedence
- EmitDiagnosticForLogicalAndInLogicalOr
- DiagnoseLogicalAndInLogicalOrLHS
- DiagnoseLogicalAndInLogicalOrRHS
- DiagnoseBitwiseOpInBitwiseOp
- DiagnoseAdditionInShift
- DiagnoseShiftCompare
- DiagnoseBinOpPrecedence
- ActOnBinOp
- LookupBinOp
- BuildOverloadedBinOp
- BuildBinOp
- isOverflowingIntegerType
- CreateBuiltinUnaryOp
- isQualifiedMemberAccess
- BuildUnaryOp
- ActOnUnaryOp
- ActOnAddrLabel
- ActOnStartStmtExpr
- ActOnStmtExprError
- ActOnStmtExpr
- BuildStmtExpr
- ActOnStmtExprResult
- BuildBuiltinOffsetOf
- ActOnBuiltinOffsetOf
- ActOnChooseExpr
- ActOnBlockStart
- ActOnBlockArguments
- ActOnBlockError
- ActOnBlockStmtExpr
- ActOnVAArg
- BuildVAArgExpr
- ActOnGNUNullExpr
- LookupStdSourceLocationImpl
- ActOnSourceLocExpr
- BuildSourceLocExpr
- ActOnEmbedExpr
- maybeDiagnoseAssignmentToFunction
- DiagnoseAssignmentResult
- VerifyIntegerConstantExpression
- VerifyIntegerConstantExpression
- diagnoseNotICEType
- diagnoseFold
- VerifyIntegerConstantExpression
- TransformToPE
- TransformToPE
- AlwaysRebuild
- ReplacingOriginal
- TransformDeclRefExpr
- TransformUnaryOperator
- TransformLambdaBody
- TransformToPotentiallyEvaluated
- TransformToPotentiallyEvaluated
- PushExpressionEvaluationContext
- PushExpressionEvaluationContext
- PushExpressionEvaluationContextForFunction
- CheckPossibleDeref
- WarnOnPendingNoDerefs
- CheckUnusedVolatileAssignment
- MarkExpressionAsImmediateEscalating
- CheckForImmediateInvocation
- EvaluateAndDiagnoseImmediateInvocation
- RemoveNestedImmediateInvocation
- HandleImmediateInvocations
- PopExpressionEvaluationContext
- DiscardCleanupsInEvaluationContext
- HandleExprEvaluationContextForTypeof
- isPotentiallyConstantEvaluatedContext
- funcHasParameterSizeMangling
- CheckCompleteParameterTypesForMangler
- OdrUseContext
- isOdrUseContext
- isImplicitlyDefinableConstexprFunction
- MarkFunctionReferenced
- MarkVarDeclODRUsed
- MarkCaptureUsedInEnclosingContext
- diagnoseUncapturableValueReferenceOrBinding
- isVariableAlreadyCapturedInScopeInfo
- getParentOfCapturingContextOrNull
- isVariableCapturable
- captureInBlock
- captureInCapturedRegion
- captureInLambda
- canCaptureVariableByCopy
- buildLambdaCaptureFixit
- tryCaptureVariable
- tryCaptureVariable
- NeedToCaptureVariable
- getCapturedDeclRefType
- CopiedTemplateArgs
- CopiedTemplateArgs
- operator TemplateArgumentListInfo*
- rebuildPotentialResultsAsNonOdrUsed
- CheckLValueToRValueConversionOperand
- ActOnConstantExpression
- CleanupVarDeclMarking
- DoMarkPotentialCapture
- DoMarkVarDeclReferenced
- DoMarkBindingDeclReferenced
- MarkVariableReferenced
- FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter
- MarkExprReferenced
- MarkDeclRefReferenced
- MarkMemberReferenced
- MarkFunctionParmPackReferenced
- MarkAnyDeclReferenced
- MarkReferencedDecls
- MarkReferencedDecls
- TraverseTemplateArgument
- MarkDeclarationsReferencedInType
- EvaluatedExprMarker
- EvaluatedExprMarker
- visitUsedDecl
- Visit
- VisitConstantExpr
- VisitDeclRefExpr
- VisitMemberExpr
- MarkDeclarationsReferencedInExpr
- DiagIfReachable
- DiagRuntimeBehavior
- DiagRuntimeBehavior
- CheckCallReturnType
- DiagnoseAssignmentAsCondition
- DiagnoseEqualityWithExtraParens
- CheckBooleanCondition
- ActOnCondition
- RebuildUnknownAnyFunction
- RebuildUnknownAnyFunction
- VisitStmt
- VisitExpr
- rebuildSugarExpr
- VisitParenExpr
- VisitUnaryExtension
- VisitUnaryAddrOf
- resolveDecl
- VisitMemberExpr
- VisitDeclRefExpr
- rebuildUnknownAnyFunction
- RebuildUnknownAnyExpr
- RebuildUnknownAnyExpr
- VisitStmt
- VisitExpr
- rebuildSugarExpr
- VisitParenExpr
- VisitUnaryExtension
- VisitUnaryAddrOf
- VisitMemberExpr
- VisitDeclRefExpr
- VisitCallExpr
- VisitObjCMessageExpr
- VisitImplicitCastExpr
- resolveDecl
- checkUnknownAnyCast
- forceUnknownAnyToType
- checkUnknownAnyArg
- diagnoseUnknownAnyExpr
- CheckPlaceholderExpr
- CheckCaseExpression
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more