File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 6860, column 12 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements semantic analysis for expressions. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "TreeTransform.h" | ||||
14 | #include "UsedDeclVisitor.h" | ||||
15 | #include "clang/AST/ASTConsumer.h" | ||||
16 | #include "clang/AST/ASTContext.h" | ||||
17 | #include "clang/AST/ASTLambda.h" | ||||
18 | #include "clang/AST/ASTMutationListener.h" | ||||
19 | #include "clang/AST/CXXInheritance.h" | ||||
20 | #include "clang/AST/DeclObjC.h" | ||||
21 | #include "clang/AST/DeclTemplate.h" | ||||
22 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||
23 | #include "clang/AST/Expr.h" | ||||
24 | #include "clang/AST/ExprCXX.h" | ||||
25 | #include "clang/AST/ExprObjC.h" | ||||
26 | #include "clang/AST/ExprOpenMP.h" | ||||
27 | #include "clang/AST/OperationKinds.h" | ||||
28 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
29 | #include "clang/AST/TypeLoc.h" | ||||
30 | #include "clang/Basic/Builtins.h" | ||||
31 | #include "clang/Basic/PartialDiagnostic.h" | ||||
32 | #include "clang/Basic/SourceManager.h" | ||||
33 | #include "clang/Basic/TargetInfo.h" | ||||
34 | #include "clang/Lex/LiteralSupport.h" | ||||
35 | #include "clang/Lex/Preprocessor.h" | ||||
36 | #include "clang/Sema/AnalysisBasedWarnings.h" | ||||
37 | #include "clang/Sema/DeclSpec.h" | ||||
38 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
39 | #include "clang/Sema/Designator.h" | ||||
40 | #include "clang/Sema/Initialization.h" | ||||
41 | #include "clang/Sema/Lookup.h" | ||||
42 | #include "clang/Sema/Overload.h" | ||||
43 | #include "clang/Sema/ParsedTemplate.h" | ||||
44 | #include "clang/Sema/Scope.h" | ||||
45 | #include "clang/Sema/ScopeInfo.h" | ||||
46 | #include "clang/Sema/SemaFixItUtils.h" | ||||
47 | #include "clang/Sema/SemaInternal.h" | ||||
48 | #include "clang/Sema/Template.h" | ||||
49 | #include "llvm/ADT/STLExtras.h" | ||||
50 | #include "llvm/ADT/StringExtras.h" | ||||
51 | #include "llvm/Support/ConvertUTF.h" | ||||
52 | #include "llvm/Support/SaveAndRestore.h" | ||||
53 | |||||
54 | using namespace clang; | ||||
55 | using namespace sema; | ||||
56 | using llvm::RoundingMode; | ||||
57 | |||||
58 | /// Determine whether the use of this declaration is valid, without | ||||
59 | /// emitting diagnostics. | ||||
60 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||
61 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
62 | if (ParsingInitForAutoVars.count(D)) | ||||
63 | return false; | ||||
64 | |||||
65 | // See if this is a deleted function. | ||||
66 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
67 | if (FD->isDeleted()) | ||||
68 | return false; | ||||
69 | |||||
70 | // If the function has a deduced return type, and we can't deduce it, | ||||
71 | // then we can't use it either. | ||||
72 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
73 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||
74 | return false; | ||||
75 | |||||
76 | // See if this is an aligned allocation/deallocation function that is | ||||
77 | // unavailable. | ||||
78 | if (TreatUnavailableAsInvalid && | ||||
79 | isUnavailableAlignedAllocationFunction(*FD)) | ||||
80 | return false; | ||||
81 | } | ||||
82 | |||||
83 | // See if this function is unavailable. | ||||
84 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||
85 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||
86 | return false; | ||||
87 | |||||
88 | if (isa<UnresolvedUsingIfExistsDecl>(D)) | ||||
89 | return false; | ||||
90 | |||||
91 | return true; | ||||
92 | } | ||||
93 | |||||
94 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||
95 | // Warn if this is used but marked unused. | ||||
96 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||
97 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||
98 | // should diagnose them. | ||||
99 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||
100 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||
101 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||
102 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||
103 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||
104 | } | ||||
105 | } | ||||
106 | } | ||||
107 | |||||
108 | /// Emit a note explaining that this function is deleted. | ||||
109 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||
110 | assert(Decl && Decl->isDeleted())(static_cast <bool> (Decl && Decl->isDeleted ()) ? void (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 110, __extension__ __PRETTY_FUNCTION__)); | ||||
111 | |||||
112 | if (Decl->isDefaulted()) { | ||||
113 | // If the method was explicitly defaulted, point at that declaration. | ||||
114 | if (!Decl->isImplicit()) | ||||
115 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||
116 | |||||
117 | // Try to diagnose why this special member function was implicitly | ||||
118 | // deleted. This might fail, if that reason no longer applies. | ||||
119 | DiagnoseDeletedDefaultedFunction(Decl); | ||||
120 | return; | ||||
121 | } | ||||
122 | |||||
123 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||
124 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
125 | return NoteDeletedInheritingConstructor(Ctor); | ||||
126 | |||||
127 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||
128 | << Decl << 1; | ||||
129 | } | ||||
130 | |||||
131 | /// Determine whether a FunctionDecl was ever declared with an | ||||
132 | /// explicit storage class. | ||||
133 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||
134 | for (auto I : D->redecls()) { | ||||
135 | if (I->getStorageClass() != SC_None) | ||||
136 | return true; | ||||
137 | } | ||||
138 | return false; | ||||
139 | } | ||||
140 | |||||
141 | /// Check whether we're in an extern inline function and referring to a | ||||
142 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||
143 | /// | ||||
144 | /// This is only a warning because we used to silently accept this code, but | ||||
145 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||
146 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||
147 | /// and so while there may still be user mistakes, most of the time we can't | ||||
148 | /// prove that there are errors. | ||||
149 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||
150 | const NamedDecl *D, | ||||
151 | SourceLocation Loc) { | ||||
152 | // This is disabled under C++; there are too many ways for this to fire in | ||||
153 | // contexts where the warning is a false positive, or where it is technically | ||||
154 | // correct but benign. | ||||
155 | if (S.getLangOpts().CPlusPlus) | ||||
156 | return; | ||||
157 | |||||
158 | // Check if this is an inlined function or method. | ||||
159 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||
160 | if (!Current) | ||||
161 | return; | ||||
162 | if (!Current->isInlined()) | ||||
163 | return; | ||||
164 | if (!Current->isExternallyVisible()) | ||||
165 | return; | ||||
166 | |||||
167 | // Check if the decl has internal linkage. | ||||
168 | if (D->getFormalLinkage() != InternalLinkage) | ||||
169 | return; | ||||
170 | |||||
171 | // Downgrade from ExtWarn to Extension if | ||||
172 | // (1) the supposedly external inline function is in the main file, | ||||
173 | // and probably won't be included anywhere else. | ||||
174 | // (2) the thing we're referencing is a pure function. | ||||
175 | // (3) the thing we're referencing is another inline function. | ||||
176 | // This last can give us false negatives, but it's better than warning on | ||||
177 | // wrappers for simple C library functions. | ||||
178 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||
179 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||
180 | if (!DowngradeWarning && UsedFn) | ||||
181 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||
182 | |||||
183 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||
184 | : diag::ext_internal_in_extern_inline) | ||||
185 | << /*IsVar=*/!UsedFn << D; | ||||
186 | |||||
187 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||
188 | |||||
189 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||
190 | << D; | ||||
191 | } | ||||
192 | |||||
193 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||
194 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||
195 | |||||
196 | // Suggest "static" on the function, if possible. | ||||
197 | if (!hasAnyExplicitStorageClass(First)) { | ||||
198 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||
199 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||
200 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||
201 | } | ||||
202 | } | ||||
203 | |||||
204 | /// Determine whether the use of this declaration is valid, and | ||||
205 | /// emit any corresponding diagnostics. | ||||
206 | /// | ||||
207 | /// This routine diagnoses various problems with referencing | ||||
208 | /// declarations that can occur when using a declaration. For example, | ||||
209 | /// it might warn if a deprecated or unavailable declaration is being | ||||
210 | /// used, or produce an error (and return true) if a C++0x deleted | ||||
211 | /// function is being used. | ||||
212 | /// | ||||
213 | /// \returns true if there was an error (this declaration cannot be | ||||
214 | /// referenced), false otherwise. | ||||
215 | /// | ||||
216 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||
217 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||
218 | bool ObjCPropertyAccess, | ||||
219 | bool AvoidPartialAvailabilityChecks, | ||||
220 | ObjCInterfaceDecl *ClassReceiver) { | ||||
221 | SourceLocation Loc = Locs.front(); | ||||
222 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||
223 | // If there were any diagnostics suppressed by template argument deduction, | ||||
224 | // emit them now. | ||||
225 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||
226 | if (Pos != SuppressedDiagnostics.end()) { | ||||
227 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||
228 | Diag(Suppressed.first, Suppressed.second); | ||||
229 | |||||
230 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||
231 | // them again for this specialization. However, we don't obsolete this | ||||
232 | // entry from the table, because we want to avoid ever emitting these | ||||
233 | // diagnostics again. | ||||
234 | Pos->second.clear(); | ||||
235 | } | ||||
236 | |||||
237 | // C++ [basic.start.main]p3: | ||||
238 | // The function 'main' shall not be used within a program. | ||||
239 | if (cast<FunctionDecl>(D)->isMain()) | ||||
240 | Diag(Loc, diag::ext_main_used); | ||||
241 | |||||
242 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||
243 | } | ||||
244 | |||||
245 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
246 | if (ParsingInitForAutoVars.count(D)) { | ||||
247 | if (isa<BindingDecl>(D)) { | ||||
248 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||
249 | << D->getDeclName(); | ||||
250 | } else { | ||||
251 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||
252 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||
253 | } | ||||
254 | return true; | ||||
255 | } | ||||
256 | |||||
257 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
258 | // See if this is a deleted function. | ||||
259 | if (FD->isDeleted()) { | ||||
260 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||
261 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
262 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||
263 | << Ctor->getParent() | ||||
264 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||
265 | else | ||||
266 | Diag(Loc, diag::err_deleted_function_use); | ||||
267 | NoteDeletedFunction(FD); | ||||
268 | return true; | ||||
269 | } | ||||
270 | |||||
271 | // [expr.prim.id]p4 | ||||
272 | // A program that refers explicitly or implicitly to a function with a | ||||
273 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||
274 | // other than to declare it, is ill-formed. [...] | ||||
275 | // | ||||
276 | // See if this is a function with constraints that need to be satisfied. | ||||
277 | // Check this before deducing the return type, as it might instantiate the | ||||
278 | // definition. | ||||
279 | if (FD->getTrailingRequiresClause()) { | ||||
280 | ConstraintSatisfaction Satisfaction; | ||||
281 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||
282 | // A diagnostic will have already been generated (non-constant | ||||
283 | // constraint expression, for example) | ||||
284 | return true; | ||||
285 | if (!Satisfaction.IsSatisfied) { | ||||
286 | Diag(Loc, | ||||
287 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||
288 | << D; | ||||
289 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
290 | return true; | ||||
291 | } | ||||
292 | } | ||||
293 | |||||
294 | // If the function has a deduced return type, and we can't deduce it, | ||||
295 | // then we can't use it either. | ||||
296 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
297 | DeduceReturnType(FD, Loc)) | ||||
298 | return true; | ||||
299 | |||||
300 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||
301 | return true; | ||||
302 | |||||
303 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||
304 | return true; | ||||
305 | } | ||||
306 | |||||
307 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
308 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||
309 | if (MD->getParent()->isLambda() && | ||||
310 | ((isa<CXXConstructorDecl>(MD) && | ||||
311 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||
312 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||
313 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||
314 | << !isa<CXXConstructorDecl>(MD); | ||||
315 | } | ||||
316 | } | ||||
317 | |||||
318 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||
319 | const ObjCPropertyDecl * { | ||||
320 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||
321 | return MD->findPropertyDecl(); | ||||
322 | return nullptr; | ||||
323 | }; | ||||
324 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||
325 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||
326 | return true; | ||||
327 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||
328 | return true; | ||||
329 | } | ||||
330 | |||||
331 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||
332 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||
333 | // Only the variables omp_priv and omp_orig are allowed in the | ||||
334 | // initializer-clause. | ||||
335 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||
336 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||
337 | isa<VarDecl>(D)) { | ||||
338 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||
339 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||
340 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
341 | return true; | ||||
342 | } | ||||
343 | |||||
344 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||
345 | // List-items in map clauses on this construct may only refer to the declared | ||||
346 | // variable var and entities that could be referenced by a procedure defined | ||||
347 | // at the same location | ||||
348 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||
349 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||
350 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||
351 | << getOpenMPDeclareMapperVarName(); | ||||
352 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
353 | return true; | ||||
354 | } | ||||
355 | |||||
356 | if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { | ||||
357 | Diag(Loc, diag::err_use_of_empty_using_if_exists); | ||||
358 | Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); | ||||
359 | return true; | ||||
360 | } | ||||
361 | |||||
362 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||
363 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||
364 | |||||
365 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||
366 | |||||
367 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||
368 | |||||
369 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||
370 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||
371 | checkDeviceDecl(VD, Loc); | ||||
372 | |||||
373 | if (!Context.getTargetInfo().isTLSSupported()) | ||||
374 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
375 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||
376 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||
377 | } | ||||
378 | |||||
379 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||
380 | !isUnevaluatedContext()) { | ||||
381 | // C++ [expr.prim.req.nested] p3 | ||||
382 | // A local parameter shall only appear as an unevaluated operand | ||||
383 | // (Clause 8) within the constraint-expression. | ||||
384 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||
385 | << D; | ||||
386 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
387 | return true; | ||||
388 | } | ||||
389 | |||||
390 | return false; | ||||
391 | } | ||||
392 | |||||
393 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||
394 | /// message-send is to a declaration with the sentinel attribute, and | ||||
395 | /// if so, it checks that the requirements of the sentinel are | ||||
396 | /// satisfied. | ||||
397 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||
398 | ArrayRef<Expr *> Args) { | ||||
399 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||
400 | if (!attr) | ||||
401 | return; | ||||
402 | |||||
403 | // The number of formal parameters of the declaration. | ||||
404 | unsigned numFormalParams; | ||||
405 | |||||
406 | // The kind of declaration. This is also an index into a %select in | ||||
407 | // the diagnostic. | ||||
408 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||
409 | |||||
410 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||
411 | numFormalParams = MD->param_size(); | ||||
412 | calleeType = CT_Method; | ||||
413 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
414 | numFormalParams = FD->param_size(); | ||||
415 | calleeType = CT_Function; | ||||
416 | } else if (isa<VarDecl>(D)) { | ||||
417 | QualType type = cast<ValueDecl>(D)->getType(); | ||||
418 | const FunctionType *fn = nullptr; | ||||
419 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
420 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||
421 | if (!fn) return; | ||||
422 | calleeType = CT_Function; | ||||
423 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||
424 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||
425 | calleeType = CT_Block; | ||||
426 | } else { | ||||
427 | return; | ||||
428 | } | ||||
429 | |||||
430 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||
431 | numFormalParams = proto->getNumParams(); | ||||
432 | } else { | ||||
433 | numFormalParams = 0; | ||||
434 | } | ||||
435 | } else { | ||||
436 | return; | ||||
437 | } | ||||
438 | |||||
439 | // "nullPos" is the number of formal parameters at the end which | ||||
440 | // effectively count as part of the variadic arguments. This is | ||||
441 | // useful if you would prefer to not have *any* formal parameters, | ||||
442 | // but the language forces you to have at least one. | ||||
443 | unsigned nullPos = attr->getNullPos(); | ||||
444 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(static_cast <bool> ((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel") ? void (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 444, __extension__ __PRETTY_FUNCTION__)); | ||||
445 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||
446 | |||||
447 | // The number of arguments which should follow the sentinel. | ||||
448 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||
449 | |||||
450 | // If there aren't enough arguments for all the formal parameters, | ||||
451 | // the sentinel, and the args after the sentinel, complain. | ||||
452 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||
453 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||
454 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
455 | return; | ||||
456 | } | ||||
457 | |||||
458 | // Otherwise, find the sentinel expression. | ||||
459 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||
460 | if (!sentinelExpr) return; | ||||
461 | if (sentinelExpr->isValueDependent()) return; | ||||
462 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||
463 | |||||
464 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||
465 | // or 'NULL' if those are actually defined in the context. Only use | ||||
466 | // 'nil' for ObjC methods, where it's much more likely that the | ||||
467 | // variadic arguments form a list of object pointers. | ||||
468 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||
469 | std::string NullValue; | ||||
470 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||
471 | NullValue = "nil"; | ||||
472 | else if (getLangOpts().CPlusPlus11) | ||||
473 | NullValue = "nullptr"; | ||||
474 | else if (PP.isMacroDefined("NULL")) | ||||
475 | NullValue = "NULL"; | ||||
476 | else | ||||
477 | NullValue = "(void*) 0"; | ||||
478 | |||||
479 | if (MissingNilLoc.isInvalid()) | ||||
480 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||
481 | else | ||||
482 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||
483 | << int(calleeType) | ||||
484 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||
485 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
486 | } | ||||
487 | |||||
488 | SourceRange Sema::getExprRange(Expr *E) const { | ||||
489 | return E ? E->getSourceRange() : SourceRange(); | ||||
490 | } | ||||
491 | |||||
492 | //===----------------------------------------------------------------------===// | ||||
493 | // Standard Promotions and Conversions | ||||
494 | //===----------------------------------------------------------------------===// | ||||
495 | |||||
496 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||
497 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||
498 | // Handle any placeholder expressions which made it here. | ||||
499 | if (E->getType()->isPlaceholderType()) { | ||||
500 | ExprResult result = CheckPlaceholderExpr(E); | ||||
501 | if (result.isInvalid()) return ExprError(); | ||||
502 | E = result.get(); | ||||
503 | } | ||||
504 | |||||
505 | QualType Ty = E->getType(); | ||||
506 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 506, __extension__ __PRETTY_FUNCTION__)); | ||||
507 | |||||
508 | if (Ty->isFunctionType()) { | ||||
509 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||
510 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||
511 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||
512 | return ExprError(); | ||||
513 | |||||
514 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
515 | CK_FunctionToPointerDecay).get(); | ||||
516 | } else if (Ty->isArrayType()) { | ||||
517 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||
518 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||
519 | // type 'array of type' is converted to an expression that has type 'pointer | ||||
520 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||
521 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||
522 | // (C90) to "an expression" (C99). | ||||
523 | // | ||||
524 | // C++ 4.2p1: | ||||
525 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||
526 | // T" can be converted to an rvalue of type "pointer to T". | ||||
527 | // | ||||
528 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { | ||||
529 | ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||
530 | CK_ArrayToPointerDecay); | ||||
531 | if (Res.isInvalid()) | ||||
532 | return ExprError(); | ||||
533 | E = Res.get(); | ||||
534 | } | ||||
535 | } | ||||
536 | return E; | ||||
537 | } | ||||
538 | |||||
539 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||
540 | // Check to see if we are dereferencing a null pointer. If so, | ||||
541 | // and if not volatile-qualified, this is undefined behavior that the | ||||
542 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||
543 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||
544 | // only handles the pattern "*null", which is a very syntactic check. | ||||
545 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||
546 | if (UO && UO->getOpcode() == UO_Deref && | ||||
547 | UO->getSubExpr()->getType()->isPointerType()) { | ||||
548 | const LangAS AS = | ||||
549 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||
550 | if ((!isTargetAddressSpace(AS) || | ||||
551 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||
552 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||
553 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||
554 | !UO->getType().isVolatileQualified()) { | ||||
555 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
556 | S.PDiag(diag::warn_indirection_through_null) | ||||
557 | << UO->getSubExpr()->getSourceRange()); | ||||
558 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
559 | S.PDiag(diag::note_indirection_through_null)); | ||||
560 | } | ||||
561 | } | ||||
562 | } | ||||
563 | |||||
564 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||
565 | SourceLocation AssignLoc, | ||||
566 | const Expr* RHS) { | ||||
567 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||
568 | if (!IV) | ||||
569 | return; | ||||
570 | |||||
571 | DeclarationName MemberName = IV->getDeclName(); | ||||
572 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||
573 | if (!Member || !Member->isStr("isa")) | ||||
574 | return; | ||||
575 | |||||
576 | const Expr *Base = OIRE->getBase(); | ||||
577 | QualType BaseType = Base->getType(); | ||||
578 | if (OIRE->isArrow()) | ||||
579 | BaseType = BaseType->getPointeeType(); | ||||
580 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||
581 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||
582 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||
583 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||
584 | if (!ClassDeclared->getSuperClass() | ||||
585 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||
586 | if (RHS) { | ||||
587 | NamedDecl *ObjectSetClass = | ||||
588 | S.LookupSingleName(S.TUScope, | ||||
589 | &S.Context.Idents.get("object_setClass"), | ||||
590 | SourceLocation(), S.LookupOrdinaryName); | ||||
591 | if (ObjectSetClass) { | ||||
592 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||
593 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||
594 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
595 | "object_setClass(") | ||||
596 | << FixItHint::CreateReplacement( | ||||
597 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||
598 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
599 | } | ||||
600 | else | ||||
601 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||
602 | } else { | ||||
603 | NamedDecl *ObjectGetClass = | ||||
604 | S.LookupSingleName(S.TUScope, | ||||
605 | &S.Context.Idents.get("object_getClass"), | ||||
606 | SourceLocation(), S.LookupOrdinaryName); | ||||
607 | if (ObjectGetClass) | ||||
608 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||
609 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
610 | "object_getClass(") | ||||
611 | << FixItHint::CreateReplacement( | ||||
612 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||
613 | else | ||||
614 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||
615 | } | ||||
616 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||
617 | } | ||||
618 | } | ||||
619 | } | ||||
620 | |||||
621 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||
622 | // Handle any placeholder expressions which made it here. | ||||
623 | if (E->getType()->isPlaceholderType()) { | ||||
624 | ExprResult result = CheckPlaceholderExpr(E); | ||||
625 | if (result.isInvalid()) return ExprError(); | ||||
626 | E = result.get(); | ||||
627 | } | ||||
628 | |||||
629 | // C++ [conv.lval]p1: | ||||
630 | // A glvalue of a non-function, non-array type T can be | ||||
631 | // converted to a prvalue. | ||||
632 | if (!E->isGLValue()) return E; | ||||
633 | |||||
634 | QualType T = E->getType(); | ||||
635 | assert(!T.isNull() && "r-value conversion on typeless expression?")(static_cast <bool> (!T.isNull() && "r-value conversion on typeless expression?" ) ? void (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 635, __extension__ __PRETTY_FUNCTION__)); | ||||
636 | |||||
637 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||
638 | if (T->isFunctionType() || T->isArrayType()) | ||||
639 | return E; | ||||
640 | |||||
641 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||
642 | // expressions of certain types in C++. | ||||
643 | if (getLangOpts().CPlusPlus && | ||||
644 | (E->getType() == Context.OverloadTy || | ||||
645 | T->isDependentType() || | ||||
646 | T->isRecordType())) | ||||
647 | return E; | ||||
648 | |||||
649 | // The C standard is actually really unclear on this point, and | ||||
650 | // DR106 tells us what the result should be but not why. It's | ||||
651 | // generally best to say that void types just doesn't undergo | ||||
652 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||
653 | // 'void' type are never l-values, but qualified void can be. | ||||
654 | if (T->isVoidType()) | ||||
655 | return E; | ||||
656 | |||||
657 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||
658 | if (getLangOpts().OpenCL && | ||||
659 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
660 | T->isHalfType()) { | ||||
661 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||
662 | << 0 << T; | ||||
663 | return ExprError(); | ||||
664 | } | ||||
665 | |||||
666 | CheckForNullPointerDereference(*this, E); | ||||
667 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||
668 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||
669 | &Context.Idents.get("object_getClass"), | ||||
670 | SourceLocation(), LookupOrdinaryName); | ||||
671 | if (ObjectGetClass) | ||||
672 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||
673 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||
674 | << FixItHint::CreateReplacement( | ||||
675 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||
676 | else | ||||
677 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||
678 | } | ||||
679 | else if (const ObjCIvarRefExpr *OIRE = | ||||
680 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||
681 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||
682 | |||||
683 | // C++ [conv.lval]p1: | ||||
684 | // [...] If T is a non-class type, the type of the prvalue is the | ||||
685 | // cv-unqualified version of T. Otherwise, the type of the | ||||
686 | // rvalue is T. | ||||
687 | // | ||||
688 | // C99 6.3.2.1p2: | ||||
689 | // If the lvalue has qualified type, the value has the unqualified | ||||
690 | // version of the type of the lvalue; otherwise, the value has the | ||||
691 | // type of the lvalue. | ||||
692 | if (T.hasQualifiers()) | ||||
693 | T = T.getUnqualifiedType(); | ||||
694 | |||||
695 | // Under the MS ABI, lock down the inheritance model now. | ||||
696 | if (T->isMemberPointerType() && | ||||
697 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
698 | (void)isCompleteType(E->getExprLoc(), T); | ||||
699 | |||||
700 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||
701 | if (Res.isInvalid()) | ||||
702 | return Res; | ||||
703 | E = Res.get(); | ||||
704 | |||||
705 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||
706 | // balance that. | ||||
707 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
708 | Cleanup.setExprNeedsCleanups(true); | ||||
709 | |||||
710 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
711 | Cleanup.setExprNeedsCleanups(true); | ||||
712 | |||||
713 | // C++ [conv.lval]p3: | ||||
714 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||
715 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||
716 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, | ||||
717 | CurFPFeatureOverrides()); | ||||
718 | |||||
719 | // C11 6.3.2.1p2: | ||||
720 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||
721 | // of the type of the lvalue ... | ||||
722 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||
723 | T = Atomic->getValueType().getUnqualifiedType(); | ||||
724 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||
725 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
726 | } | ||||
727 | |||||
728 | return Res; | ||||
729 | } | ||||
730 | |||||
731 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||
732 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||
733 | if (Res.isInvalid()) | ||||
734 | return ExprError(); | ||||
735 | Res = DefaultLvalueConversion(Res.get()); | ||||
736 | if (Res.isInvalid()) | ||||
737 | return ExprError(); | ||||
738 | return Res; | ||||
739 | } | ||||
740 | |||||
741 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||
742 | /// performed on a function designator of a call expression. | ||||
743 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||
744 | QualType Ty = E->getType(); | ||||
745 | ExprResult Res = E; | ||||
746 | // Only do implicit cast for a function type, but not for a pointer | ||||
747 | // to function type. | ||||
748 | if (Ty->isFunctionType()) { | ||||
749 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
750 | CK_FunctionToPointerDecay); | ||||
751 | if (Res.isInvalid()) | ||||
752 | return ExprError(); | ||||
753 | } | ||||
754 | Res = DefaultLvalueConversion(Res.get()); | ||||
755 | if (Res.isInvalid()) | ||||
756 | return ExprError(); | ||||
757 | return Res.get(); | ||||
758 | } | ||||
759 | |||||
760 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||
761 | /// operators (C99 6.3). The conversions of array and function types are | ||||
762 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||
763 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||
764 | /// In these instances, this routine should *not* be called. | ||||
765 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||
766 | // First, convert to an r-value. | ||||
767 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||
768 | if (Res.isInvalid()) | ||||
769 | return ExprError(); | ||||
770 | E = Res.get(); | ||||
771 | |||||
772 | QualType Ty = E->getType(); | ||||
773 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")(static_cast <bool> (!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 773, __extension__ __PRETTY_FUNCTION__)); | ||||
774 | |||||
775 | LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); | ||||
776 | if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType()) { | ||||
777 | switch (EvalMethod) { | ||||
778 | default: | ||||
779 | llvm_unreachable("Unrecognized float evaluation method")::llvm::llvm_unreachable_internal("Unrecognized float evaluation method" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 779); | ||||
780 | break; | ||||
781 | case LangOptions::FEM_TargetDefault: | ||||
782 | // Float evaluation method not defined, use FEM_Source. | ||||
783 | break; | ||||
784 | case LangOptions::FEM_Double: | ||||
785 | if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) | ||||
786 | // Widen the expression to double. | ||||
787 | return Ty->isComplexType() | ||||
788 | ? ImpCastExprToType(E, | ||||
789 | Context.getComplexType(Context.DoubleTy), | ||||
790 | CK_FloatingComplexCast) | ||||
791 | : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); | ||||
792 | break; | ||||
793 | case LangOptions::FEM_Extended: | ||||
794 | if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) | ||||
795 | // Widen the expression to long double. | ||||
796 | return Ty->isComplexType() | ||||
797 | ? ImpCastExprToType( | ||||
798 | E, Context.getComplexType(Context.LongDoubleTy), | ||||
799 | CK_FloatingComplexCast) | ||||
800 | : ImpCastExprToType(E, Context.LongDoubleTy, | ||||
801 | CK_FloatingCast); | ||||
802 | break; | ||||
803 | } | ||||
804 | } | ||||
805 | |||||
806 | // Half FP have to be promoted to float unless it is natively supported | ||||
807 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||
808 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||
809 | |||||
810 | // Try to perform integral promotions if the object has a theoretically | ||||
811 | // promotable type. | ||||
812 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||
813 | // C99 6.3.1.1p2: | ||||
814 | // | ||||
815 | // The following may be used in an expression wherever an int or | ||||
816 | // unsigned int may be used: | ||||
817 | // - an object or expression with an integer type whose integer | ||||
818 | // conversion rank is less than or equal to the rank of int | ||||
819 | // and unsigned int. | ||||
820 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||
821 | // | ||||
822 | // If an int can represent all values of the original type, the | ||||
823 | // value is converted to an int; otherwise, it is converted to an | ||||
824 | // unsigned int. These are called the integer promotions. All | ||||
825 | // other types are unchanged by the integer promotions. | ||||
826 | |||||
827 | QualType PTy = Context.isPromotableBitField(E); | ||||
828 | if (!PTy.isNull()) { | ||||
829 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||
830 | return E; | ||||
831 | } | ||||
832 | if (Ty->isPromotableIntegerType()) { | ||||
833 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||
834 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||
835 | return E; | ||||
836 | } | ||||
837 | } | ||||
838 | return E; | ||||
839 | } | ||||
840 | |||||
841 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||
842 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||
843 | /// are promoted to double. All other argument types are converted by | ||||
844 | /// UsualUnaryConversions(). | ||||
845 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||
846 | QualType Ty = E->getType(); | ||||
847 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")(static_cast <bool> (!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? void (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 847, __extension__ __PRETTY_FUNCTION__)); | ||||
848 | |||||
849 | ExprResult Res = UsualUnaryConversions(E); | ||||
850 | if (Res.isInvalid()) | ||||
851 | return ExprError(); | ||||
852 | E = Res.get(); | ||||
853 | |||||
854 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||
855 | // promote to double. | ||||
856 | // Note that default argument promotion applies only to float (and | ||||
857 | // half/fp16); it does not apply to _Float16. | ||||
858 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
859 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||
860 | BTy->getKind() == BuiltinType::Float)) { | ||||
861 | if (getLangOpts().OpenCL && | ||||
862 | !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { | ||||
863 | if (BTy->getKind() == BuiltinType::Half) { | ||||
864 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||
865 | } | ||||
866 | } else { | ||||
867 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||
868 | } | ||||
869 | } | ||||
870 | if (BTy && | ||||
871 | getLangOpts().getExtendIntArgs() == | ||||
872 | LangOptions::ExtendArgsKind::ExtendTo64 && | ||||
873 | Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && | ||||
874 | Context.getTypeSizeInChars(BTy) < | ||||
875 | Context.getTypeSizeInChars(Context.LongLongTy)) { | ||||
876 | E = (Ty->isUnsignedIntegerType()) | ||||
877 | ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) | ||||
878 | .get() | ||||
879 | : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); | ||||
880 | assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 881, __extension__ __PRETTY_FUNCTION__)) | ||||
881 | "Unexpected typesize for LongLongTy")(static_cast <bool> (8 == Context.getTypeSizeInChars(Context .LongLongTy).getQuantity() && "Unexpected typesize for LongLongTy" ) ? void (0) : __assert_fail ("8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && \"Unexpected typesize for LongLongTy\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 881, __extension__ __PRETTY_FUNCTION__)); | ||||
882 | } | ||||
883 | |||||
884 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||
885 | // promotion, even on class types, but note: | ||||
886 | // C++11 [conv.lval]p2: | ||||
887 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||
888 | // operand or a subexpression thereof the value contained in the | ||||
889 | // referenced object is not accessed. Otherwise, if the glvalue | ||||
890 | // has a class type, the conversion copy-initializes a temporary | ||||
891 | // of type T from the glvalue and the result of the conversion | ||||
892 | // is a prvalue for the temporary. | ||||
893 | // FIXME: add some way to gate this entire thing for correctness in | ||||
894 | // potentially potentially evaluated contexts. | ||||
895 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||
896 | ExprResult Temp = PerformCopyInitialization( | ||||
897 | InitializedEntity::InitializeTemporary(E->getType()), | ||||
898 | E->getExprLoc(), E); | ||||
899 | if (Temp.isInvalid()) | ||||
900 | return ExprError(); | ||||
901 | E = Temp.get(); | ||||
902 | } | ||||
903 | |||||
904 | return E; | ||||
905 | } | ||||
906 | |||||
907 | /// Determine the degree of POD-ness for an expression. | ||||
908 | /// Incomplete types are considered POD, since this check can be performed | ||||
909 | /// when we're in an unevaluated context. | ||||
910 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||
911 | if (Ty->isIncompleteType()) { | ||||
912 | // C++11 [expr.call]p7: | ||||
913 | // After these conversions, if the argument does not have arithmetic, | ||||
914 | // enumeration, pointer, pointer to member, or class type, the program | ||||
915 | // is ill-formed. | ||||
916 | // | ||||
917 | // Since we've already performed array-to-pointer and function-to-pointer | ||||
918 | // decay, the only such type in C++ is cv void. This also handles | ||||
919 | // initializer lists as variadic arguments. | ||||
920 | if (Ty->isVoidType()) | ||||
921 | return VAK_Invalid; | ||||
922 | |||||
923 | if (Ty->isObjCObjectType()) | ||||
924 | return VAK_Invalid; | ||||
925 | return VAK_Valid; | ||||
926 | } | ||||
927 | |||||
928 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
929 | return VAK_Invalid; | ||||
930 | |||||
931 | if (Ty.isCXX98PODType(Context)) | ||||
932 | return VAK_Valid; | ||||
933 | |||||
934 | // C++11 [expr.call]p7: | ||||
935 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||
936 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||
937 | // or a non-trivial destructor, with no corresponding parameter, | ||||
938 | // is conditionally-supported with implementation-defined semantics. | ||||
939 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||
940 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||
941 | if (!Record->hasNonTrivialCopyConstructor() && | ||||
942 | !Record->hasNonTrivialMoveConstructor() && | ||||
943 | !Record->hasNonTrivialDestructor()) | ||||
944 | return VAK_ValidInCXX11; | ||||
945 | |||||
946 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||
947 | return VAK_Valid; | ||||
948 | |||||
949 | if (Ty->isObjCObjectType()) | ||||
950 | return VAK_Invalid; | ||||
951 | |||||
952 | if (getLangOpts().MSVCCompat) | ||||
953 | return VAK_MSVCUndefined; | ||||
954 | |||||
955 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||
956 | // permitted to reject them. We should consider doing so. | ||||
957 | return VAK_Undefined; | ||||
958 | } | ||||
959 | |||||
960 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||
961 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||
962 | const QualType &Ty = E->getType(); | ||||
963 | VarArgKind VAK = isValidVarArgType(Ty); | ||||
964 | |||||
965 | // Complain about passing non-POD types through varargs. | ||||
966 | switch (VAK) { | ||||
967 | case VAK_ValidInCXX11: | ||||
968 | DiagRuntimeBehavior( | ||||
969 | E->getBeginLoc(), nullptr, | ||||
970 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||
971 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
972 | case VAK_Valid: | ||||
973 | if (Ty->isRecordType()) { | ||||
974 | // This is unlikely to be what the user intended. If the class has a | ||||
975 | // 'c_str' member function, the user probably meant to call that. | ||||
976 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
977 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||
978 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||
979 | } | ||||
980 | break; | ||||
981 | |||||
982 | case VAK_Undefined: | ||||
983 | case VAK_MSVCUndefined: | ||||
984 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
985 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||
986 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||
987 | break; | ||||
988 | |||||
989 | case VAK_Invalid: | ||||
990 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
991 | Diag(E->getBeginLoc(), | ||||
992 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||
993 | << Ty << CT; | ||||
994 | else if (Ty->isObjCObjectType()) | ||||
995 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
996 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||
997 | << Ty << CT); | ||||
998 | else | ||||
999 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||
1000 | << isa<InitListExpr>(E) << Ty << CT; | ||||
1001 | break; | ||||
1002 | } | ||||
1003 | } | ||||
1004 | |||||
1005 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||
1006 | /// will create a trap if the resulting type is not a POD type. | ||||
1007 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||
1008 | FunctionDecl *FDecl) { | ||||
1009 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||
1010 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
1011 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||
1012 | (CT == VariadicMethod || | ||||
1013 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||
1014 | E = stripARCUnbridgedCast(E); | ||||
1015 | |||||
1016 | // Otherwise, do normal placeholder checking. | ||||
1017 | } else { | ||||
1018 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||
1019 | if (ExprRes.isInvalid()) | ||||
1020 | return ExprError(); | ||||
1021 | E = ExprRes.get(); | ||||
1022 | } | ||||
1023 | } | ||||
1024 | |||||
1025 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||
1026 | if (ExprRes.isInvalid()) | ||||
1027 | return ExprError(); | ||||
1028 | |||||
1029 | // Copy blocks to the heap. | ||||
1030 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||
1031 | maybeExtendBlockObject(ExprRes); | ||||
1032 | |||||
1033 | E = ExprRes.get(); | ||||
1034 | |||||
1035 | // Diagnostics regarding non-POD argument types are | ||||
1036 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||
1037 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||
1038 | // Turn this into a trap. | ||||
1039 | CXXScopeSpec SS; | ||||
1040 | SourceLocation TemplateKWLoc; | ||||
1041 | UnqualifiedId Name; | ||||
1042 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||
1043 | E->getBeginLoc()); | ||||
1044 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||
1045 | /*HasTrailingLParen=*/true, | ||||
1046 | /*IsAddressOfOperand=*/false); | ||||
1047 | if (TrapFn.isInvalid()) | ||||
1048 | return ExprError(); | ||||
1049 | |||||
1050 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||
1051 | None, E->getEndLoc()); | ||||
1052 | if (Call.isInvalid()) | ||||
1053 | return ExprError(); | ||||
1054 | |||||
1055 | ExprResult Comma = | ||||
1056 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||
1057 | if (Comma.isInvalid()) | ||||
1058 | return ExprError(); | ||||
1059 | return Comma.get(); | ||||
1060 | } | ||||
1061 | |||||
1062 | if (!getLangOpts().CPlusPlus && | ||||
1063 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||
1064 | diag::err_call_incomplete_argument)) | ||||
1065 | return ExprError(); | ||||
1066 | |||||
1067 | return E; | ||||
1068 | } | ||||
1069 | |||||
1070 | /// Converts an integer to complex float type. Helper function of | ||||
1071 | /// UsualArithmeticConversions() | ||||
1072 | /// | ||||
1073 | /// \return false if the integer expression is an integer type and is | ||||
1074 | /// successfully converted to the complex type. | ||||
1075 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||
1076 | ExprResult &ComplexExpr, | ||||
1077 | QualType IntTy, | ||||
1078 | QualType ComplexTy, | ||||
1079 | bool SkipCast) { | ||||
1080 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||
1081 | if (SkipCast) return false; | ||||
1082 | if (IntTy->isIntegerType()) { | ||||
1083 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||
1084 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||
1085 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1086 | CK_FloatingRealToComplex); | ||||
1087 | } else { | ||||
1088 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1088, __extension__ __PRETTY_FUNCTION__)); | ||||
1089 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1090 | CK_IntegralComplexToFloatingComplex); | ||||
1091 | } | ||||
1092 | return false; | ||||
1093 | } | ||||
1094 | |||||
1095 | /// Handle arithmetic conversion with complex types. Helper function of | ||||
1096 | /// UsualArithmeticConversions() | ||||
1097 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||
1098 | ExprResult &RHS, QualType LHSType, | ||||
1099 | QualType RHSType, | ||||
1100 | bool IsCompAssign) { | ||||
1101 | // if we have an integer operand, the result is the complex type. | ||||
1102 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1103 | /*skipCast*/false)) | ||||
1104 | return LHSType; | ||||
1105 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1106 | /*skipCast*/IsCompAssign)) | ||||
1107 | return RHSType; | ||||
1108 | |||||
1109 | // This handles complex/complex, complex/float, or float/complex. | ||||
1110 | // When both operands are complex, the shorter operand is converted to the | ||||
1111 | // type of the longer, and that is the type of the result. This corresponds | ||||
1112 | // to what is done when combining two real floating-point operands. | ||||
1113 | // The fun begins when size promotion occur across type domains. | ||||
1114 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||
1115 | // floating-point type, the less precise type is converted, within it's | ||||
1116 | // real or complex domain, to the precision of the other type. For example, | ||||
1117 | // when combining a "long double" with a "double _Complex", the | ||||
1118 | // "double _Complex" is promoted to "long double _Complex". | ||||
1119 | |||||
1120 | // Compute the rank of the two types, regardless of whether they are complex. | ||||
1121 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1122 | |||||
1123 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||
1124 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||
1125 | QualType LHSElementType = | ||||
1126 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||
1127 | QualType RHSElementType = | ||||
1128 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||
1129 | |||||
1130 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||
1131 | if (Order < 0) { | ||||
1132 | // Promote the precision of the LHS if not an assignment. | ||||
1133 | ResultType = S.Context.getComplexType(RHSElementType); | ||||
1134 | if (!IsCompAssign) { | ||||
1135 | if (LHSComplexType) | ||||
1136 | LHS = | ||||
1137 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1138 | else | ||||
1139 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||
1140 | } | ||||
1141 | } else if (Order > 0) { | ||||
1142 | // Promote the precision of the RHS. | ||||
1143 | if (RHSComplexType) | ||||
1144 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1145 | else | ||||
1146 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||
1147 | } | ||||
1148 | return ResultType; | ||||
1149 | } | ||||
1150 | |||||
1151 | /// Handle arithmetic conversion from integer to float. Helper function | ||||
1152 | /// of UsualArithmeticConversions() | ||||
1153 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||
1154 | ExprResult &IntExpr, | ||||
1155 | QualType FloatTy, QualType IntTy, | ||||
1156 | bool ConvertFloat, bool ConvertInt) { | ||||
1157 | if (IntTy->isIntegerType()) { | ||||
1158 | if (ConvertInt) | ||||
1159 | // Convert intExpr to the lhs floating point type. | ||||
1160 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||
1161 | CK_IntegralToFloating); | ||||
1162 | return FloatTy; | ||||
1163 | } | ||||
1164 | |||||
1165 | // Convert both sides to the appropriate complex float. | ||||
1166 | assert(IntTy->isComplexIntegerType())(static_cast <bool> (IntTy->isComplexIntegerType()) ? void (0) : __assert_fail ("IntTy->isComplexIntegerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1166, __extension__ __PRETTY_FUNCTION__)); | ||||
1167 | QualType result = S.Context.getComplexType(FloatTy); | ||||
1168 | |||||
1169 | // _Complex int -> _Complex float | ||||
1170 | if (ConvertInt) | ||||
1171 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||
1172 | CK_IntegralComplexToFloatingComplex); | ||||
1173 | |||||
1174 | // float -> _Complex float | ||||
1175 | if (ConvertFloat) | ||||
1176 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||
1177 | CK_FloatingRealToComplex); | ||||
1178 | |||||
1179 | return result; | ||||
1180 | } | ||||
1181 | |||||
1182 | /// Handle arithmethic conversion with floating point types. Helper | ||||
1183 | /// function of UsualArithmeticConversions() | ||||
1184 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||
1185 | ExprResult &RHS, QualType LHSType, | ||||
1186 | QualType RHSType, bool IsCompAssign) { | ||||
1187 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||
1188 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||
1189 | |||||
1190 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||
1191 | // operand has a fixed-point type, the fixed-point operand | ||||
1192 | // is converted to the floating type [...] | ||||
1193 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||
1194 | if (LHSFloat) | ||||
1195 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||
1196 | else if (!IsCompAssign) | ||||
1197 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||
1198 | return LHSFloat ? LHSType : RHSType; | ||||
1199 | } | ||||
1200 | |||||
1201 | // If we have two real floating types, convert the smaller operand | ||||
1202 | // to the bigger result. | ||||
1203 | if (LHSFloat && RHSFloat) { | ||||
1204 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1205 | if (order > 0) { | ||||
1206 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||
1207 | return LHSType; | ||||
1208 | } | ||||
1209 | |||||
1210 | assert(order < 0 && "illegal float comparison")(static_cast <bool> (order < 0 && "illegal float comparison" ) ? void (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1210, __extension__ __PRETTY_FUNCTION__)); | ||||
1211 | if (!IsCompAssign) | ||||
1212 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||
1213 | return RHSType; | ||||
1214 | } | ||||
1215 | |||||
1216 | if (LHSFloat) { | ||||
1217 | // Half FP has to be promoted to float unless it is natively supported | ||||
1218 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||
1219 | LHSType = S.Context.FloatTy; | ||||
1220 | |||||
1221 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1222 | /*ConvertFloat=*/!IsCompAssign, | ||||
1223 | /*ConvertInt=*/ true); | ||||
1224 | } | ||||
1225 | assert(RHSFloat)(static_cast <bool> (RHSFloat) ? void (0) : __assert_fail ("RHSFloat", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1225, __extension__ __PRETTY_FUNCTION__)); | ||||
1226 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1227 | /*ConvertFloat=*/ true, | ||||
1228 | /*ConvertInt=*/!IsCompAssign); | ||||
1229 | } | ||||
1230 | |||||
1231 | /// Diagnose attempts to convert between __float128 and long double if | ||||
1232 | /// there is no support for such conversion. Helper function of | ||||
1233 | /// UsualArithmeticConversions(). | ||||
1234 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||
1235 | QualType RHSType) { | ||||
1236 | /* No issue converting if at least one of the types is not a floating point | ||||
1237 | type or the two types have the same rank. | ||||
1238 | */ | ||||
1239 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||
1240 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||
1241 | return false; | ||||
1242 | |||||
1243 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&(static_cast <bool> (LHSType->isFloatingType() && RHSType->isFloatingType() && "The remaining types must be floating point types." ) ? void (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1244, __extension__ __PRETTY_FUNCTION__)) | ||||
1244 | "The remaining types must be floating point types.")(static_cast <bool> (LHSType->isFloatingType() && RHSType->isFloatingType() && "The remaining types must be floating point types." ) ? void (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1244, __extension__ __PRETTY_FUNCTION__)); | ||||
1245 | |||||
1246 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||
1247 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||
1248 | |||||
1249 | QualType LHSElemType = LHSComplex ? | ||||
1250 | LHSComplex->getElementType() : LHSType; | ||||
1251 | QualType RHSElemType = RHSComplex ? | ||||
1252 | RHSComplex->getElementType() : RHSType; | ||||
1253 | |||||
1254 | // No issue if the two types have the same representation | ||||
1255 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||
1256 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||
1257 | return false; | ||||
1258 | |||||
1259 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||
1260 | RHSElemType == S.Context.LongDoubleTy); | ||||
1261 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||
1262 | RHSElemType == S.Context.Float128Ty); | ||||
1263 | |||||
1264 | // We've handled the situation where __float128 and long double have the same | ||||
1265 | // representation. We allow all conversions for all possible long double types | ||||
1266 | // except PPC's double double. | ||||
1267 | return Float128AndLongDouble && | ||||
1268 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||
1269 | &llvm::APFloat::PPCDoubleDouble()); | ||||
1270 | } | ||||
1271 | |||||
1272 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||
1273 | |||||
1274 | namespace { | ||||
1275 | /// These helper callbacks are placed in an anonymous namespace to | ||||
1276 | /// permit their use as function template parameters. | ||||
1277 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1278 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||
1279 | } | ||||
1280 | |||||
1281 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1282 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||
1283 | CK_IntegralComplexCast); | ||||
1284 | } | ||||
1285 | } | ||||
1286 | |||||
1287 | /// Handle integer arithmetic conversions. Helper function of | ||||
1288 | /// UsualArithmeticConversions() | ||||
1289 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||
1290 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||
1291 | ExprResult &RHS, QualType LHSType, | ||||
1292 | QualType RHSType, bool IsCompAssign) { | ||||
1293 | // The rules for this case are in C99 6.3.1.8 | ||||
1294 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||
1295 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||
1296 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||
1297 | if (LHSSigned == RHSSigned) { | ||||
1298 | // Same signedness; use the higher-ranked type | ||||
1299 | if (order >= 0) { | ||||
1300 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1301 | return LHSType; | ||||
1302 | } else if (!IsCompAssign) | ||||
1303 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1304 | return RHSType; | ||||
1305 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||
1306 | // The unsigned type has greater than or equal rank to the | ||||
1307 | // signed type, so use the unsigned type | ||||
1308 | if (RHSSigned) { | ||||
1309 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1310 | return LHSType; | ||||
1311 | } else if (!IsCompAssign) | ||||
1312 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1313 | return RHSType; | ||||
1314 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||
1315 | // The two types are different widths; if we are here, that | ||||
1316 | // means the signed type is larger than the unsigned type, so | ||||
1317 | // use the signed type. | ||||
1318 | if (LHSSigned) { | ||||
1319 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1320 | return LHSType; | ||||
1321 | } else if (!IsCompAssign) | ||||
1322 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1323 | return RHSType; | ||||
1324 | } else { | ||||
1325 | // The signed type is higher-ranked than the unsigned type, | ||||
1326 | // but isn't actually any bigger (like unsigned int and long | ||||
1327 | // on most 32-bit systems). Use the unsigned type corresponding | ||||
1328 | // to the signed type. | ||||
1329 | QualType result = | ||||
1330 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||
1331 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||
1332 | if (!IsCompAssign) | ||||
1333 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||
1334 | return result; | ||||
1335 | } | ||||
1336 | } | ||||
1337 | |||||
1338 | /// Handle conversions with GCC complex int extension. Helper function | ||||
1339 | /// of UsualArithmeticConversions() | ||||
1340 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||
1341 | ExprResult &RHS, QualType LHSType, | ||||
1342 | QualType RHSType, | ||||
1343 | bool IsCompAssign) { | ||||
1344 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||
1345 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||
1346 | |||||
1347 | if (LHSComplexInt && RHSComplexInt) { | ||||
1348 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1349 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1350 | QualType ScalarType = | ||||
1351 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||
1352 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||
1353 | |||||
1354 | return S.Context.getComplexType(ScalarType); | ||||
1355 | } | ||||
1356 | |||||
1357 | if (LHSComplexInt) { | ||||
1358 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1359 | QualType ScalarType = | ||||
1360 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||
1361 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||
1362 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1363 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||
1364 | CK_IntegralRealToComplex); | ||||
1365 | |||||
1366 | return ComplexType; | ||||
1367 | } | ||||
1368 | |||||
1369 | assert(RHSComplexInt)(static_cast <bool> (RHSComplexInt) ? void (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1369, __extension__ __PRETTY_FUNCTION__)); | ||||
1370 | |||||
1371 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1372 | QualType ScalarType = | ||||
1373 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||
1374 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||
1375 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1376 | |||||
1377 | if (!IsCompAssign) | ||||
1378 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||
1379 | CK_IntegralRealToComplex); | ||||
1380 | return ComplexType; | ||||
1381 | } | ||||
1382 | |||||
1383 | /// Return the rank of a given fixed point or integer type. The value itself | ||||
1384 | /// doesn't matter, but the values must be increasing with proper increasing | ||||
1385 | /// rank as described in N1169 4.1.1. | ||||
1386 | static unsigned GetFixedPointRank(QualType Ty) { | ||||
1387 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||
1388 | assert(BTy && "Expected a builtin type.")(static_cast <bool> (BTy && "Expected a builtin type." ) ? void (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1388, __extension__ __PRETTY_FUNCTION__)); | ||||
1389 | |||||
1390 | switch (BTy->getKind()) { | ||||
1391 | case BuiltinType::ShortFract: | ||||
1392 | case BuiltinType::UShortFract: | ||||
1393 | case BuiltinType::SatShortFract: | ||||
1394 | case BuiltinType::SatUShortFract: | ||||
1395 | return 1; | ||||
1396 | case BuiltinType::Fract: | ||||
1397 | case BuiltinType::UFract: | ||||
1398 | case BuiltinType::SatFract: | ||||
1399 | case BuiltinType::SatUFract: | ||||
1400 | return 2; | ||||
1401 | case BuiltinType::LongFract: | ||||
1402 | case BuiltinType::ULongFract: | ||||
1403 | case BuiltinType::SatLongFract: | ||||
1404 | case BuiltinType::SatULongFract: | ||||
1405 | return 3; | ||||
1406 | case BuiltinType::ShortAccum: | ||||
1407 | case BuiltinType::UShortAccum: | ||||
1408 | case BuiltinType::SatShortAccum: | ||||
1409 | case BuiltinType::SatUShortAccum: | ||||
1410 | return 4; | ||||
1411 | case BuiltinType::Accum: | ||||
1412 | case BuiltinType::UAccum: | ||||
1413 | case BuiltinType::SatAccum: | ||||
1414 | case BuiltinType::SatUAccum: | ||||
1415 | return 5; | ||||
1416 | case BuiltinType::LongAccum: | ||||
1417 | case BuiltinType::ULongAccum: | ||||
1418 | case BuiltinType::SatLongAccum: | ||||
1419 | case BuiltinType::SatULongAccum: | ||||
1420 | return 6; | ||||
1421 | default: | ||||
1422 | if (BTy->isInteger()) | ||||
1423 | return 0; | ||||
1424 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1424); | ||||
1425 | } | ||||
1426 | } | ||||
1427 | |||||
1428 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||
1429 | /// point types and integers or other fixed point types do not fall under | ||||
1430 | /// usual arithmetic conversion since these conversions could result in loss | ||||
1431 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||
1432 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||
1433 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||
1434 | QualType RHSTy) { | ||||
1435 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1436, __extension__ __PRETTY_FUNCTION__)) | ||||
1436 | "Expected at least one of the operands to be a fixed point type")(static_cast <bool> ((LHSTy->isFixedPointType() || RHSTy ->isFixedPointType()) && "Expected at least one of the operands to be a fixed point type" ) ? void (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1436, __extension__ __PRETTY_FUNCTION__)); | ||||
1437 | assert((LHSTy->isFixedPointOrIntegerType() ||(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1440, __extension__ __PRETTY_FUNCTION__)) | ||||
1438 | RHSTy->isFixedPointOrIntegerType()) &&(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1440, __extension__ __PRETTY_FUNCTION__)) | ||||
1439 | "Special fixed point arithmetic operation conversions are only "(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1440, __extension__ __PRETTY_FUNCTION__)) | ||||
1440 | "applied to ints or other fixed point types")(static_cast <bool> ((LHSTy->isFixedPointOrIntegerType () || RHSTy->isFixedPointOrIntegerType()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? void (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1440, __extension__ __PRETTY_FUNCTION__)); | ||||
1441 | |||||
1442 | // If one operand has signed fixed-point type and the other operand has | ||||
1443 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||
1444 | // converted to its corresponding signed fixed-point type and the resulting | ||||
1445 | // type is the type of the converted operand. | ||||
1446 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||
1447 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||
1448 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||
1449 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||
1450 | |||||
1451 | // The result type is the type with the highest rank, whereby a fixed-point | ||||
1452 | // conversion rank is always greater than an integer conversion rank; if the | ||||
1453 | // type of either of the operands is a saturating fixedpoint type, the result | ||||
1454 | // type shall be the saturating fixed-point type corresponding to the type | ||||
1455 | // with the highest rank; the resulting value is converted (taking into | ||||
1456 | // account rounding and overflow) to the precision of the resulting type. | ||||
1457 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||
1458 | // types are either signed or both unsigned at this point. | ||||
1459 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||
1460 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||
1461 | |||||
1462 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||
1463 | |||||
1464 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||
1465 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||
1466 | |||||
1467 | return ResultTy; | ||||
1468 | } | ||||
1469 | |||||
1470 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||
1471 | /// expressions that might be of enumeration type. | ||||
1472 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||
1473 | SourceLocation Loc, | ||||
1474 | Sema::ArithConvKind ACK) { | ||||
1475 | // C++2a [expr.arith.conv]p1: | ||||
1476 | // If one operand is of enumeration type and the other operand is of a | ||||
1477 | // different enumeration type or a floating-point type, this behavior is | ||||
1478 | // deprecated ([depr.arith.conv.enum]). | ||||
1479 | // | ||||
1480 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||
1481 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||
1482 | QualType L = LHS->getType(), R = RHS->getType(); | ||||
1483 | bool LEnum = L->isUnscopedEnumerationType(), | ||||
1484 | REnum = R->isUnscopedEnumerationType(); | ||||
1485 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||
1486 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||
1487 | (REnum && L->isFloatingType())) { | ||||
1488 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||
1489 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||
1490 | : diag::warn_arith_conv_enum_float) | ||||
1491 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1492 | << (int)ACK << LEnum << L << R; | ||||
1493 | } else if (!IsCompAssign && LEnum && REnum && | ||||
1494 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||
1495 | unsigned DiagID; | ||||
1496 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||
1497 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||
1498 | // If either enumeration type is unnamed, it's less likely that the | ||||
1499 | // user cares about this, but this situation is still deprecated in | ||||
1500 | // C++2a. Use a different warning group. | ||||
1501 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1502 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||
1503 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||
1504 | } else if (ACK == Sema::ACK_Conditional) { | ||||
1505 | // Conditional expressions are separated out because they have | ||||
1506 | // historically had a different warning flag. | ||||
1507 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1508 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||
1509 | : diag::warn_conditional_mixed_enum_types; | ||||
1510 | } else if (ACK == Sema::ACK_Comparison) { | ||||
1511 | // Comparison expressions are separated out because they have | ||||
1512 | // historically had a different warning flag. | ||||
1513 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1514 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||
1515 | : diag::warn_comparison_mixed_enum_types; | ||||
1516 | } else { | ||||
1517 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1518 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||
1519 | : diag::warn_arith_conv_mixed_enum_types; | ||||
1520 | } | ||||
1521 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1522 | << (int)ACK << L << R; | ||||
1523 | } | ||||
1524 | } | ||||
1525 | |||||
1526 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||
1527 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||
1528 | /// routine returns the first non-arithmetic type found. The client is | ||||
1529 | /// responsible for emitting appropriate error diagnostics. | ||||
1530 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||
1531 | SourceLocation Loc, | ||||
1532 | ArithConvKind ACK) { | ||||
1533 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||
1534 | |||||
1535 | if (ACK != ACK_CompAssign) { | ||||
1536 | LHS = UsualUnaryConversions(LHS.get()); | ||||
1537 | if (LHS.isInvalid()) | ||||
1538 | return QualType(); | ||||
1539 | } | ||||
1540 | |||||
1541 | RHS = UsualUnaryConversions(RHS.get()); | ||||
1542 | if (RHS.isInvalid()) | ||||
1543 | return QualType(); | ||||
1544 | |||||
1545 | // For conversion purposes, we ignore any qualifiers. | ||||
1546 | // For example, "const float" and "float" are equivalent. | ||||
1547 | QualType LHSType = | ||||
1548 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
1549 | QualType RHSType = | ||||
1550 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
1551 | |||||
1552 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||
1553 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||
1554 | LHSType = AtomicLHS->getValueType(); | ||||
1555 | |||||
1556 | // If both types are identical, no conversion is needed. | ||||
1557 | if (LHSType == RHSType) | ||||
1558 | return LHSType; | ||||
1559 | |||||
1560 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||
1561 | // The caller can deal with this (e.g. pointer + int). | ||||
1562 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||
1563 | return QualType(); | ||||
1564 | |||||
1565 | // Apply unary and bitfield promotions to the LHS's type. | ||||
1566 | QualType LHSUnpromotedType = LHSType; | ||||
1567 | if (LHSType->isPromotableIntegerType()) | ||||
1568 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||
1569 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||
1570 | if (!LHSBitfieldPromoteTy.isNull()) | ||||
1571 | LHSType = LHSBitfieldPromoteTy; | ||||
1572 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||
1573 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||
1574 | |||||
1575 | // If both types are identical, no conversion is needed. | ||||
1576 | if (LHSType == RHSType) | ||||
1577 | return LHSType; | ||||
1578 | |||||
1579 | // At this point, we have two different arithmetic types. | ||||
1580 | |||||
1581 | // Diagnose attempts to convert between __float128 and long double where | ||||
1582 | // such conversions currently can't be handled. | ||||
1583 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
1584 | return QualType(); | ||||
1585 | |||||
1586 | // Handle complex types first (C99 6.3.1.8p1). | ||||
1587 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||
1588 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1589 | ACK == ACK_CompAssign); | ||||
1590 | |||||
1591 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
1592 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
1593 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1594 | ACK == ACK_CompAssign); | ||||
1595 | |||||
1596 | // Handle GCC complex int extension. | ||||
1597 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||
1598 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1599 | ACK == ACK_CompAssign); | ||||
1600 | |||||
1601 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||
1602 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||
1603 | |||||
1604 | // Finally, we have two differing integer types. | ||||
1605 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
1606 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||
1607 | } | ||||
1608 | |||||
1609 | //===----------------------------------------------------------------------===// | ||||
1610 | // Semantic Analysis for various Expression Types | ||||
1611 | //===----------------------------------------------------------------------===// | ||||
1612 | |||||
1613 | |||||
1614 | ExprResult | ||||
1615 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1616 | SourceLocation DefaultLoc, | ||||
1617 | SourceLocation RParenLoc, | ||||
1618 | Expr *ControllingExpr, | ||||
1619 | ArrayRef<ParsedType> ArgTypes, | ||||
1620 | ArrayRef<Expr *> ArgExprs) { | ||||
1621 | unsigned NumAssocs = ArgTypes.size(); | ||||
1622 | assert(NumAssocs == ArgExprs.size())(static_cast <bool> (NumAssocs == ArgExprs.size()) ? void (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1622, __extension__ __PRETTY_FUNCTION__)); | ||||
1623 | |||||
1624 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||
1625 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1626 | if (ArgTypes[i]) | ||||
1627 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||
1628 | else | ||||
1629 | Types[i] = nullptr; | ||||
1630 | } | ||||
1631 | |||||
1632 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||
1633 | ControllingExpr, | ||||
1634 | llvm::makeArrayRef(Types, NumAssocs), | ||||
1635 | ArgExprs); | ||||
1636 | delete [] Types; | ||||
1637 | return ER; | ||||
1638 | } | ||||
1639 | |||||
1640 | ExprResult | ||||
1641 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1642 | SourceLocation DefaultLoc, | ||||
1643 | SourceLocation RParenLoc, | ||||
1644 | Expr *ControllingExpr, | ||||
1645 | ArrayRef<TypeSourceInfo *> Types, | ||||
1646 | ArrayRef<Expr *> Exprs) { | ||||
1647 | unsigned NumAssocs = Types.size(); | ||||
1648 | assert(NumAssocs == Exprs.size())(static_cast <bool> (NumAssocs == Exprs.size()) ? void ( 0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1648, __extension__ __PRETTY_FUNCTION__)); | ||||
1649 | |||||
1650 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||
1651 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||
1652 | { | ||||
1653 | EnterExpressionEvaluationContext Unevaluated( | ||||
1654 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
1655 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||
1656 | if (R.isInvalid()) | ||||
1657 | return ExprError(); | ||||
1658 | ControllingExpr = R.get(); | ||||
1659 | } | ||||
1660 | |||||
1661 | // The controlling expression is an unevaluated operand, so side effects are | ||||
1662 | // likely unintended. | ||||
1663 | if (!inTemplateInstantiation() && | ||||
1664 | ControllingExpr->HasSideEffects(Context, false)) | ||||
1665 | Diag(ControllingExpr->getExprLoc(), | ||||
1666 | diag::warn_side_effects_unevaluated_context); | ||||
1667 | |||||
1668 | bool TypeErrorFound = false, | ||||
1669 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||
1670 | ContainsUnexpandedParameterPack | ||||
1671 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||
1672 | |||||
1673 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1674 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||
1675 | ContainsUnexpandedParameterPack = true; | ||||
1676 | |||||
1677 | if (Types[i]) { | ||||
1678 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||
1679 | ContainsUnexpandedParameterPack = true; | ||||
1680 | |||||
1681 | if (Types[i]->getType()->isDependentType()) { | ||||
1682 | IsResultDependent = true; | ||||
1683 | } else { | ||||
1684 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||
1685 | // complete object type other than a variably modified type." | ||||
1686 | unsigned D = 0; | ||||
1687 | if (Types[i]->getType()->isIncompleteType()) | ||||
1688 | D = diag::err_assoc_type_incomplete; | ||||
1689 | else if (!Types[i]->getType()->isObjectType()) | ||||
1690 | D = diag::err_assoc_type_nonobject; | ||||
1691 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||
1692 | D = diag::err_assoc_type_variably_modified; | ||||
1693 | |||||
1694 | if (D != 0) { | ||||
1695 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||
1696 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1697 | << Types[i]->getType(); | ||||
1698 | TypeErrorFound = true; | ||||
1699 | } | ||||
1700 | |||||
1701 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||
1702 | // selection shall specify compatible types." | ||||
1703 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||
1704 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||
1705 | Context.typesAreCompatible(Types[i]->getType(), | ||||
1706 | Types[j]->getType())) { | ||||
1707 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||
1708 | diag::err_assoc_compatible_types) | ||||
1709 | << Types[j]->getTypeLoc().getSourceRange() | ||||
1710 | << Types[j]->getType() | ||||
1711 | << Types[i]->getType(); | ||||
1712 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1713 | diag::note_compat_assoc) | ||||
1714 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1715 | << Types[i]->getType(); | ||||
1716 | TypeErrorFound = true; | ||||
1717 | } | ||||
1718 | } | ||||
1719 | } | ||||
1720 | } | ||||
1721 | if (TypeErrorFound) | ||||
1722 | return ExprError(); | ||||
1723 | |||||
1724 | // If we determined that the generic selection is result-dependent, don't | ||||
1725 | // try to compute the result expression. | ||||
1726 | if (IsResultDependent) | ||||
1727 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||
1728 | Exprs, DefaultLoc, RParenLoc, | ||||
1729 | ContainsUnexpandedParameterPack); | ||||
1730 | |||||
1731 | SmallVector<unsigned, 1> CompatIndices; | ||||
1732 | unsigned DefaultIndex = -1U; | ||||
1733 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1734 | if (!Types[i]) | ||||
1735 | DefaultIndex = i; | ||||
1736 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||
1737 | Types[i]->getType())) | ||||
1738 | CompatIndices.push_back(i); | ||||
1739 | } | ||||
1740 | |||||
1741 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||
1742 | // type compatible with at most one of the types named in its generic | ||||
1743 | // association list." | ||||
1744 | if (CompatIndices.size() > 1) { | ||||
1745 | // We strip parens here because the controlling expression is typically | ||||
1746 | // parenthesized in macro definitions. | ||||
1747 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1748 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||
1749 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||
1750 | << (unsigned)CompatIndices.size(); | ||||
1751 | for (unsigned I : CompatIndices) { | ||||
1752 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||
1753 | diag::note_compat_assoc) | ||||
1754 | << Types[I]->getTypeLoc().getSourceRange() | ||||
1755 | << Types[I]->getType(); | ||||
1756 | } | ||||
1757 | return ExprError(); | ||||
1758 | } | ||||
1759 | |||||
1760 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||
1761 | // its controlling expression shall have type compatible with exactly one of | ||||
1762 | // the types named in its generic association list." | ||||
1763 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||
1764 | // We strip parens here because the controlling expression is typically | ||||
1765 | // parenthesized in macro definitions. | ||||
1766 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1767 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||
1768 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||
1769 | return ExprError(); | ||||
1770 | } | ||||
1771 | |||||
1772 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||
1773 | // type name that is compatible with the type of the controlling expression, | ||||
1774 | // then the result expression of the generic selection is the expression | ||||
1775 | // in that generic association. Otherwise, the result expression of the | ||||
1776 | // generic selection is the expression in the default generic association." | ||||
1777 | unsigned ResultIndex = | ||||
1778 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||
1779 | |||||
1780 | return GenericSelectionExpr::Create( | ||||
1781 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||
1782 | ContainsUnexpandedParameterPack, ResultIndex); | ||||
1783 | } | ||||
1784 | |||||
1785 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||
1786 | /// location of the token and the offset of the ud-suffix within it. | ||||
1787 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||
1788 | unsigned Offset) { | ||||
1789 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||
1790 | S.getLangOpts()); | ||||
1791 | } | ||||
1792 | |||||
1793 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||
1794 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||
1795 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||
1796 | IdentifierInfo *UDSuffix, | ||||
1797 | SourceLocation UDSuffixLoc, | ||||
1798 | ArrayRef<Expr*> Args, | ||||
1799 | SourceLocation LitEndLoc) { | ||||
1800 | assert(Args.size() <= 2 && "too many arguments for literal operator")(static_cast <bool> (Args.size() <= 2 && "too many arguments for literal operator" ) ? void (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1800, __extension__ __PRETTY_FUNCTION__)); | ||||
1801 | |||||
1802 | QualType ArgTy[2]; | ||||
1803 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||
1804 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||
1805 | if (ArgTy[ArgIdx]->isArrayType()) | ||||
1806 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||
1807 | } | ||||
1808 | |||||
1809 | DeclarationName OpName = | ||||
1810 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1811 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1812 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1813 | |||||
1814 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||
1815 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||
1816 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||
1817 | /*AllowStringTemplatePack*/ false, | ||||
1818 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||
1819 | return ExprError(); | ||||
1820 | |||||
1821 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||
1822 | } | ||||
1823 | |||||
1824 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||
1825 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||
1826 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||
1827 | /// multiple tokens. However, the common case is that StringToks points to one | ||||
1828 | /// string. | ||||
1829 | /// | ||||
1830 | ExprResult | ||||
1831 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||
1832 | assert(!StringToks.empty() && "Must have at least one string!")(static_cast <bool> (!StringToks.empty() && "Must have at least one string!" ) ? void (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1832, __extension__ __PRETTY_FUNCTION__)); | ||||
1833 | |||||
1834 | StringLiteralParser Literal(StringToks, PP); | ||||
1835 | if (Literal.hadError) | ||||
1836 | return ExprError(); | ||||
1837 | |||||
1838 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||
1839 | for (const Token &Tok : StringToks) | ||||
1840 | StringTokLocs.push_back(Tok.getLocation()); | ||||
1841 | |||||
1842 | QualType CharTy = Context.CharTy; | ||||
1843 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||
1844 | if (Literal.isWide()) { | ||||
1845 | CharTy = Context.getWideCharType(); | ||||
1846 | Kind = StringLiteral::Wide; | ||||
1847 | } else if (Literal.isUTF8()) { | ||||
1848 | if (getLangOpts().Char8) | ||||
1849 | CharTy = Context.Char8Ty; | ||||
1850 | Kind = StringLiteral::UTF8; | ||||
1851 | } else if (Literal.isUTF16()) { | ||||
1852 | CharTy = Context.Char16Ty; | ||||
1853 | Kind = StringLiteral::UTF16; | ||||
1854 | } else if (Literal.isUTF32()) { | ||||
1855 | CharTy = Context.Char32Ty; | ||||
1856 | Kind = StringLiteral::UTF32; | ||||
1857 | } else if (Literal.isPascal()) { | ||||
1858 | CharTy = Context.UnsignedCharTy; | ||||
1859 | } | ||||
1860 | |||||
1861 | // Warn on initializing an array of char from a u8 string literal; this | ||||
1862 | // becomes ill-formed in C++2a. | ||||
1863 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||
1864 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||
1865 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||
1866 | |||||
1867 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||
1868 | // ensures C++2a compatibility (but may change the program behavior when | ||||
1869 | // built by non-Clang compilers for which the execution character set is | ||||
1870 | // not always UTF-8). | ||||
1871 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||
1872 | SourceLocation RemovalDiagLoc; | ||||
1873 | for (const Token &Tok : StringToks) { | ||||
1874 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||
1875 | if (RemovalDiagLoc.isInvalid()) | ||||
1876 | RemovalDiagLoc = Tok.getLocation(); | ||||
1877 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||
1878 | Tok.getLocation(), | ||||
1879 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||
1880 | getSourceManager(), getLangOpts()))); | ||||
1881 | } | ||||
1882 | } | ||||
1883 | Diag(RemovalDiagLoc, RemovalDiag); | ||||
1884 | } | ||||
1885 | |||||
1886 | QualType StrTy = | ||||
1887 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||
1888 | |||||
1889 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||
1890 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||
1891 | Kind, Literal.Pascal, StrTy, | ||||
1892 | &StringTokLocs[0], | ||||
1893 | StringTokLocs.size()); | ||||
1894 | if (Literal.getUDSuffix().empty()) | ||||
1895 | return Lit; | ||||
1896 | |||||
1897 | // We're building a user-defined literal. | ||||
1898 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
1899 | SourceLocation UDSuffixLoc = | ||||
1900 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||
1901 | Literal.getUDSuffixOffset()); | ||||
1902 | |||||
1903 | // Make sure we're allowed user-defined literals here. | ||||
1904 | if (!UDLScope) | ||||
1905 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||
1906 | |||||
1907 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||
1908 | // operator "" X (str, len) | ||||
1909 | QualType SizeType = Context.getSizeType(); | ||||
1910 | |||||
1911 | DeclarationName OpName = | ||||
1912 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1913 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1914 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1915 | |||||
1916 | QualType ArgTy[] = { | ||||
1917 | Context.getArrayDecayedType(StrTy), SizeType | ||||
1918 | }; | ||||
1919 | |||||
1920 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
1921 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||
1922 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||
1923 | /*AllowStringTemplatePack*/ true, | ||||
1924 | /*DiagnoseMissing*/ true, Lit)) { | ||||
1925 | |||||
1926 | case LOLR_Cooked: { | ||||
1927 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||
1928 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||
1929 | StringTokLocs[0]); | ||||
1930 | Expr *Args[] = { Lit, LenArg }; | ||||
1931 | |||||
1932 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||
1933 | } | ||||
1934 | |||||
1935 | case LOLR_Template: { | ||||
1936 | TemplateArgumentListInfo ExplicitArgs; | ||||
1937 | TemplateArgument Arg(Lit); | ||||
1938 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||
1939 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1940 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1941 | &ExplicitArgs); | ||||
1942 | } | ||||
1943 | |||||
1944 | case LOLR_StringTemplatePack: { | ||||
1945 | TemplateArgumentListInfo ExplicitArgs; | ||||
1946 | |||||
1947 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||
1948 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||
1949 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
1950 | |||||
1951 | TemplateArgument TypeArg(CharTy); | ||||
1952 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||
1953 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||
1954 | |||||
1955 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||
1956 | Value = Lit->getCodeUnit(I); | ||||
1957 | TemplateArgument Arg(Context, Value, CharTy); | ||||
1958 | TemplateArgumentLocInfo ArgInfo; | ||||
1959 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1960 | } | ||||
1961 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1962 | &ExplicitArgs); | ||||
1963 | } | ||||
1964 | case LOLR_Raw: | ||||
1965 | case LOLR_ErrorNoDiagnostic: | ||||
1966 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1966); | ||||
1967 | case LOLR_Error: | ||||
1968 | return ExprError(); | ||||
1969 | } | ||||
1970 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1970); | ||||
1971 | } | ||||
1972 | |||||
1973 | DeclRefExpr * | ||||
1974 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1975 | SourceLocation Loc, | ||||
1976 | const CXXScopeSpec *SS) { | ||||
1977 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||
1978 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||
1979 | } | ||||
1980 | |||||
1981 | DeclRefExpr * | ||||
1982 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1983 | const DeclarationNameInfo &NameInfo, | ||||
1984 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||
1985 | SourceLocation TemplateKWLoc, | ||||
1986 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
1987 | NestedNameSpecifierLoc NNS = | ||||
1988 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||
1989 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||
1990 | TemplateArgs); | ||||
1991 | } | ||||
1992 | |||||
1993 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||
1994 | // host variable in a device or host device lambda. | ||||
1995 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||
1996 | VarDecl *VD) { | ||||
1997 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||
1998 | return false; | ||||
1999 | assert(VD->getType()->isReferenceType())(static_cast <bool> (VD->getType()->isReferenceType ()) ? void (0) : __assert_fail ("VD->getType()->isReferenceType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 1999, __extension__ __PRETTY_FUNCTION__)); | ||||
2000 | |||||
2001 | // Check whether the reference variable is referencing a host variable. | ||||
2002 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||
2003 | if (!DRE) | ||||
2004 | return false; | ||||
2005 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
2006 | if (!Referee || !Referee->hasGlobalStorage() || | ||||
2007 | Referee->hasAttr<CUDADeviceAttr>()) | ||||
2008 | return false; | ||||
2009 | |||||
2010 | // Check whether the current function is a device or host device lambda. | ||||
2011 | // Check whether the reference variable is a capture by getDeclContext() | ||||
2012 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||
2013 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||
2014 | if (MD && MD->getParent()->isLambda() && | ||||
2015 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||
2016 | VD->getDeclContext() != MD) | ||||
2017 | return true; | ||||
2018 | |||||
2019 | return false; | ||||
2020 | } | ||||
2021 | |||||
2022 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||
2023 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||
2024 | if (isUnevaluatedContext()) | ||||
2025 | return NOUR_Unevaluated; | ||||
2026 | |||||
2027 | // C++2a [basic.def.odr]p4: | ||||
2028 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
2029 | // is odr-used by e unless [...] x is a reference that is usable in | ||||
2030 | // constant expressions. | ||||
2031 | // CUDA/HIP: | ||||
2032 | // If a reference variable referencing a host variable is captured in a | ||||
2033 | // device or host device lambda, the value of the referee must be copied | ||||
2034 | // to the capture and the reference variable must be treated as odr-use | ||||
2035 | // since the value of the referee is not known at compile time and must | ||||
2036 | // be loaded from the captured. | ||||
2037 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2038 | if (VD->getType()->isReferenceType() && | ||||
2039 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||
2040 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||
2041 | VD->isUsableInConstantExpressions(Context)) | ||||
2042 | return NOUR_Constant; | ||||
2043 | } | ||||
2044 | |||||
2045 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||
2046 | // need to wait and see how the expression is used. | ||||
2047 | return NOUR_None; | ||||
2048 | } | ||||
2049 | |||||
2050 | /// BuildDeclRefExpr - Build an expression that references a | ||||
2051 | /// declaration that does not require a closure capture. | ||||
2052 | DeclRefExpr * | ||||
2053 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2054 | const DeclarationNameInfo &NameInfo, | ||||
2055 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||
2056 | SourceLocation TemplateKWLoc, | ||||
2057 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2058 | bool RefersToCapturedVariable = | ||||
2059 | isa<VarDecl>(D) && | ||||
2060 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||
2061 | |||||
2062 | DeclRefExpr *E = DeclRefExpr::Create( | ||||
2063 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||
2064 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||
2065 | MarkDeclRefReferenced(E); | ||||
2066 | |||||
2067 | // C++ [except.spec]p17: | ||||
2068 | // An exception-specification is considered to be needed when: | ||||
2069 | // - in an expression, the function is the unique lookup result or | ||||
2070 | // the selected member of a set of overloaded functions. | ||||
2071 | // | ||||
2072 | // We delay doing this until after we've built the function reference and | ||||
2073 | // marked it as used so that: | ||||
2074 | // a) if the function is defaulted, we get errors from defining it before / | ||||
2075 | // instead of errors from computing its exception specification, and | ||||
2076 | // b) if the function is a defaulted comparison, we can use the body we | ||||
2077 | // build when defining it as input to the exception specification | ||||
2078 | // computation rather than computing a new body. | ||||
2079 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||
2080 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||
2081 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||
2082 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||
2083 | } | ||||
2084 | } | ||||
2085 | |||||
2086 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||
2087 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||
2088 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||
2089 | getCurFunction()->recordUseOfWeak(E); | ||||
2090 | |||||
2091 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
2092 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||
2093 | FD = IFD->getAnonField(); | ||||
2094 | if (FD) { | ||||
2095 | UnusedPrivateFields.remove(FD); | ||||
2096 | // Just in case we're building an illegal pointer-to-member. | ||||
2097 | if (FD->isBitField()) | ||||
2098 | E->setObjectKind(OK_BitField); | ||||
2099 | } | ||||
2100 | |||||
2101 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||
2102 | // designates a bit-field. | ||||
2103 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||
2104 | if (auto *BE = BD->getBinding()) | ||||
2105 | E->setObjectKind(BE->getObjectKind()); | ||||
2106 | |||||
2107 | return E; | ||||
2108 | } | ||||
2109 | |||||
2110 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||
2111 | /// possibly a list of template arguments. | ||||
2112 | /// | ||||
2113 | /// If this produces template arguments, it is permitted to call | ||||
2114 | /// DecomposeTemplateName. | ||||
2115 | /// | ||||
2116 | /// This actually loses a lot of source location information for | ||||
2117 | /// non-standard name kinds; we should consider preserving that in | ||||
2118 | /// some way. | ||||
2119 | void | ||||
2120 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||
2121 | TemplateArgumentListInfo &Buffer, | ||||
2122 | DeclarationNameInfo &NameInfo, | ||||
2123 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||
2124 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
2125 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||
2126 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||
2127 | |||||
2128 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||
2129 | Id.TemplateId->NumArgs); | ||||
2130 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||
2131 | |||||
2132 | TemplateName TName = Id.TemplateId->Template.get(); | ||||
2133 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||
2134 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||
2135 | TemplateArgs = &Buffer; | ||||
2136 | } else { | ||||
2137 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||
2138 | TemplateArgs = nullptr; | ||||
2139 | } | ||||
2140 | } | ||||
2141 | |||||
2142 | static void emitEmptyLookupTypoDiagnostic( | ||||
2143 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||
2144 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||
2145 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||
2146 | DeclContext *Ctx = | ||||
2147 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||
2148 | if (!TC) { | ||||
2149 | // Emit a special diagnostic for failed member lookups. | ||||
2150 | // FIXME: computing the declaration context might fail here (?) | ||||
2151 | if (Ctx) | ||||
2152 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||
2153 | << SS.getRange(); | ||||
2154 | else | ||||
2155 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||
2156 | return; | ||||
2157 | } | ||||
2158 | |||||
2159 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||
2160 | bool DroppedSpecifier = | ||||
2161 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||
2162 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2163 | ? diag::note_implicit_param_decl | ||||
2164 | : diag::note_previous_decl; | ||||
2165 | if (!Ctx) | ||||
2166 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||
2167 | SemaRef.PDiag(NoteID)); | ||||
2168 | else | ||||
2169 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||
2170 | << Typo << Ctx << DroppedSpecifier | ||||
2171 | << SS.getRange(), | ||||
2172 | SemaRef.PDiag(NoteID)); | ||||
2173 | } | ||||
2174 | |||||
2175 | /// Diagnose a lookup that found results in an enclosing class during error | ||||
2176 | /// recovery. This usually indicates that the results were found in a dependent | ||||
2177 | /// base class that could not be searched as part of a template definition. | ||||
2178 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||
2179 | /// compatibility mode). | ||||
2180 | /// | ||||
2181 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||
2182 | /// should attempt to recover using these lookup results. | ||||
2183 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||
2184 | // During a default argument instantiation the CurContext points | ||||
2185 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||
2186 | // function parameter list, hence add an explicit check. | ||||
2187 | bool isDefaultArgument = | ||||
2188 | !CodeSynthesisContexts.empty() && | ||||
2189 | CodeSynthesisContexts.back().Kind == | ||||
2190 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||
2191 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||
2192 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||
2193 | R.getNamingClass() == CurMethod->getParent() && | ||||
2194 | !isDefaultArgument; | ||||
2195 | |||||
2196 | // There are two ways we can find a class-scope declaration during template | ||||
2197 | // instantiation that we did not find in the template definition: if it is a | ||||
2198 | // member of a dependent base class, or if it is declared after the point of | ||||
2199 | // use in the same class. Distinguish these by comparing the class in which | ||||
2200 | // the member was found to the naming class of the lookup. | ||||
2201 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||
2202 | unsigned NoteID = diag::note_member_declared_at; | ||||
2203 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||
2204 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||
2205 | : diag::err_found_later_in_class; | ||||
2206 | } else if (getLangOpts().MSVCCompat) { | ||||
2207 | DiagID = diag::ext_found_in_dependent_base; | ||||
2208 | NoteID = diag::note_dependent_member_use; | ||||
2209 | } | ||||
2210 | |||||
2211 | if (isInstance) { | ||||
2212 | // Give a code modification hint to insert 'this->'. | ||||
2213 | Diag(R.getNameLoc(), DiagID) | ||||
2214 | << R.getLookupName() | ||||
2215 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||
2216 | CheckCXXThisCapture(R.getNameLoc()); | ||||
2217 | } else { | ||||
2218 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||
2219 | // they're not shadowed). | ||||
2220 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||
2221 | } | ||||
2222 | |||||
2223 | for (NamedDecl *D : R) | ||||
2224 | Diag(D->getLocation(), NoteID); | ||||
2225 | |||||
2226 | // Return true if we are inside a default argument instantiation | ||||
2227 | // and the found name refers to an instance member function, otherwise | ||||
2228 | // the caller will try to create an implicit member call and this is wrong | ||||
2229 | // for default arguments. | ||||
2230 | // | ||||
2231 | // FIXME: Is this special case necessary? We could allow the caller to | ||||
2232 | // diagnose this. | ||||
2233 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||
2234 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||
2235 | return true; | ||||
2236 | } | ||||
2237 | |||||
2238 | // Tell the callee to try to recover. | ||||
2239 | return false; | ||||
2240 | } | ||||
2241 | |||||
2242 | /// Diagnose an empty lookup. | ||||
2243 | /// | ||||
2244 | /// \return false if new lookup candidates were found | ||||
2245 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||
2246 | CorrectionCandidateCallback &CCC, | ||||
2247 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||
2248 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||
2249 | DeclarationName Name = R.getLookupName(); | ||||
2250 | |||||
2251 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||
2252 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||
2253 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||
2254 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||
2255 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
2256 | diagnostic = diag::err_undeclared_use; | ||||
2257 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||
2258 | } | ||||
2259 | |||||
2260 | // If the original lookup was an unqualified lookup, fake an | ||||
2261 | // unqualified lookup. This is useful when (for example) the | ||||
2262 | // original lookup would not have found something because it was a | ||||
2263 | // dependent name. | ||||
2264 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||
2265 | while (DC) { | ||||
2266 | if (isa<CXXRecordDecl>(DC)) { | ||||
2267 | LookupQualifiedName(R, DC); | ||||
2268 | |||||
2269 | if (!R.empty()) { | ||||
2270 | // Don't give errors about ambiguities in this lookup. | ||||
2271 | R.suppressDiagnostics(); | ||||
2272 | |||||
2273 | // If there's a best viable function among the results, only mention | ||||
2274 | // that one in the notes. | ||||
2275 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||
2276 | OverloadCandidateSet::CSK_Normal); | ||||
2277 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||
2278 | OverloadCandidateSet::iterator Best; | ||||
2279 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||
2280 | OR_Success) { | ||||
2281 | R.clear(); | ||||
2282 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||
2283 | R.resolveKind(); | ||||
2284 | } | ||||
2285 | |||||
2286 | return DiagnoseDependentMemberLookup(R); | ||||
2287 | } | ||||
2288 | |||||
2289 | R.clear(); | ||||
2290 | } | ||||
2291 | |||||
2292 | DC = DC->getLookupParent(); | ||||
2293 | } | ||||
2294 | |||||
2295 | // We didn't find anything, so try to correct for a typo. | ||||
2296 | TypoCorrection Corrected; | ||||
2297 | if (S && Out) { | ||||
2298 | SourceLocation TypoLoc = R.getNameLoc(); | ||||
2299 | assert(!ExplicitTemplateArgs &&(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2300, __extension__ __PRETTY_FUNCTION__)) | ||||
2300 | "Diagnosing an empty lookup with explicit template args!")(static_cast <bool> (!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? void (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2300, __extension__ __PRETTY_FUNCTION__)); | ||||
2301 | *Out = CorrectTypoDelayed( | ||||
2302 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
2303 | [=](const TypoCorrection &TC) { | ||||
2304 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||
2305 | diagnostic, diagnostic_suggest); | ||||
2306 | }, | ||||
2307 | nullptr, CTK_ErrorRecovery); | ||||
2308 | if (*Out) | ||||
2309 | return true; | ||||
2310 | } else if (S && | ||||
2311 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||
2312 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||
2313 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
2314 | bool DroppedSpecifier = | ||||
2315 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||
2316 | R.setLookupName(Corrected.getCorrection()); | ||||
2317 | |||||
2318 | bool AcceptableWithRecovery = false; | ||||
2319 | bool AcceptableWithoutRecovery = false; | ||||
2320 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||
2321 | if (ND) { | ||||
2322 | if (Corrected.isOverloaded()) { | ||||
2323 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||
2324 | OverloadCandidateSet::CSK_Normal); | ||||
2325 | OverloadCandidateSet::iterator Best; | ||||
2326 | for (NamedDecl *CD : Corrected) { | ||||
2327 | if (FunctionTemplateDecl *FTD = | ||||
2328 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||
2329 | AddTemplateOverloadCandidate( | ||||
2330 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||
2331 | Args, OCS); | ||||
2332 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
2333 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||
2334 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||
2335 | Args, OCS); | ||||
2336 | } | ||||
2337 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||
2338 | case OR_Success: | ||||
2339 | ND = Best->FoundDecl; | ||||
2340 | Corrected.setCorrectionDecl(ND); | ||||
2341 | break; | ||||
2342 | default: | ||||
2343 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||
2344 | Corrected.setCorrectionDecl(ND); | ||||
2345 | break; | ||||
2346 | } | ||||
2347 | } | ||||
2348 | R.addDecl(ND); | ||||
2349 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||
2350 | CXXRecordDecl *Record = nullptr; | ||||
2351 | if (Corrected.getCorrectionSpecifier()) { | ||||
2352 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||
2353 | Record = Ty->getAsCXXRecordDecl(); | ||||
2354 | } | ||||
2355 | if (!Record) | ||||
2356 | Record = cast<CXXRecordDecl>( | ||||
2357 | ND->getDeclContext()->getRedeclContext()); | ||||
2358 | R.setNamingClass(Record); | ||||
2359 | } | ||||
2360 | |||||
2361 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||
2362 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||
2363 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||
2364 | // FIXME: If we ended up with a typo for a type name or | ||||
2365 | // Objective-C class name, we're in trouble because the parser | ||||
2366 | // is in the wrong place to recover. Suggest the typo | ||||
2367 | // correction, but don't make it a fix-it since we're not going | ||||
2368 | // to recover well anyway. | ||||
2369 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||
2370 | getAsTypeTemplateDecl(UnderlyingND) || | ||||
2371 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||
2372 | } else { | ||||
2373 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||
2374 | // because we aren't able to recover. | ||||
2375 | AcceptableWithoutRecovery = true; | ||||
2376 | } | ||||
2377 | |||||
2378 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||
2379 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2380 | ? diag::note_implicit_param_decl | ||||
2381 | : diag::note_previous_decl; | ||||
2382 | if (SS.isEmpty()) | ||||
2383 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||
2384 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2385 | else | ||||
2386 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
2387 | << Name << computeDeclContext(SS, false) | ||||
2388 | << DroppedSpecifier << SS.getRange(), | ||||
2389 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2390 | |||||
2391 | // Tell the callee whether to try to recover. | ||||
2392 | return !AcceptableWithRecovery; | ||||
2393 | } | ||||
2394 | } | ||||
2395 | R.clear(); | ||||
2396 | |||||
2397 | // Emit a special diagnostic for failed member lookups. | ||||
2398 | // FIXME: computing the declaration context might fail here (?) | ||||
2399 | if (!SS.isEmpty()) { | ||||
2400 | Diag(R.getNameLoc(), diag::err_no_member) | ||||
2401 | << Name << computeDeclContext(SS, false) | ||||
2402 | << SS.getRange(); | ||||
2403 | return true; | ||||
2404 | } | ||||
2405 | |||||
2406 | // Give up, we can't recover. | ||||
2407 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||
2408 | return true; | ||||
2409 | } | ||||
2410 | |||||
2411 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||
2412 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||
2413 | /// assume the identifier is a member of a dependent base class. We can only | ||||
2414 | /// recover successfully in static methods, instance methods, and other contexts | ||||
2415 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||
2416 | /// instantiation model, but it's close enough. | ||||
2417 | static Expr * | ||||
2418 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||
2419 | DeclarationNameInfo &NameInfo, | ||||
2420 | SourceLocation TemplateKWLoc, | ||||
2421 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2422 | // Only try to recover from lookup into dependent bases in static methods or | ||||
2423 | // contexts where 'this' is available. | ||||
2424 | QualType ThisType = S.getCurrentThisType(); | ||||
2425 | const CXXRecordDecl *RD = nullptr; | ||||
2426 | if (!ThisType.isNull()) | ||||
2427 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||
2428 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||
2429 | RD = MD->getParent(); | ||||
2430 | if (!RD || !RD->hasAnyDependentBases()) | ||||
2431 | return nullptr; | ||||
2432 | |||||
2433 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||
2434 | // is available, suggest inserting 'this->' as a fixit. | ||||
2435 | SourceLocation Loc = NameInfo.getLoc(); | ||||
2436 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||
2437 | DB << NameInfo.getName() << RD; | ||||
2438 | |||||
2439 | if (!ThisType.isNull()) { | ||||
2440 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||
2441 | return CXXDependentScopeMemberExpr::Create( | ||||
2442 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||
2443 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||
2444 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||
2445 | } | ||||
2446 | |||||
2447 | // Synthesize a fake NNS that points to the derived class. This will | ||||
2448 | // perform name lookup during template instantiation. | ||||
2449 | CXXScopeSpec SS; | ||||
2450 | auto *NNS = | ||||
2451 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||
2452 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||
2453 | return DependentScopeDeclRefExpr::Create( | ||||
2454 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||
2455 | TemplateArgs); | ||||
2456 | } | ||||
2457 | |||||
2458 | ExprResult | ||||
2459 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||
2460 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||
2461 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||
2462 | CorrectionCandidateCallback *CCC, | ||||
2463 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||
2464 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2465, __extension__ __PRETTY_FUNCTION__)) | ||||
2465 | "cannot be direct & operand and have a trailing lparen")(static_cast <bool> (!(IsAddressOfOperand && HasTrailingLParen ) && "cannot be direct & operand and have a trailing lparen" ) ? void (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2465, __extension__ __PRETTY_FUNCTION__)); | ||||
2466 | if (SS.isInvalid()) | ||||
2467 | return ExprError(); | ||||
2468 | |||||
2469 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||
2470 | |||||
2471 | // Decompose the UnqualifiedId into the following data. | ||||
2472 | DeclarationNameInfo NameInfo; | ||||
2473 | const TemplateArgumentListInfo *TemplateArgs; | ||||
2474 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||
2475 | |||||
2476 | DeclarationName Name = NameInfo.getName(); | ||||
2477 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
2478 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||
2479 | |||||
2480 | if (II && II->isEditorPlaceholder()) { | ||||
2481 | // FIXME: When typed placeholders are supported we can create a typed | ||||
2482 | // placeholder expression node. | ||||
2483 | return ExprError(); | ||||
2484 | } | ||||
2485 | |||||
2486 | // C++ [temp.dep.expr]p3: | ||||
2487 | // An id-expression is type-dependent if it contains: | ||||
2488 | // -- an identifier that was declared with a dependent type, | ||||
2489 | // (note: handled after lookup) | ||||
2490 | // -- a template-id that is dependent, | ||||
2491 | // (note: handled in BuildTemplateIdExpr) | ||||
2492 | // -- a conversion-function-id that specifies a dependent type, | ||||
2493 | // -- a nested-name-specifier that contains a class-name that | ||||
2494 | // names a dependent type. | ||||
2495 | // Determine whether this is a member of an unknown specialization; | ||||
2496 | // we need to handle these differently. | ||||
2497 | bool DependentID = false; | ||||
2498 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||
2499 | Name.getCXXNameType()->isDependentType()) { | ||||
2500 | DependentID = true; | ||||
2501 | } else if (SS.isSet()) { | ||||
2502 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||
2503 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2504 | return ExprError(); | ||||
2505 | } else { | ||||
2506 | DependentID = true; | ||||
2507 | } | ||||
2508 | } | ||||
2509 | |||||
2510 | if (DependentID) | ||||
2511 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2512 | IsAddressOfOperand, TemplateArgs); | ||||
2513 | |||||
2514 | // Perform the required lookup. | ||||
2515 | LookupResult R(*this, NameInfo, | ||||
2516 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||
2517 | ? LookupObjCImplicitSelfParam | ||||
2518 | : LookupOrdinaryName); | ||||
2519 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||
2520 | // Lookup the template name again to correctly establish the context in | ||||
2521 | // which it was found. This is really unfortunate as we already did the | ||||
2522 | // lookup to determine that it was a template name in the first place. If | ||||
2523 | // this becomes a performance hit, we can work harder to preserve those | ||||
2524 | // results until we get here but it's likely not worth it. | ||||
2525 | bool MemberOfUnknownSpecialization; | ||||
2526 | AssumedTemplateKind AssumedTemplate; | ||||
2527 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||
2528 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||
2529 | &AssumedTemplate)) | ||||
2530 | return ExprError(); | ||||
2531 | |||||
2532 | if (MemberOfUnknownSpecialization || | ||||
2533 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||
2534 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2535 | IsAddressOfOperand, TemplateArgs); | ||||
2536 | } else { | ||||
2537 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||
2538 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||
2539 | |||||
2540 | // If the result might be in a dependent base class, this is a dependent | ||||
2541 | // id-expression. | ||||
2542 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2543 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2544 | IsAddressOfOperand, TemplateArgs); | ||||
2545 | |||||
2546 | // If this reference is in an Objective-C method, then we need to do | ||||
2547 | // some special Objective-C lookup, too. | ||||
2548 | if (IvarLookupFollowUp) { | ||||
2549 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||
2550 | if (E.isInvalid()) | ||||
2551 | return ExprError(); | ||||
2552 | |||||
2553 | if (Expr *Ex = E.getAs<Expr>()) | ||||
2554 | return Ex; | ||||
2555 | } | ||||
2556 | } | ||||
2557 | |||||
2558 | if (R.isAmbiguous()) | ||||
2559 | return ExprError(); | ||||
2560 | |||||
2561 | // This could be an implicitly declared function reference (legal in C90, | ||||
2562 | // extension in C99, forbidden in C++). | ||||
2563 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||
2564 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||
2565 | if (D) R.addDecl(D); | ||||
2566 | } | ||||
2567 | |||||
2568 | // Determine whether this name might be a candidate for | ||||
2569 | // argument-dependent lookup. | ||||
2570 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||
2571 | |||||
2572 | if (R.empty() && !ADL) { | ||||
2573 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
2574 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||
2575 | TemplateKWLoc, TemplateArgs)) | ||||
2576 | return E; | ||||
2577 | } | ||||
2578 | |||||
2579 | // Don't diagnose an empty lookup for inline assembly. | ||||
2580 | if (IsInlineAsmIdentifier) | ||||
2581 | return ExprError(); | ||||
2582 | |||||
2583 | // If this name wasn't predeclared and if this is not a function | ||||
2584 | // call, diagnose the problem. | ||||
2585 | TypoExpr *TE = nullptr; | ||||
2586 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||
2587 | : nullptr); | ||||
2588 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||
2589 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2590, __extension__ __PRETTY_FUNCTION__)) | ||||
2590 | "Typo correction callback misconfigured")(static_cast <bool> ((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured" ) ? void (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2590, __extension__ __PRETTY_FUNCTION__)); | ||||
2591 | if (CCC) { | ||||
2592 | // Make sure the callback knows what the typo being diagnosed is. | ||||
2593 | CCC->setTypoName(II); | ||||
2594 | if (SS.isValid()) | ||||
2595 | CCC->setTypoNNS(SS.getScopeRep()); | ||||
2596 | } | ||||
2597 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||
2598 | // a template name, but we happen to have always already looked up the name | ||||
2599 | // before we get here if it must be a template name. | ||||
2600 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||
2601 | None, &TE)) { | ||||
2602 | if (TE && KeywordReplacement) { | ||||
2603 | auto &State = getTypoExprState(TE); | ||||
2604 | auto BestTC = State.Consumer->getNextCorrection(); | ||||
2605 | if (BestTC.isKeyword()) { | ||||
2606 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||
2607 | if (State.DiagHandler) | ||||
2608 | State.DiagHandler(BestTC); | ||||
2609 | KeywordReplacement->startToken(); | ||||
2610 | KeywordReplacement->setKind(II->getTokenID()); | ||||
2611 | KeywordReplacement->setIdentifierInfo(II); | ||||
2612 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||
2613 | // Clean up the state associated with the TypoExpr, since it has | ||||
2614 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||
2615 | clearDelayedTypo(TE); | ||||
2616 | // Signal that a correction to a keyword was performed by returning a | ||||
2617 | // valid-but-null ExprResult. | ||||
2618 | return (Expr*)nullptr; | ||||
2619 | } | ||||
2620 | State.Consumer->resetCorrectionStream(); | ||||
2621 | } | ||||
2622 | return TE ? TE : ExprError(); | ||||
2623 | } | ||||
2624 | |||||
2625 | assert(!R.empty() &&(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2626, __extension__ __PRETTY_FUNCTION__)) | ||||
2626 | "DiagnoseEmptyLookup returned false but added no results")(static_cast <bool> (!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? void (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2626, __extension__ __PRETTY_FUNCTION__)); | ||||
2627 | |||||
2628 | // If we found an Objective-C instance variable, let | ||||
2629 | // LookupInObjCMethod build the appropriate expression to | ||||
2630 | // reference the ivar. | ||||
2631 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||
2632 | R.clear(); | ||||
2633 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||
2634 | // In a hopelessly buggy code, Objective-C instance variable | ||||
2635 | // lookup fails and no expression will be built to reference it. | ||||
2636 | if (!E.isInvalid() && !E.get()) | ||||
2637 | return ExprError(); | ||||
2638 | return E; | ||||
2639 | } | ||||
2640 | } | ||||
2641 | |||||
2642 | // This is guaranteed from this point on. | ||||
2643 | assert(!R.empty() || ADL)(static_cast <bool> (!R.empty() || ADL) ? void (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2643, __extension__ __PRETTY_FUNCTION__)); | ||||
2644 | |||||
2645 | // Check whether this might be a C++ implicit instance member access. | ||||
2646 | // C++ [class.mfct.non-static]p3: | ||||
2647 | // When an id-expression that is not part of a class member access | ||||
2648 | // syntax and not used to form a pointer to member is used in the | ||||
2649 | // body of a non-static member function of class X, if name lookup | ||||
2650 | // resolves the name in the id-expression to a non-static non-type | ||||
2651 | // member of some class C, the id-expression is transformed into a | ||||
2652 | // class member access expression using (*this) as the | ||||
2653 | // postfix-expression to the left of the . operator. | ||||
2654 | // | ||||
2655 | // But we don't actually need to do this for '&' operands if R | ||||
2656 | // resolved to a function or overloaded function set, because the | ||||
2657 | // expression is ill-formed if it actually works out to be a | ||||
2658 | // non-static member function: | ||||
2659 | // | ||||
2660 | // C++ [expr.ref]p4: | ||||
2661 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||
2662 | // [t]he expression can be used only as the left-hand operand of a | ||||
2663 | // member function call. | ||||
2664 | // | ||||
2665 | // There are other safeguards against such uses, but it's important | ||||
2666 | // to get this right here so that we don't end up making a | ||||
2667 | // spuriously dependent expression if we're inside a dependent | ||||
2668 | // instance method. | ||||
2669 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||
2670 | bool MightBeImplicitMember; | ||||
2671 | if (!IsAddressOfOperand) | ||||
2672 | MightBeImplicitMember = true; | ||||
2673 | else if (!SS.isEmpty()) | ||||
2674 | MightBeImplicitMember = false; | ||||
2675 | else if (R.isOverloadedResult()) | ||||
2676 | MightBeImplicitMember = false; | ||||
2677 | else if (R.isUnresolvableResult()) | ||||
2678 | MightBeImplicitMember = true; | ||||
2679 | else | ||||
2680 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||
2681 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||
2682 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||
2683 | |||||
2684 | if (MightBeImplicitMember) | ||||
2685 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||
2686 | R, TemplateArgs, S); | ||||
2687 | } | ||||
2688 | |||||
2689 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||
2690 | |||||
2691 | // In C++1y, if this is a variable template id, then check it | ||||
2692 | // in BuildTemplateIdExpr(). | ||||
2693 | // The single lookup result must be a variable template declaration. | ||||
2694 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||
2695 | Id.TemplateId->Kind == TNK_Var_template) { | ||||
2696 | assert(R.getAsSingle<VarTemplateDecl>() &&(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2697, __extension__ __PRETTY_FUNCTION__)) | ||||
2697 | "There should only be one declaration found.")(static_cast <bool> (R.getAsSingle<VarTemplateDecl> () && "There should only be one declaration found.") ? void (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2697, __extension__ __PRETTY_FUNCTION__)); | ||||
2698 | } | ||||
2699 | |||||
2700 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||
2701 | } | ||||
2702 | |||||
2703 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||
2704 | } | ||||
2705 | |||||
2706 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||
2707 | /// declaration name, generally during template instantiation. | ||||
2708 | /// There's a large number of things which don't need to be done along | ||||
2709 | /// this path. | ||||
2710 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||
2711 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||
2712 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||
2713 | DeclContext *DC = computeDeclContext(SS, false); | ||||
2714 | if (!DC) | ||||
2715 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2716 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2717 | |||||
2718 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2719 | return ExprError(); | ||||
2720 | |||||
2721 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
2722 | LookupQualifiedName(R, DC); | ||||
2723 | |||||
2724 | if (R.isAmbiguous()) | ||||
2725 | return ExprError(); | ||||
2726 | |||||
2727 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2728 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2729 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2730 | |||||
2731 | if (R.empty()) { | ||||
2732 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||
2733 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||
2734 | // is invalid because it's derived from an invalid base class, then missing | ||||
2735 | // members were likely supposed to be inherited. | ||||
2736 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||
2737 | if (CD->isInvalidDecl()) | ||||
2738 | return ExprError(); | ||||
2739 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||
2740 | << NameInfo.getName() << DC << SS.getRange(); | ||||
2741 | return ExprError(); | ||||
2742 | } | ||||
2743 | |||||
2744 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||
2745 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||
2746 | // a dependent context. If we can recover with a type, downgrade this to | ||||
2747 | // a warning in Microsoft compatibility mode. | ||||
2748 | unsigned DiagID = diag::err_typename_missing; | ||||
2749 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||
2750 | DiagID = diag::ext_typename_missing; | ||||
2751 | SourceLocation Loc = SS.getBeginLoc(); | ||||
2752 | auto D = Diag(Loc, DiagID); | ||||
2753 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||
2754 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||
2755 | |||||
2756 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||
2757 | // context. | ||||
2758 | if (!RecoveryTSI) | ||||
2759 | return ExprError(); | ||||
2760 | |||||
2761 | // Only issue the fixit if we're prepared to recover. | ||||
2762 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||
2763 | |||||
2764 | // Recover by pretending this was an elaborated type. | ||||
2765 | QualType Ty = Context.getTypeDeclType(TD); | ||||
2766 | TypeLocBuilder TLB; | ||||
2767 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||
2768 | |||||
2769 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||
2770 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||
2771 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
2772 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
2773 | |||||
2774 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||
2775 | |||||
2776 | return ExprEmpty(); | ||||
2777 | } | ||||
2778 | |||||
2779 | // Defend against this resolving to an implicit member access. We usually | ||||
2780 | // won't get here if this might be a legitimate a class member (we end up in | ||||
2781 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||
2782 | // a pointer-to-member or in an unevaluated context in C++11. | ||||
2783 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||
2784 | return BuildPossibleImplicitMemberExpr(SS, | ||||
2785 | /*TemplateKWLoc=*/SourceLocation(), | ||||
2786 | R, /*TemplateArgs=*/nullptr, S); | ||||
2787 | |||||
2788 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||
2789 | } | ||||
2790 | |||||
2791 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2792 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2793 | /// should form a reference to an ivar. | ||||
2794 | /// | ||||
2795 | /// Ideally, most of this would be done by lookup, but there's | ||||
2796 | /// actually quite a lot of extra work involved. | ||||
2797 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2798 | IdentifierInfo *II) { | ||||
2799 | SourceLocation Loc = Lookup.getNameLoc(); | ||||
2800 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2801 | |||||
2802 | // Check for error condition which is already reported. | ||||
2803 | if (!CurMethod) | ||||
2804 | return DeclResult(true); | ||||
2805 | |||||
2806 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||
2807 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||
2808 | // found a decl, but that decl is outside the current instance method (i.e. | ||||
2809 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||
2810 | // this name, if the lookup sucedes, we replace it our current decl. | ||||
2811 | |||||
2812 | // If we're in a class method, we don't normally want to look for | ||||
2813 | // ivars. But if we don't find anything else, and there's an | ||||
2814 | // ivar, that's an error. | ||||
2815 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||
2816 | |||||
2817 | bool LookForIvars; | ||||
2818 | if (Lookup.empty()) | ||||
2819 | LookForIvars = true; | ||||
2820 | else if (IsClassMethod) | ||||
2821 | LookForIvars = false; | ||||
2822 | else | ||||
2823 | LookForIvars = (Lookup.isSingleResult() && | ||||
2824 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||
2825 | ObjCInterfaceDecl *IFace = nullptr; | ||||
2826 | if (LookForIvars) { | ||||
2827 | IFace = CurMethod->getClassInterface(); | ||||
2828 | ObjCInterfaceDecl *ClassDeclared; | ||||
2829 | ObjCIvarDecl *IV = nullptr; | ||||
2830 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||
2831 | // Diagnose using an ivar in a class method. | ||||
2832 | if (IsClassMethod) { | ||||
2833 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2834 | return DeclResult(true); | ||||
2835 | } | ||||
2836 | |||||
2837 | // Diagnose the use of an ivar outside of the declaring class. | ||||
2838 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||
2839 | !declaresSameEntity(ClassDeclared, IFace) && | ||||
2840 | !getLangOpts().DebuggerSupport) | ||||
2841 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||
2842 | |||||
2843 | // Success. | ||||
2844 | return IV; | ||||
2845 | } | ||||
2846 | } else if (CurMethod->isInstanceMethod()) { | ||||
2847 | // We should warn if a local variable hides an ivar. | ||||
2848 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||
2849 | ObjCInterfaceDecl *ClassDeclared; | ||||
2850 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||
2851 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||
2852 | declaresSameEntity(IFace, ClassDeclared)) | ||||
2853 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||
2854 | } | ||||
2855 | } | ||||
2856 | } else if (Lookup.isSingleResult() && | ||||
2857 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||
2858 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||
2859 | if (const ObjCIvarDecl *IV = | ||||
2860 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||
2861 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2862 | return DeclResult(true); | ||||
2863 | } | ||||
2864 | } | ||||
2865 | |||||
2866 | // Didn't encounter an error, didn't find an ivar. | ||||
2867 | return DeclResult(false); | ||||
2868 | } | ||||
2869 | |||||
2870 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||
2871 | ObjCIvarDecl *IV) { | ||||
2872 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2873 | assert(CurMethod && CurMethod->isInstanceMethod() &&(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2874, __extension__ __PRETTY_FUNCTION__)) | ||||
2874 | "should not reference ivar from this context")(static_cast <bool> (CurMethod && CurMethod-> isInstanceMethod() && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2874, __extension__ __PRETTY_FUNCTION__)); | ||||
2875 | |||||
2876 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||
2877 | assert(IFace && "should not reference ivar from this context")(static_cast <bool> (IFace && "should not reference ivar from this context" ) ? void (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 2877, __extension__ __PRETTY_FUNCTION__)); | ||||
2878 | |||||
2879 | // If we're referencing an invalid decl, just return this as a silent | ||||
2880 | // error node. The error diagnostic was already emitted on the decl. | ||||
2881 | if (IV->isInvalidDecl()) | ||||
2882 | return ExprError(); | ||||
2883 | |||||
2884 | // Check if referencing a field with __attribute__((deprecated)). | ||||
2885 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||
2886 | return ExprError(); | ||||
2887 | |||||
2888 | // FIXME: This should use a new expr for a direct reference, don't | ||||
2889 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||
2890 | IdentifierInfo &II = Context.Idents.get("self"); | ||||
2891 | UnqualifiedId SelfName; | ||||
2892 | SelfName.setImplicitSelfParam(&II); | ||||
2893 | CXXScopeSpec SelfScopeSpec; | ||||
2894 | SourceLocation TemplateKWLoc; | ||||
2895 | ExprResult SelfExpr = | ||||
2896 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||
2897 | /*HasTrailingLParen=*/false, | ||||
2898 | /*IsAddressOfOperand=*/false); | ||||
2899 | if (SelfExpr.isInvalid()) | ||||
2900 | return ExprError(); | ||||
2901 | |||||
2902 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||
2903 | if (SelfExpr.isInvalid()) | ||||
2904 | return ExprError(); | ||||
2905 | |||||
2906 | MarkAnyDeclReferenced(Loc, IV, true); | ||||
2907 | |||||
2908 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||
2909 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||
2910 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||
2911 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||
2912 | |||||
2913 | ObjCIvarRefExpr *Result = new (Context) | ||||
2914 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||
2915 | IV->getLocation(), SelfExpr.get(), true, true); | ||||
2916 | |||||
2917 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
2918 | if (!isUnevaluatedContext() && | ||||
2919 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||
2920 | getCurFunction()->recordUseOfWeak(Result); | ||||
2921 | } | ||||
2922 | if (getLangOpts().ObjCAutoRefCount) | ||||
2923 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||
2924 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||
2925 | |||||
2926 | return Result; | ||||
2927 | } | ||||
2928 | |||||
2929 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2930 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2931 | /// should form a reference to an ivar. If so, build an expression referencing | ||||
2932 | /// that ivar. | ||||
2933 | ExprResult | ||||
2934 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2935 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||
2936 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||
2937 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||
2938 | if (Ivar.isInvalid()) | ||||
2939 | return ExprError(); | ||||
2940 | if (Ivar.isUsable()) | ||||
2941 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||
2942 | cast<ObjCIvarDecl>(Ivar.get())); | ||||
2943 | |||||
2944 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||
2945 | LookupBuiltin(Lookup); | ||||
2946 | |||||
2947 | // Sentinel value saying that we didn't do anything special. | ||||
2948 | return ExprResult(false); | ||||
2949 | } | ||||
2950 | |||||
2951 | /// Cast a base object to a member's actual type. | ||||
2952 | /// | ||||
2953 | /// There are two relevant checks: | ||||
2954 | /// | ||||
2955 | /// C++ [class.access.base]p7: | ||||
2956 | /// | ||||
2957 | /// If a class member access operator [...] is used to access a non-static | ||||
2958 | /// data member or non-static member function, the reference is ill-formed if | ||||
2959 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||
2960 | /// naming class of the right operand. | ||||
2961 | /// | ||||
2962 | /// C++ [expr.ref]p7: | ||||
2963 | /// | ||||
2964 | /// If E2 is a non-static data member or a non-static member function, the | ||||
2965 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||
2966 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||
2967 | /// | ||||
2968 | /// Note that the latter check does not consider access; the access of the | ||||
2969 | /// "real" base class is checked as appropriate when checking the access of the | ||||
2970 | /// member name. | ||||
2971 | ExprResult | ||||
2972 | Sema::PerformObjectMemberConversion(Expr *From, | ||||
2973 | NestedNameSpecifier *Qualifier, | ||||
2974 | NamedDecl *FoundDecl, | ||||
2975 | NamedDecl *Member) { | ||||
2976 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||
2977 | if (!RD) | ||||
2978 | return From; | ||||
2979 | |||||
2980 | QualType DestRecordType; | ||||
2981 | QualType DestType; | ||||
2982 | QualType FromRecordType; | ||||
2983 | QualType FromType = From->getType(); | ||||
2984 | bool PointerConversions = false; | ||||
2985 | if (isa<FieldDecl>(Member)) { | ||||
2986 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||
2987 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||
2988 | DestRecordType = Context.getAddrSpaceQualType( | ||||
2989 | DestRecordType, FromPtrType | ||||
2990 | ? FromType->getPointeeType().getAddressSpace() | ||||
2991 | : FromType.getAddressSpace()); | ||||
2992 | |||||
2993 | if (FromPtrType) { | ||||
2994 | DestType = Context.getPointerType(DestRecordType); | ||||
2995 | FromRecordType = FromPtrType->getPointeeType(); | ||||
2996 | PointerConversions = true; | ||||
2997 | } else { | ||||
2998 | DestType = DestRecordType; | ||||
2999 | FromRecordType = FromType; | ||||
3000 | } | ||||
3001 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||
3002 | if (Method->isStatic()) | ||||
3003 | return From; | ||||
3004 | |||||
3005 | DestType = Method->getThisType(); | ||||
3006 | DestRecordType = DestType->getPointeeType(); | ||||
3007 | |||||
3008 | if (FromType->getAs<PointerType>()) { | ||||
3009 | FromRecordType = FromType->getPointeeType(); | ||||
3010 | PointerConversions = true; | ||||
3011 | } else { | ||||
3012 | FromRecordType = FromType; | ||||
3013 | DestType = DestRecordType; | ||||
3014 | } | ||||
3015 | |||||
3016 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||
3017 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||
3018 | if (FromAS != DestAS) { | ||||
3019 | QualType FromRecordTypeWithoutAS = | ||||
3020 | Context.removeAddrSpaceQualType(FromRecordType); | ||||
3021 | QualType FromTypeWithDestAS = | ||||
3022 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||
3023 | if (PointerConversions) | ||||
3024 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||
3025 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||
3026 | CK_AddressSpaceConversion, From->getValueKind()) | ||||
3027 | .get(); | ||||
3028 | } | ||||
3029 | } else { | ||||
3030 | // No conversion necessary. | ||||
3031 | return From; | ||||
3032 | } | ||||
3033 | |||||
3034 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||
3035 | return From; | ||||
3036 | |||||
3037 | // If the unqualified types are the same, no conversion is necessary. | ||||
3038 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3039 | return From; | ||||
3040 | |||||
3041 | SourceRange FromRange = From->getSourceRange(); | ||||
3042 | SourceLocation FromLoc = FromRange.getBegin(); | ||||
3043 | |||||
3044 | ExprValueKind VK = From->getValueKind(); | ||||
3045 | |||||
3046 | // C++ [class.member.lookup]p8: | ||||
3047 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||
3048 | // class name. | ||||
3049 | // | ||||
3050 | // If the member was a qualified name and the qualified referred to a | ||||
3051 | // specific base subobject type, we'll cast to that intermediate type | ||||
3052 | // first and then to the object in which the member is declared. That allows | ||||
3053 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||
3054 | // | ||||
3055 | // class Base { public: int x; }; | ||||
3056 | // class Derived1 : public Base { }; | ||||
3057 | // class Derived2 : public Base { }; | ||||
3058 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||
3059 | // | ||||
3060 | // void VeryDerived::f() { | ||||
3061 | // x = 17; // error: ambiguous base subobjects | ||||
3062 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||
3063 | // } | ||||
3064 | if (Qualifier && Qualifier->getAsType()) { | ||||
3065 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||
3066 | assert(QType->isRecordType() && "lookup done with non-record type")(static_cast <bool> (QType->isRecordType() && "lookup done with non-record type") ? void (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3066, __extension__ __PRETTY_FUNCTION__)); | ||||
3067 | |||||
3068 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||
3069 | |||||
3070 | // In C++98, the qualifier type doesn't actually have to be a base | ||||
3071 | // type of the object type, in which case we just ignore it. | ||||
3072 | // Otherwise build the appropriate casts. | ||||
3073 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||
3074 | CXXCastPath BasePath; | ||||
3075 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||
3076 | FromLoc, FromRange, &BasePath)) | ||||
3077 | return ExprError(); | ||||
3078 | |||||
3079 | if (PointerConversions) | ||||
3080 | QType = Context.getPointerType(QType); | ||||
3081 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||
3082 | VK, &BasePath).get(); | ||||
3083 | |||||
3084 | FromType = QType; | ||||
3085 | FromRecordType = QRecordType; | ||||
3086 | |||||
3087 | // If the qualifier type was the same as the destination type, | ||||
3088 | // we're done. | ||||
3089 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3090 | return From; | ||||
3091 | } | ||||
3092 | } | ||||
3093 | |||||
3094 | CXXCastPath BasePath; | ||||
3095 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||
3096 | FromLoc, FromRange, &BasePath, | ||||
3097 | /*IgnoreAccess=*/true)) | ||||
3098 | return ExprError(); | ||||
3099 | |||||
3100 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||
3101 | VK, &BasePath); | ||||
3102 | } | ||||
3103 | |||||
3104 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||
3105 | const LookupResult &R, | ||||
3106 | bool HasTrailingLParen) { | ||||
3107 | // Only when used directly as the postfix-expression of a call. | ||||
3108 | if (!HasTrailingLParen) | ||||
3109 | return false; | ||||
3110 | |||||
3111 | // Never if a scope specifier was provided. | ||||
3112 | if (SS.isSet()) | ||||
3113 | return false; | ||||
3114 | |||||
3115 | // Only in C++ or ObjC++. | ||||
3116 | if (!getLangOpts().CPlusPlus) | ||||
3117 | return false; | ||||
3118 | |||||
3119 | // Turn off ADL when we find certain kinds of declarations during | ||||
3120 | // normal lookup: | ||||
3121 | for (NamedDecl *D : R) { | ||||
3122 | // C++0x [basic.lookup.argdep]p3: | ||||
3123 | // -- a declaration of a class member | ||||
3124 | // Since using decls preserve this property, we check this on the | ||||
3125 | // original decl. | ||||
3126 | if (D->isCXXClassMember()) | ||||
3127 | return false; | ||||
3128 | |||||
3129 | // C++0x [basic.lookup.argdep]p3: | ||||
3130 | // -- a block-scope function declaration that is not a | ||||
3131 | // using-declaration | ||||
3132 | // NOTE: we also trigger this for function templates (in fact, we | ||||
3133 | // don't check the decl type at all, since all other decl types | ||||
3134 | // turn off ADL anyway). | ||||
3135 | if (isa<UsingShadowDecl>(D)) | ||||
3136 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
3137 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3138 | return false; | ||||
3139 | |||||
3140 | // C++0x [basic.lookup.argdep]p3: | ||||
3141 | // -- a declaration that is neither a function or a function | ||||
3142 | // template | ||||
3143 | // And also for builtin functions. | ||||
3144 | if (isa<FunctionDecl>(D)) { | ||||
3145 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||
3146 | |||||
3147 | // But also builtin functions. | ||||
3148 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||
3149 | return false; | ||||
3150 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||
3151 | return false; | ||||
3152 | } | ||||
3153 | |||||
3154 | return true; | ||||
3155 | } | ||||
3156 | |||||
3157 | |||||
3158 | /// Diagnoses obvious problems with the use of the given declaration | ||||
3159 | /// as an expression. This is only actually called for lookups that | ||||
3160 | /// were not overloaded, and it doesn't promise that the declaration | ||||
3161 | /// will in fact be used. | ||||
3162 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||
3163 | if (D->isInvalidDecl()) | ||||
3164 | return true; | ||||
3165 | |||||
3166 | if (isa<TypedefNameDecl>(D)) { | ||||
3167 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||
3168 | return true; | ||||
3169 | } | ||||
3170 | |||||
3171 | if (isa<ObjCInterfaceDecl>(D)) { | ||||
3172 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||
3173 | return true; | ||||
3174 | } | ||||
3175 | |||||
3176 | if (isa<NamespaceDecl>(D)) { | ||||
3177 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||
3178 | return true; | ||||
3179 | } | ||||
3180 | |||||
3181 | return false; | ||||
3182 | } | ||||
3183 | |||||
3184 | // Certain multiversion types should be treated as overloaded even when there is | ||||
3185 | // only one result. | ||||
3186 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||
3187 | assert(R.isSingleResult() && "Expected only a single result")(static_cast <bool> (R.isSingleResult() && "Expected only a single result" ) ? void (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3187, __extension__ __PRETTY_FUNCTION__)); | ||||
3188 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||
3189 | return FD && | ||||
3190 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||
3191 | } | ||||
3192 | |||||
3193 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||
3194 | LookupResult &R, bool NeedsADL, | ||||
3195 | bool AcceptInvalidDecl) { | ||||
3196 | // If this is a single, fully-resolved result and we don't need ADL, | ||||
3197 | // just build an ordinary singleton decl ref. | ||||
3198 | if (!NeedsADL && R.isSingleResult() && | ||||
3199 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||
3200 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||
3201 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||
3202 | R.getRepresentativeDecl(), nullptr, | ||||
3203 | AcceptInvalidDecl); | ||||
3204 | |||||
3205 | // We only need to check the declaration if there's exactly one | ||||
3206 | // result, because in the overloaded case the results can only be | ||||
3207 | // functions and function templates. | ||||
3208 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||
3209 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||
3210 | return ExprError(); | ||||
3211 | |||||
3212 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||
3213 | // any lookup-related diagnostics; we'll hash these out later, when | ||||
3214 | // we've picked a target. | ||||
3215 | R.suppressDiagnostics(); | ||||
3216 | |||||
3217 | UnresolvedLookupExpr *ULE | ||||
3218 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||
3219 | SS.getWithLocInContext(Context), | ||||
3220 | R.getLookupNameInfo(), | ||||
3221 | NeedsADL, R.isOverloadedResult(), | ||||
3222 | R.begin(), R.end()); | ||||
3223 | |||||
3224 | return ULE; | ||||
3225 | } | ||||
3226 | |||||
3227 | static void | ||||
3228 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
3229 | ValueDecl *var, DeclContext *DC); | ||||
3230 | |||||
3231 | /// Complete semantic analysis for a reference to the given declaration. | ||||
3232 | ExprResult Sema::BuildDeclarationNameExpr( | ||||
3233 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||
3234 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||
3235 | bool AcceptInvalidDecl) { | ||||
3236 | assert(D && "Cannot refer to a NULL declaration")(static_cast <bool> (D && "Cannot refer to a NULL declaration" ) ? void (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3236, __extension__ __PRETTY_FUNCTION__)); | ||||
3237 | assert(!isa<FunctionTemplateDecl>(D) &&(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3238, __extension__ __PRETTY_FUNCTION__)) | ||||
3238 | "Cannot refer unambiguously to a function template")(static_cast <bool> (!isa<FunctionTemplateDecl>(D ) && "Cannot refer unambiguously to a function template" ) ? void (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3238, __extension__ __PRETTY_FUNCTION__)); | ||||
3239 | |||||
3240 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3241 | if (CheckDeclInExpr(*this, Loc, D)) | ||||
3242 | return ExprError(); | ||||
3243 | |||||
3244 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||
3245 | // Specifically diagnose references to class templates that are missing | ||||
3246 | // a template argument list. | ||||
3247 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||
3248 | return ExprError(); | ||||
3249 | } | ||||
3250 | |||||
3251 | // Make sure that we're referring to a value. | ||||
3252 | if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { | ||||
3253 | Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); | ||||
3254 | Diag(D->getLocation(), diag::note_declared_at); | ||||
3255 | return ExprError(); | ||||
3256 | } | ||||
3257 | |||||
3258 | // Check whether this declaration can be used. Note that we suppress | ||||
3259 | // this check when we're going to perform argument-dependent lookup | ||||
3260 | // on this function name, because this might not be the function | ||||
3261 | // that overload resolution actually selects. | ||||
3262 | if (DiagnoseUseOfDecl(D, Loc)) | ||||
3263 | return ExprError(); | ||||
3264 | |||||
3265 | auto *VD = cast<ValueDecl>(D); | ||||
3266 | |||||
3267 | // Only create DeclRefExpr's for valid Decl's. | ||||
3268 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||
3269 | return ExprError(); | ||||
3270 | |||||
3271 | // Handle members of anonymous structs and unions. If we got here, | ||||
3272 | // and the reference is to a class member indirect field, then this | ||||
3273 | // must be the subject of a pointer-to-member expression. | ||||
3274 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||
3275 | if (!indirectField->isCXXClassMember()) | ||||
3276 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||
3277 | indirectField); | ||||
3278 | |||||
3279 | QualType type = VD->getType(); | ||||
3280 | if (type.isNull()) | ||||
3281 | return ExprError(); | ||||
3282 | ExprValueKind valueKind = VK_PRValue; | ||||
3283 | |||||
3284 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||
3285 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||
3286 | // is expanded by some outer '...' in the context of the use. | ||||
3287 | type = type.getNonPackExpansionType(); | ||||
3288 | |||||
3289 | switch (D->getKind()) { | ||||
3290 | // Ignore all the non-ValueDecl kinds. | ||||
3291 | #define ABSTRACT_DECL(kind) | ||||
3292 | #define VALUE(type, base) | ||||
3293 | #define DECL(type, base) case Decl::type: | ||||
3294 | #include "clang/AST/DeclNodes.inc" | ||||
3295 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3295); | ||||
3296 | |||||
3297 | // These shouldn't make it here. | ||||
3298 | case Decl::ObjCAtDefsField: | ||||
3299 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3299); | ||||
3300 | |||||
3301 | // Enum constants are always r-values and never references. | ||||
3302 | // Unresolved using declarations are dependent. | ||||
3303 | case Decl::EnumConstant: | ||||
3304 | case Decl::UnresolvedUsingValue: | ||||
3305 | case Decl::OMPDeclareReduction: | ||||
3306 | case Decl::OMPDeclareMapper: | ||||
3307 | valueKind = VK_PRValue; | ||||
3308 | break; | ||||
3309 | |||||
3310 | // Fields and indirect fields that got here must be for | ||||
3311 | // pointer-to-member expressions; we just call them l-values for | ||||
3312 | // internal consistency, because this subexpression doesn't really | ||||
3313 | // exist in the high-level semantics. | ||||
3314 | case Decl::Field: | ||||
3315 | case Decl::IndirectField: | ||||
3316 | case Decl::ObjCIvar: | ||||
3317 | assert(getLangOpts().CPlusPlus && "building reference to field in C?")(static_cast <bool> (getLangOpts().CPlusPlus && "building reference to field in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3317, __extension__ __PRETTY_FUNCTION__)); | ||||
3318 | |||||
3319 | // These can't have reference type in well-formed programs, but | ||||
3320 | // for internal consistency we do this anyway. | ||||
3321 | type = type.getNonReferenceType(); | ||||
3322 | valueKind = VK_LValue; | ||||
3323 | break; | ||||
3324 | |||||
3325 | // Non-type template parameters are either l-values or r-values | ||||
3326 | // depending on the type. | ||||
3327 | case Decl::NonTypeTemplateParm: { | ||||
3328 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||
3329 | type = reftype->getPointeeType(); | ||||
3330 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||
3331 | break; | ||||
3332 | } | ||||
3333 | |||||
3334 | // [expr.prim.id.unqual]p2: | ||||
3335 | // If the entity is a template parameter object for a template | ||||
3336 | // parameter of type T, the type of the expression is const T. | ||||
3337 | // [...] The expression is an lvalue if the entity is a [...] template | ||||
3338 | // parameter object. | ||||
3339 | if (type->isRecordType()) { | ||||
3340 | type = type.getUnqualifiedType().withConst(); | ||||
3341 | valueKind = VK_LValue; | ||||
3342 | break; | ||||
3343 | } | ||||
3344 | |||||
3345 | // For non-references, we need to strip qualifiers just in case | ||||
3346 | // the template parameter was declared as 'const int' or whatever. | ||||
3347 | valueKind = VK_PRValue; | ||||
3348 | type = type.getUnqualifiedType(); | ||||
3349 | break; | ||||
3350 | } | ||||
3351 | |||||
3352 | case Decl::Var: | ||||
3353 | case Decl::VarTemplateSpecialization: | ||||
3354 | case Decl::VarTemplatePartialSpecialization: | ||||
3355 | case Decl::Decomposition: | ||||
3356 | case Decl::OMPCapturedExpr: | ||||
3357 | // In C, "extern void blah;" is valid and is an r-value. | ||||
3358 | if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && | ||||
3359 | type->isVoidType()) { | ||||
3360 | valueKind = VK_PRValue; | ||||
3361 | break; | ||||
3362 | } | ||||
3363 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3364 | |||||
3365 | case Decl::ImplicitParam: | ||||
3366 | case Decl::ParmVar: { | ||||
3367 | // These are always l-values. | ||||
3368 | valueKind = VK_LValue; | ||||
3369 | type = type.getNonReferenceType(); | ||||
3370 | |||||
3371 | // FIXME: Does the addition of const really only apply in | ||||
3372 | // potentially-evaluated contexts? Since the variable isn't actually | ||||
3373 | // captured in an unevaluated context, it seems that the answer is no. | ||||
3374 | if (!isUnevaluatedContext()) { | ||||
3375 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||
3376 | if (!CapturedType.isNull()) | ||||
3377 | type = CapturedType; | ||||
3378 | } | ||||
3379 | |||||
3380 | break; | ||||
3381 | } | ||||
3382 | |||||
3383 | case Decl::Binding: { | ||||
3384 | // These are always lvalues. | ||||
3385 | valueKind = VK_LValue; | ||||
3386 | type = type.getNonReferenceType(); | ||||
3387 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||
3388 | // decides how that's supposed to work. | ||||
3389 | auto *BD = cast<BindingDecl>(VD); | ||||
3390 | if (BD->getDeclContext() != CurContext) { | ||||
3391 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||
3392 | if (DD && DD->hasLocalStorage()) | ||||
3393 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||
3394 | } | ||||
3395 | break; | ||||
3396 | } | ||||
3397 | |||||
3398 | case Decl::Function: { | ||||
3399 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||
3400 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||
3401 | type = Context.BuiltinFnTy; | ||||
3402 | valueKind = VK_PRValue; | ||||
3403 | break; | ||||
3404 | } | ||||
3405 | } | ||||
3406 | |||||
3407 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||
3408 | |||||
3409 | // If we're referring to a function with an __unknown_anytype | ||||
3410 | // result type, make the entire expression __unknown_anytype. | ||||
3411 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||
3412 | type = Context.UnknownAnyTy; | ||||
3413 | valueKind = VK_PRValue; | ||||
3414 | break; | ||||
3415 | } | ||||
3416 | |||||
3417 | // Functions are l-values in C++. | ||||
3418 | if (getLangOpts().CPlusPlus) { | ||||
3419 | valueKind = VK_LValue; | ||||
3420 | break; | ||||
3421 | } | ||||
3422 | |||||
3423 | // C99 DR 316 says that, if a function type comes from a | ||||
3424 | // function definition (without a prototype), that type is only | ||||
3425 | // used for checking compatibility. Therefore, when referencing | ||||
3426 | // the function, we pretend that we don't have the full function | ||||
3427 | // type. | ||||
3428 | if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) | ||||
3429 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||
3430 | fty->getExtInfo()); | ||||
3431 | |||||
3432 | // Functions are r-values in C. | ||||
3433 | valueKind = VK_PRValue; | ||||
3434 | break; | ||||
3435 | } | ||||
3436 | |||||
3437 | case Decl::CXXDeductionGuide: | ||||
3438 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3438); | ||||
3439 | |||||
3440 | case Decl::MSProperty: | ||||
3441 | case Decl::MSGuid: | ||||
3442 | case Decl::TemplateParamObject: | ||||
3443 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||
3444 | // capture in OpenMP, or duplicated between host and device? | ||||
3445 | valueKind = VK_LValue; | ||||
3446 | break; | ||||
3447 | |||||
3448 | case Decl::CXXMethod: | ||||
3449 | // If we're referring to a method with an __unknown_anytype | ||||
3450 | // result type, make the entire expression __unknown_anytype. | ||||
3451 | // This should only be possible with a type written directly. | ||||
3452 | if (const FunctionProtoType *proto = | ||||
3453 | dyn_cast<FunctionProtoType>(VD->getType())) | ||||
3454 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||
3455 | type = Context.UnknownAnyTy; | ||||
3456 | valueKind = VK_PRValue; | ||||
3457 | break; | ||||
3458 | } | ||||
3459 | |||||
3460 | // C++ methods are l-values if static, r-values if non-static. | ||||
3461 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||
3462 | valueKind = VK_LValue; | ||||
3463 | break; | ||||
3464 | } | ||||
3465 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3466 | |||||
3467 | case Decl::CXXConversion: | ||||
3468 | case Decl::CXXDestructor: | ||||
3469 | case Decl::CXXConstructor: | ||||
3470 | valueKind = VK_PRValue; | ||||
3471 | break; | ||||
3472 | } | ||||
3473 | |||||
3474 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||
3475 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||
3476 | TemplateArgs); | ||||
3477 | } | ||||
3478 | |||||
3479 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||
3480 | SmallString<32> &Target) { | ||||
3481 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||
3482 | char *ResultPtr = &Target[0]; | ||||
3483 | const llvm::UTF8 *ErrorPtr; | ||||
3484 | bool success = | ||||
3485 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||
3486 | (void)success; | ||||
3487 | assert(success)(static_cast <bool> (success) ? void (0) : __assert_fail ("success", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3487, __extension__ __PRETTY_FUNCTION__)); | ||||
3488 | Target.resize(ResultPtr - &Target[0]); | ||||
3489 | } | ||||
3490 | |||||
3491 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||
3492 | PredefinedExpr::IdentKind IK) { | ||||
3493 | // Pick the current block, lambda, captured statement or function. | ||||
3494 | Decl *currentDecl = nullptr; | ||||
3495 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||
3496 | currentDecl = BSI->TheDecl; | ||||
3497 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||
3498 | currentDecl = LSI->CallOperator; | ||||
3499 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||
3500 | currentDecl = CSI->TheCapturedDecl; | ||||
3501 | else | ||||
3502 | currentDecl = getCurFunctionOrMethodDecl(); | ||||
3503 | |||||
3504 | if (!currentDecl) { | ||||
3505 | Diag(Loc, diag::ext_predef_outside_function); | ||||
3506 | currentDecl = Context.getTranslationUnitDecl(); | ||||
3507 | } | ||||
3508 | |||||
3509 | QualType ResTy; | ||||
3510 | StringLiteral *SL = nullptr; | ||||
3511 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||
3512 | ResTy = Context.DependentTy; | ||||
3513 | else { | ||||
3514 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||
3515 | // the string. | ||||
3516 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||
3517 | unsigned Length = Str.length(); | ||||
3518 | |||||
3519 | llvm::APInt LengthI(32, Length + 1); | ||||
3520 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||
3521 | ResTy = | ||||
3522 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||
3523 | SmallString<32> RawChars; | ||||
3524 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||
3525 | Str, RawChars); | ||||
3526 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3527 | ArrayType::Normal, | ||||
3528 | /*IndexTypeQuals*/ 0); | ||||
3529 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||
3530 | /*Pascal*/ false, ResTy, Loc); | ||||
3531 | } else { | ||||
3532 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||
3533 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3534 | ArrayType::Normal, | ||||
3535 | /*IndexTypeQuals*/ 0); | ||||
3536 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||
3537 | /*Pascal*/ false, ResTy, Loc); | ||||
3538 | } | ||||
3539 | } | ||||
3540 | |||||
3541 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||
3542 | } | ||||
3543 | |||||
3544 | ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3545 | SourceLocation LParen, | ||||
3546 | SourceLocation RParen, | ||||
3547 | TypeSourceInfo *TSI) { | ||||
3548 | return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); | ||||
3549 | } | ||||
3550 | |||||
3551 | ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, | ||||
3552 | SourceLocation LParen, | ||||
3553 | SourceLocation RParen, | ||||
3554 | ParsedType ParsedTy) { | ||||
3555 | TypeSourceInfo *TSI = nullptr; | ||||
3556 | QualType Ty = GetTypeFromParser(ParsedTy, &TSI); | ||||
3557 | |||||
3558 | if (Ty.isNull()) | ||||
3559 | return ExprError(); | ||||
3560 | if (!TSI) | ||||
3561 | TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); | ||||
3562 | |||||
3563 | return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); | ||||
3564 | } | ||||
3565 | |||||
3566 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||
3567 | PredefinedExpr::IdentKind IK; | ||||
3568 | |||||
3569 | switch (Kind) { | ||||
3570 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3570); | ||||
3571 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||
3572 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||
3573 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||
3574 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||
3575 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||
3576 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||
3577 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||
3578 | } | ||||
3579 | |||||
3580 | return BuildPredefinedExpr(Loc, IK); | ||||
3581 | } | ||||
3582 | |||||
3583 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||
3584 | SmallString<16> CharBuffer; | ||||
3585 | bool Invalid = false; | ||||
3586 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||
3587 | if (Invalid) | ||||
3588 | return ExprError(); | ||||
3589 | |||||
3590 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||
3591 | PP, Tok.getKind()); | ||||
3592 | if (Literal.hadError()) | ||||
3593 | return ExprError(); | ||||
3594 | |||||
3595 | QualType Ty; | ||||
3596 | if (Literal.isWide()) | ||||
3597 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||
3598 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||
3599 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||
3600 | else if (Literal.isUTF16()) | ||||
3601 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||
3602 | else if (Literal.isUTF32()) | ||||
3603 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||
3604 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||
3605 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||
3606 | else | ||||
3607 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||
3608 | |||||
3609 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||
3610 | if (Literal.isWide()) | ||||
3611 | Kind = CharacterLiteral::Wide; | ||||
3612 | else if (Literal.isUTF16()) | ||||
3613 | Kind = CharacterLiteral::UTF16; | ||||
3614 | else if (Literal.isUTF32()) | ||||
3615 | Kind = CharacterLiteral::UTF32; | ||||
3616 | else if (Literal.isUTF8()) | ||||
3617 | Kind = CharacterLiteral::UTF8; | ||||
3618 | |||||
3619 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||
3620 | Tok.getLocation()); | ||||
3621 | |||||
3622 | if (Literal.getUDSuffix().empty()) | ||||
3623 | return Lit; | ||||
3624 | |||||
3625 | // We're building a user-defined literal. | ||||
3626 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3627 | SourceLocation UDSuffixLoc = | ||||
3628 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3629 | |||||
3630 | // Make sure we're allowed user-defined literals here. | ||||
3631 | if (!UDLScope) | ||||
3632 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||
3633 | |||||
3634 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||
3635 | // operator "" X (ch) | ||||
3636 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||
3637 | Lit, Tok.getLocation()); | ||||
3638 | } | ||||
3639 | |||||
3640 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||
3641 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3642 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||
3643 | Context.IntTy, Loc); | ||||
3644 | } | ||||
3645 | |||||
3646 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||
3647 | QualType Ty, SourceLocation Loc) { | ||||
3648 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||
3649 | |||||
3650 | using llvm::APFloat; | ||||
3651 | APFloat Val(Format); | ||||
3652 | |||||
3653 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||
3654 | |||||
3655 | // Overflow is always an error, but underflow is only an error if | ||||
3656 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||
3657 | if ((result & APFloat::opOverflow) || | ||||
3658 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||
3659 | unsigned diagnostic; | ||||
3660 | SmallString<20> buffer; | ||||
3661 | if (result & APFloat::opOverflow) { | ||||
3662 | diagnostic = diag::warn_float_overflow; | ||||
3663 | APFloat::getLargest(Format).toString(buffer); | ||||
3664 | } else { | ||||
3665 | diagnostic = diag::warn_float_underflow; | ||||
3666 | APFloat::getSmallest(Format).toString(buffer); | ||||
3667 | } | ||||
3668 | |||||
3669 | S.Diag(Loc, diagnostic) | ||||
3670 | << Ty | ||||
3671 | << StringRef(buffer.data(), buffer.size()); | ||||
3672 | } | ||||
3673 | |||||
3674 | bool isExact = (result == APFloat::opOK); | ||||
3675 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||
3676 | } | ||||
3677 | |||||
3678 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||
3679 | assert(E && "Invalid expression")(static_cast <bool> (E && "Invalid expression") ? void (0) : __assert_fail ("E && \"Invalid expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3679, __extension__ __PRETTY_FUNCTION__)); | ||||
3680 | |||||
3681 | if (E->isValueDependent()) | ||||
3682 | return false; | ||||
3683 | |||||
3684 | QualType QT = E->getType(); | ||||
3685 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||
3686 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||
3687 | return true; | ||||
3688 | } | ||||
3689 | |||||
3690 | llvm::APSInt ValueAPS; | ||||
3691 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||
3692 | |||||
3693 | if (R.isInvalid()) | ||||
3694 | return true; | ||||
3695 | |||||
3696 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||
3697 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||
3698 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||
3699 | << toString(ValueAPS, 10) << ValueIsPositive; | ||||
3700 | return true; | ||||
3701 | } | ||||
3702 | |||||
3703 | return false; | ||||
3704 | } | ||||
3705 | |||||
3706 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||
3707 | // Fast path for a single digit (which is quite common). A single digit | ||||
3708 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||
3709 | if (Tok.getLength() == 1) { | ||||
3710 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||
3711 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||
3712 | } | ||||
3713 | |||||
3714 | SmallString<128> SpellingBuffer; | ||||
3715 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||
3716 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||
3717 | // returns a StringRef to the memory buffer, it should have a null char at | ||||
3718 | // the EOF, so it is also safe. | ||||
3719 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||
3720 | |||||
3721 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||
3722 | bool Invalid = false; | ||||
3723 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||
3724 | if (Invalid) | ||||
3725 | return ExprError(); | ||||
3726 | |||||
3727 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||
3728 | PP.getSourceManager(), PP.getLangOpts(), | ||||
3729 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||
3730 | if (Literal.hadError) | ||||
3731 | return ExprError(); | ||||
3732 | |||||
3733 | if (Literal.hasUDSuffix()) { | ||||
3734 | // We're building a user-defined literal. | ||||
3735 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3736 | SourceLocation UDSuffixLoc = | ||||
3737 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3738 | |||||
3739 | // Make sure we're allowed user-defined literals here. | ||||
3740 | if (!UDLScope) | ||||
3741 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||
3742 | |||||
3743 | QualType CookedTy; | ||||
3744 | if (Literal.isFloatingLiteral()) { | ||||
3745 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||
3746 | // long double, the literal is treated as a call of the form | ||||
3747 | // operator "" X (f L) | ||||
3748 | CookedTy = Context.LongDoubleTy; | ||||
3749 | } else { | ||||
3750 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||
3751 | // unsigned long long, the literal is treated as a call of the form | ||||
3752 | // operator "" X (n ULL) | ||||
3753 | CookedTy = Context.UnsignedLongLongTy; | ||||
3754 | } | ||||
3755 | |||||
3756 | DeclarationName OpName = | ||||
3757 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
3758 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
3759 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
3760 | |||||
3761 | SourceLocation TokLoc = Tok.getLocation(); | ||||
3762 | |||||
3763 | // Perform literal operator lookup to determine if we're building a raw | ||||
3764 | // literal or a cooked one. | ||||
3765 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
3766 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||
3767 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||
3768 | /*AllowStringTemplatePack*/ false, | ||||
3769 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||
3770 | case LOLR_ErrorNoDiagnostic: | ||||
3771 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||
3772 | // GNU extension producing _Complex types. | ||||
3773 | break; | ||||
3774 | case LOLR_Error: | ||||
3775 | return ExprError(); | ||||
3776 | case LOLR_Cooked: { | ||||
3777 | Expr *Lit; | ||||
3778 | if (Literal.isFloatingLiteral()) { | ||||
3779 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||
3780 | } else { | ||||
3781 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||
3782 | if (Literal.GetIntegerValue(ResultVal)) | ||||
3783 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3784 | << /* Unsigned */ 1; | ||||
3785 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||
3786 | Tok.getLocation()); | ||||
3787 | } | ||||
3788 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3789 | } | ||||
3790 | |||||
3791 | case LOLR_Raw: { | ||||
3792 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||
3793 | // literal is treated as a call of the form | ||||
3794 | // operator "" X ("n") | ||||
3795 | unsigned Length = Literal.getUDSuffixOffset(); | ||||
3796 | QualType StrTy = Context.getConstantArrayType( | ||||
3797 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||
3798 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||
3799 | Expr *Lit = StringLiteral::Create( | ||||
3800 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||
3801 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||
3802 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3803 | } | ||||
3804 | |||||
3805 | case LOLR_Template: { | ||||
3806 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||
3807 | // template), L is treated as a call fo the form | ||||
3808 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||
3809 | // where n is the source character sequence c1 c2 ... ck. | ||||
3810 | TemplateArgumentListInfo ExplicitArgs; | ||||
3811 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||
3812 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||
3813 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
3814 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||
3815 | Value = TokSpelling[I]; | ||||
3816 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||
3817 | TemplateArgumentLocInfo ArgInfo; | ||||
3818 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
3819 | } | ||||
3820 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||
3821 | &ExplicitArgs); | ||||
3822 | } | ||||
3823 | case LOLR_StringTemplatePack: | ||||
3824 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3824); | ||||
3825 | } | ||||
3826 | } | ||||
3827 | |||||
3828 | Expr *Res; | ||||
3829 | |||||
3830 | if (Literal.isFixedPointLiteral()) { | ||||
3831 | QualType Ty; | ||||
3832 | |||||
3833 | if (Literal.isAccum) { | ||||
3834 | if (Literal.isHalf) { | ||||
3835 | Ty = Context.ShortAccumTy; | ||||
3836 | } else if (Literal.isLong) { | ||||
3837 | Ty = Context.LongAccumTy; | ||||
3838 | } else { | ||||
3839 | Ty = Context.AccumTy; | ||||
3840 | } | ||||
3841 | } else if (Literal.isFract) { | ||||
3842 | if (Literal.isHalf) { | ||||
3843 | Ty = Context.ShortFractTy; | ||||
3844 | } else if (Literal.isLong) { | ||||
3845 | Ty = Context.LongFractTy; | ||||
3846 | } else { | ||||
3847 | Ty = Context.FractTy; | ||||
3848 | } | ||||
3849 | } | ||||
3850 | |||||
3851 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||
3852 | |||||
3853 | bool isSigned = !Literal.isUnsigned; | ||||
3854 | unsigned scale = Context.getFixedPointScale(Ty); | ||||
3855 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||
3856 | |||||
3857 | llvm::APInt Val(bit_width, 0, isSigned); | ||||
3858 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||
3859 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||
3860 | |||||
3861 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||
3862 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||
3863 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||
3864 | // representable values for its type, with exception for constants of a | ||||
3865 | // fract type with a value of exactly 1; such a constant shall denote | ||||
3866 | // the maximal value for the type. | ||||
3867 | --Val; | ||||
3868 | else if (Val.ugt(MaxVal) || Overflowed) | ||||
3869 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||
3870 | |||||
3871 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||
3872 | Tok.getLocation(), scale); | ||||
3873 | } else if (Literal.isFloatingLiteral()) { | ||||
3874 | QualType Ty; | ||||
3875 | if (Literal.isHalf){ | ||||
3876 | if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) | ||||
3877 | Ty = Context.HalfTy; | ||||
3878 | else { | ||||
3879 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||
3880 | return ExprError(); | ||||
3881 | } | ||||
3882 | } else if (Literal.isFloat) | ||||
3883 | Ty = Context.FloatTy; | ||||
3884 | else if (Literal.isLong) | ||||
3885 | Ty = Context.LongDoubleTy; | ||||
3886 | else if (Literal.isFloat16) | ||||
3887 | Ty = Context.Float16Ty; | ||||
3888 | else if (Literal.isFloat128) | ||||
3889 | Ty = Context.Float128Ty; | ||||
3890 | else | ||||
3891 | Ty = Context.DoubleTy; | ||||
3892 | |||||
3893 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||
3894 | |||||
3895 | if (Ty == Context.DoubleTy) { | ||||
3896 | if (getLangOpts().SinglePrecisionConstants) { | ||||
3897 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||
3898 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3899 | } | ||||
3900 | } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( | ||||
3901 | "cl_khr_fp64", getLangOpts())) { | ||||
3902 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||
3903 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) | ||||
3904 | << (getLangOpts().OpenCLVersion >= 300); | ||||
3905 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3906 | } | ||||
3907 | } | ||||
3908 | } else if (!Literal.isIntegerLiteral()) { | ||||
3909 | return ExprError(); | ||||
3910 | } else { | ||||
3911 | QualType Ty; | ||||
3912 | |||||
3913 | // 'long long' is a C99 or C++11 feature. | ||||
3914 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||
3915 | if (getLangOpts().CPlusPlus) | ||||
3916 | Diag(Tok.getLocation(), | ||||
3917 | getLangOpts().CPlusPlus11 ? | ||||
3918 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||
3919 | else | ||||
3920 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||
3921 | } | ||||
3922 | |||||
3923 | // 'z/uz' literals are a C++2b feature. | ||||
3924 | if (Literal.isSizeT) | ||||
3925 | Diag(Tok.getLocation(), getLangOpts().CPlusPlus | ||||
3926 | ? getLangOpts().CPlusPlus2b | ||||
3927 | ? diag::warn_cxx20_compat_size_t_suffix | ||||
3928 | : diag::ext_cxx2b_size_t_suffix | ||||
3929 | : diag::err_cxx2b_size_t_suffix); | ||||
3930 | |||||
3931 | // Get the value in the widest-possible width. | ||||
3932 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||
3933 | llvm::APInt ResultVal(MaxWidth, 0); | ||||
3934 | |||||
3935 | if (Literal.GetIntegerValue(ResultVal)) { | ||||
3936 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||
3937 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3938 | << /* Unsigned */ 1; | ||||
3939 | Ty = Context.UnsignedLongLongTy; | ||||
3940 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3941, __extension__ __PRETTY_FUNCTION__)) | ||||
3941 | "long long is not intmax_t?")(static_cast <bool> (Context.getTypeSize(Ty) == ResultVal .getBitWidth() && "long long is not intmax_t?") ? void (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3941, __extension__ __PRETTY_FUNCTION__)); | ||||
3942 | } else { | ||||
3943 | // If this value fits into a ULL, try to figure out what else it fits into | ||||
3944 | // according to the rules of C99 6.4.4.1p5. | ||||
3945 | |||||
3946 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||
3947 | // be an unsigned int. | ||||
3948 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||
3949 | |||||
3950 | // Check from smallest to largest, picking the smallest type we can. | ||||
3951 | unsigned Width = 0; | ||||
3952 | |||||
3953 | // Microsoft specific integer suffixes are explicitly sized. | ||||
3954 | if (Literal.MicrosoftInteger) { | ||||
3955 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||
3956 | Width = 8; | ||||
3957 | Ty = Context.CharTy; | ||||
3958 | } else { | ||||
3959 | Width = Literal.MicrosoftInteger; | ||||
3960 | Ty = Context.getIntTypeForBitwidth(Width, | ||||
3961 | /*Signed=*/!Literal.isUnsigned); | ||||
3962 | } | ||||
3963 | } | ||||
3964 | |||||
3965 | // Check C++2b size_t literals. | ||||
3966 | if (Literal.isSizeT) { | ||||
3967 | assert(!Literal.MicrosoftInteger &&(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3968, __extension__ __PRETTY_FUNCTION__)) | ||||
3968 | "size_t literals can't be Microsoft literals")(static_cast <bool> (!Literal.MicrosoftInteger && "size_t literals can't be Microsoft literals") ? void (0) : __assert_fail ("!Literal.MicrosoftInteger && \"size_t literals can't be Microsoft literals\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 3968, __extension__ __PRETTY_FUNCTION__)); | ||||
3969 | unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( | ||||
3970 | Context.getTargetInfo().getSizeType()); | ||||
3971 | |||||
3972 | // Does it fit in size_t? | ||||
3973 | if (ResultVal.isIntN(SizeTSize)) { | ||||
3974 | // Does it fit in ssize_t? | ||||
3975 | if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) | ||||
3976 | Ty = Context.getSignedSizeType(); | ||||
3977 | else if (AllowUnsigned) | ||||
3978 | Ty = Context.getSizeType(); | ||||
3979 | Width = SizeTSize; | ||||
3980 | } | ||||
3981 | } | ||||
3982 | |||||
3983 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && | ||||
3984 | !Literal.isSizeT) { | ||||
3985 | // Are int/unsigned possibilities? | ||||
3986 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3987 | |||||
3988 | // Does it fit in a unsigned int? | ||||
3989 | if (ResultVal.isIntN(IntSize)) { | ||||
3990 | // Does it fit in a signed int? | ||||
3991 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||
3992 | Ty = Context.IntTy; | ||||
3993 | else if (AllowUnsigned) | ||||
3994 | Ty = Context.UnsignedIntTy; | ||||
3995 | Width = IntSize; | ||||
3996 | } | ||||
3997 | } | ||||
3998 | |||||
3999 | // Are long/unsigned long possibilities? | ||||
4000 | if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { | ||||
4001 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||
4002 | |||||
4003 | // Does it fit in a unsigned long? | ||||
4004 | if (ResultVal.isIntN(LongSize)) { | ||||
4005 | // Does it fit in a signed long? | ||||
4006 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||
4007 | Ty = Context.LongTy; | ||||
4008 | else if (AllowUnsigned) | ||||
4009 | Ty = Context.UnsignedLongTy; | ||||
4010 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||
4011 | // is compatible. | ||||
4012 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||
4013 | const unsigned LongLongSize = | ||||
4014 | Context.getTargetInfo().getLongLongWidth(); | ||||
4015 | Diag(Tok.getLocation(), | ||||
4016 | getLangOpts().CPlusPlus | ||||
4017 | ? Literal.isLong | ||||
4018 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||
4019 | : /*C++98 UB*/ diag:: | ||||
4020 | ext_old_implicitly_unsigned_long_cxx | ||||
4021 | : diag::warn_old_implicitly_unsigned_long) | ||||
4022 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||
4023 | : /*will be ill-formed*/ 1); | ||||
4024 | Ty = Context.UnsignedLongTy; | ||||
4025 | } | ||||
4026 | Width = LongSize; | ||||
4027 | } | ||||
4028 | } | ||||
4029 | |||||
4030 | // Check long long if needed. | ||||
4031 | if (Ty.isNull() && !Literal.isSizeT) { | ||||
4032 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||
4033 | |||||
4034 | // Does it fit in a unsigned long long? | ||||
4035 | if (ResultVal.isIntN(LongLongSize)) { | ||||
4036 | // Does it fit in a signed long long? | ||||
4037 | // To be compatible with MSVC, hex integer literals ending with the | ||||
4038 | // LL or i64 suffix are always signed in Microsoft mode. | ||||
4039 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||
4040 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||
4041 | Ty = Context.LongLongTy; | ||||
4042 | else if (AllowUnsigned) | ||||
4043 | Ty = Context.UnsignedLongLongTy; | ||||
4044 | Width = LongLongSize; | ||||
4045 | } | ||||
4046 | } | ||||
4047 | |||||
4048 | // If we still couldn't decide a type, we either have 'size_t' literal | ||||
4049 | // that is out of range, or a decimal literal that does not fit in a | ||||
4050 | // signed long long and has no U suffix. | ||||
4051 | if (Ty.isNull()) { | ||||
4052 | if (Literal.isSizeT) | ||||
4053 | Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) | ||||
4054 | << Literal.isUnsigned; | ||||
4055 | else | ||||
4056 | Diag(Tok.getLocation(), | ||||
4057 | diag::ext_integer_literal_too_large_for_signed); | ||||
4058 | Ty = Context.UnsignedLongLongTy; | ||||
4059 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||
4060 | } | ||||
4061 | |||||
4062 | if (ResultVal.getBitWidth() != Width) | ||||
4063 | ResultVal = ResultVal.trunc(Width); | ||||
4064 | } | ||||
4065 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||
4066 | } | ||||
4067 | |||||
4068 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||
4069 | if (Literal.isImaginary) { | ||||
4070 | Res = new (Context) ImaginaryLiteral(Res, | ||||
4071 | Context.getComplexType(Res->getType())); | ||||
4072 | |||||
4073 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||
4074 | } | ||||
4075 | return Res; | ||||
4076 | } | ||||
4077 | |||||
4078 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||
4079 | assert(E && "ActOnParenExpr() missing expr")(static_cast <bool> (E && "ActOnParenExpr() missing expr" ) ? void (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4079, __extension__ __PRETTY_FUNCTION__)); | ||||
4080 | QualType ExprTy = E->getType(); | ||||
4081 | if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && | ||||
4082 | !E->isLValue() && ExprTy->hasFloatingRepresentation()) | ||||
4083 | return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); | ||||
4084 | return new (Context) ParenExpr(L, R, E); | ||||
4085 | } | ||||
4086 | |||||
4087 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||
4088 | SourceLocation Loc, | ||||
4089 | SourceRange ArgRange) { | ||||
4090 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||
4091 | // scalar or vector data type argument..." | ||||
4092 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||
4093 | // type (C99 6.2.5p18) or void. | ||||
4094 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||
4095 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||
4096 | << T << ArgRange; | ||||
4097 | return true; | ||||
4098 | } | ||||
4099 | |||||
4100 | assert((T->isVoidType() || !T->isIncompleteType()) &&(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4101, __extension__ __PRETTY_FUNCTION__)) | ||||
4101 | "Scalar types should always be complete")(static_cast <bool> ((T->isVoidType() || !T->isIncompleteType ()) && "Scalar types should always be complete") ? void (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4101, __extension__ __PRETTY_FUNCTION__)); | ||||
4102 | return false; | ||||
4103 | } | ||||
4104 | |||||
4105 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||
4106 | SourceLocation Loc, | ||||
4107 | SourceRange ArgRange, | ||||
4108 | UnaryExprOrTypeTrait TraitKind) { | ||||
4109 | // Invalid types must be hard errors for SFINAE in C++. | ||||
4110 | if (S.LangOpts.CPlusPlus) | ||||
4111 | return true; | ||||
4112 | |||||
4113 | // C99 6.5.3.4p1: | ||||
4114 | if (T->isFunctionType() && | ||||
4115 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||
4116 | TraitKind == UETT_PreferredAlignOf)) { | ||||
4117 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||
4118 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||
4119 | << getTraitSpelling(TraitKind) << ArgRange; | ||||
4120 | return false; | ||||
4121 | } | ||||
4122 | |||||
4123 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||
4124 | // this is an error (OpenCL v1.1 s6.3.k) | ||||
4125 | if (T->isVoidType()) { | ||||
4126 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||
4127 | : diag::ext_sizeof_alignof_void_type; | ||||
4128 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||
4129 | return false; | ||||
4130 | } | ||||
4131 | |||||
4132 | return true; | ||||
4133 | } | ||||
4134 | |||||
4135 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||
4136 | SourceLocation Loc, | ||||
4137 | SourceRange ArgRange, | ||||
4138 | UnaryExprOrTypeTrait TraitKind) { | ||||
4139 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||
4140 | // runtime doesn't allow it. | ||||
4141 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||
4142 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||
4143 | << T << (TraitKind == UETT_SizeOf) | ||||
4144 | << ArgRange; | ||||
4145 | return true; | ||||
4146 | } | ||||
4147 | |||||
4148 | return false; | ||||
4149 | } | ||||
4150 | |||||
4151 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||
4152 | /// pointer type is equal to T) and emit a warning if it is. | ||||
4153 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||
4154 | Expr *E) { | ||||
4155 | // Don't warn if the operation changed the type. | ||||
4156 | if (T != E->getType()) | ||||
4157 | return; | ||||
4158 | |||||
4159 | // Now look for array decays. | ||||
4160 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||
4161 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||
4162 | return; | ||||
4163 | |||||
4164 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||
4165 | << ICE->getType() | ||||
4166 | << ICE->getSubExpr()->getType(); | ||||
4167 | } | ||||
4168 | |||||
4169 | /// Check the constraints on expression operands to unary type expression | ||||
4170 | /// and type traits. | ||||
4171 | /// | ||||
4172 | /// Completes any types necessary and validates the constraints on the operand | ||||
4173 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||
4174 | /// the expression as it completes the type for that expression through template | ||||
4175 | /// instantiation, etc. | ||||
4176 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||
4177 | UnaryExprOrTypeTrait ExprKind) { | ||||
4178 | QualType ExprTy = E->getType(); | ||||
4179 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4179, __extension__ __PRETTY_FUNCTION__)); | ||||
4180 | |||||
4181 | bool IsUnevaluatedOperand = | ||||
4182 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||
4183 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||
4184 | if (IsUnevaluatedOperand) { | ||||
4185 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||
4186 | if (Result.isInvalid()) | ||||
4187 | return true; | ||||
4188 | E = Result.get(); | ||||
4189 | } | ||||
4190 | |||||
4191 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||
4192 | // so side effects could result in unintended consequences. | ||||
4193 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||
4194 | // used to build SFINAE gadgets. | ||||
4195 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||
4196 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||
4197 | !E->isInstantiationDependent() && | ||||
4198 | E->HasSideEffects(Context, false)) | ||||
4199 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
4200 | |||||
4201 | if (ExprKind == UETT_VecStep) | ||||
4202 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4203 | E->getSourceRange()); | ||||
4204 | |||||
4205 | // Explicitly list some types as extensions. | ||||
4206 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4207 | E->getSourceRange(), ExprKind)) | ||||
4208 | return false; | ||||
4209 | |||||
4210 | // 'alignof' applied to an expression only requires the base element type of | ||||
4211 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||
4212 | // be complete (and will attempt to complete it if it's an array of unknown | ||||
4213 | // bound). | ||||
4214 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4215 | if (RequireCompleteSizedType( | ||||
4216 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||
4217 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4218 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4219 | return true; | ||||
4220 | } else { | ||||
4221 | if (RequireCompleteSizedExprType( | ||||
4222 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4223 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4224 | return true; | ||||
4225 | } | ||||
4226 | |||||
4227 | // Completing the expression's type may have changed it. | ||||
4228 | ExprTy = E->getType(); | ||||
4229 | assert(!ExprTy->isReferenceType())(static_cast <bool> (!ExprTy->isReferenceType()) ? void (0) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4229, __extension__ __PRETTY_FUNCTION__)); | ||||
4230 | |||||
4231 | if (ExprTy->isFunctionType()) { | ||||
4232 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||
4233 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||
4234 | return true; | ||||
4235 | } | ||||
4236 | |||||
4237 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||
4238 | E->getSourceRange(), ExprKind)) | ||||
4239 | return true; | ||||
4240 | |||||
4241 | if (ExprKind == UETT_SizeOf) { | ||||
4242 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
4243 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||
4244 | QualType OType = PVD->getOriginalType(); | ||||
4245 | QualType Type = PVD->getType(); | ||||
4246 | if (Type->isPointerType() && OType->isArrayType()) { | ||||
4247 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||
4248 | << Type << OType; | ||||
4249 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||
4250 | } | ||||
4251 | } | ||||
4252 | } | ||||
4253 | |||||
4254 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||
4255 | // decays into a pointer and returns an unintended result. This is most | ||||
4256 | // likely a typo for "sizeof(array) op x". | ||||
4257 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||
4258 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4259 | BO->getLHS()); | ||||
4260 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4261 | BO->getRHS()); | ||||
4262 | } | ||||
4263 | } | ||||
4264 | |||||
4265 | return false; | ||||
4266 | } | ||||
4267 | |||||
4268 | /// Check the constraints on operands to unary expression and type | ||||
4269 | /// traits. | ||||
4270 | /// | ||||
4271 | /// This will complete any types necessary, and validate the various constraints | ||||
4272 | /// on those operands. | ||||
4273 | /// | ||||
4274 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||
4275 | /// C99 6.3.2.1p[2-4] all state: | ||||
4276 | /// Except when it is the operand of the sizeof operator ... | ||||
4277 | /// | ||||
4278 | /// C++ [expr.sizeof]p4 | ||||
4279 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||
4280 | /// standard conversions are not applied to the operand of sizeof. | ||||
4281 | /// | ||||
4282 | /// This policy is followed for all of the unary trait expressions. | ||||
4283 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||
4284 | SourceLocation OpLoc, | ||||
4285 | SourceRange ExprRange, | ||||
4286 | UnaryExprOrTypeTrait ExprKind) { | ||||
4287 | if (ExprType->isDependentType()) | ||||
4288 | return false; | ||||
4289 | |||||
4290 | // C++ [expr.sizeof]p2: | ||||
4291 | // When applied to a reference or a reference type, the result | ||||
4292 | // is the size of the referenced type. | ||||
4293 | // C++11 [expr.alignof]p3: | ||||
4294 | // When alignof is applied to a reference type, the result | ||||
4295 | // shall be the alignment of the referenced type. | ||||
4296 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||
4297 | ExprType = Ref->getPointeeType(); | ||||
4298 | |||||
4299 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||
4300 | // When alignof or _Alignof is applied to an array type, the result | ||||
4301 | // is the alignment of the element type. | ||||
4302 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||
4303 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||
4304 | ExprType = Context.getBaseElementType(ExprType); | ||||
4305 | |||||
4306 | if (ExprKind == UETT_VecStep) | ||||
4307 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||
4308 | |||||
4309 | // Explicitly list some types as extensions. | ||||
4310 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||
4311 | ExprKind)) | ||||
4312 | return false; | ||||
4313 | |||||
4314 | if (RequireCompleteSizedType( | ||||
4315 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4316 | getTraitSpelling(ExprKind), ExprRange)) | ||||
4317 | return true; | ||||
4318 | |||||
4319 | if (ExprType->isFunctionType()) { | ||||
4320 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||
4321 | << getTraitSpelling(ExprKind) << ExprRange; | ||||
4322 | return true; | ||||
4323 | } | ||||
4324 | |||||
4325 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||
4326 | ExprKind)) | ||||
4327 | return true; | ||||
4328 | |||||
4329 | return false; | ||||
4330 | } | ||||
4331 | |||||
4332 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||
4333 | // Cannot know anything else if the expression is dependent. | ||||
4334 | if (E->isTypeDependent()) | ||||
4335 | return false; | ||||
4336 | |||||
4337 | if (E->getObjectKind() == OK_BitField) { | ||||
4338 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||
4339 | << 1 << E->getSourceRange(); | ||||
4340 | return true; | ||||
4341 | } | ||||
4342 | |||||
4343 | ValueDecl *D = nullptr; | ||||
4344 | Expr *Inner = E->IgnoreParens(); | ||||
4345 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||
4346 | D = DRE->getDecl(); | ||||
4347 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||
4348 | D = ME->getMemberDecl(); | ||||
4349 | } | ||||
4350 | |||||
4351 | // If it's a field, require the containing struct to have a | ||||
4352 | // complete definition so that we can compute the layout. | ||||
4353 | // | ||||
4354 | // This can happen in C++11 onwards, either by naming the member | ||||
4355 | // in a way that is not transformed into a member access expression | ||||
4356 | // (in an unevaluated operand, for instance), or by naming the member | ||||
4357 | // in a trailing-return-type. | ||||
4358 | // | ||||
4359 | // For the record, since __alignof__ on expressions is a GCC | ||||
4360 | // extension, GCC seems to permit this but always gives the | ||||
4361 | // nonsensical answer 0. | ||||
4362 | // | ||||
4363 | // We don't really need the layout here --- we could instead just | ||||
4364 | // directly check for all the appropriate alignment-lowing | ||||
4365 | // attributes --- but that would require duplicating a lot of | ||||
4366 | // logic that just isn't worth duplicating for such a marginal | ||||
4367 | // use-case. | ||||
4368 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||
4369 | // Fast path this check, since we at least know the record has a | ||||
4370 | // definition if we can find a member of it. | ||||
4371 | if (!FD->getParent()->isCompleteDefinition()) { | ||||
4372 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||
4373 | << E->getSourceRange(); | ||||
4374 | return true; | ||||
4375 | } | ||||
4376 | |||||
4377 | // Otherwise, if it's a field, and the field doesn't have | ||||
4378 | // reference type, then it must have a complete type (or be a | ||||
4379 | // flexible array member, which we explicitly want to | ||||
4380 | // white-list anyway), which makes the following checks trivial. | ||||
4381 | if (!FD->getType()->isReferenceType()) | ||||
4382 | return false; | ||||
4383 | } | ||||
4384 | |||||
4385 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||
4386 | } | ||||
4387 | |||||
4388 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||
4389 | E = E->IgnoreParens(); | ||||
4390 | |||||
4391 | // Cannot know anything else if the expression is dependent. | ||||
4392 | if (E->isTypeDependent()) | ||||
4393 | return false; | ||||
4394 | |||||
4395 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||
4396 | } | ||||
4397 | |||||
4398 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||
4399 | CapturingScopeInfo *CSI) { | ||||
4400 | assert(T->isVariablyModifiedType())(static_cast <bool> (T->isVariablyModifiedType()) ? void (0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4400, __extension__ __PRETTY_FUNCTION__)); | ||||
4401 | assert(CSI != nullptr)(static_cast <bool> (CSI != nullptr) ? void (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4401, __extension__ __PRETTY_FUNCTION__)); | ||||
4402 | |||||
4403 | // We're going to walk down into the type and look for VLA expressions. | ||||
4404 | do { | ||||
4405 | const Type *Ty = T.getTypePtr(); | ||||
4406 | switch (Ty->getTypeClass()) { | ||||
4407 | #define TYPE(Class, Base) | ||||
4408 | #define ABSTRACT_TYPE(Class, Base) | ||||
4409 | #define NON_CANONICAL_TYPE(Class, Base) | ||||
4410 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||
4411 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||
4412 | #include "clang/AST/TypeNodes.inc" | ||||
4413 | T = QualType(); | ||||
4414 | break; | ||||
4415 | // These types are never variably-modified. | ||||
4416 | case Type::Builtin: | ||||
4417 | case Type::Complex: | ||||
4418 | case Type::Vector: | ||||
4419 | case Type::ExtVector: | ||||
4420 | case Type::ConstantMatrix: | ||||
4421 | case Type::Record: | ||||
4422 | case Type::Enum: | ||||
4423 | case Type::Elaborated: | ||||
4424 | case Type::TemplateSpecialization: | ||||
4425 | case Type::ObjCObject: | ||||
4426 | case Type::ObjCInterface: | ||||
4427 | case Type::ObjCObjectPointer: | ||||
4428 | case Type::ObjCTypeParam: | ||||
4429 | case Type::Pipe: | ||||
4430 | case Type::ExtInt: | ||||
4431 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4431); | ||||
4432 | case Type::Adjusted: | ||||
4433 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||
4434 | break; | ||||
4435 | case Type::Decayed: | ||||
4436 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||
4437 | break; | ||||
4438 | case Type::Pointer: | ||||
4439 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
4440 | break; | ||||
4441 | case Type::BlockPointer: | ||||
4442 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
4443 | break; | ||||
4444 | case Type::LValueReference: | ||||
4445 | case Type::RValueReference: | ||||
4446 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
4447 | break; | ||||
4448 | case Type::MemberPointer: | ||||
4449 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
4450 | break; | ||||
4451 | case Type::ConstantArray: | ||||
4452 | case Type::IncompleteArray: | ||||
4453 | // Losing element qualification here is fine. | ||||
4454 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
4455 | break; | ||||
4456 | case Type::VariableArray: { | ||||
4457 | // Losing element qualification here is fine. | ||||
4458 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||
4459 | |||||
4460 | // Unknown size indication requires no size computation. | ||||
4461 | // Otherwise, evaluate and record it. | ||||
4462 | auto Size = VAT->getSizeExpr(); | ||||
4463 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||
4464 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||
4465 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||
4466 | |||||
4467 | T = VAT->getElementType(); | ||||
4468 | break; | ||||
4469 | } | ||||
4470 | case Type::FunctionProto: | ||||
4471 | case Type::FunctionNoProto: | ||||
4472 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||
4473 | break; | ||||
4474 | case Type::Paren: | ||||
4475 | case Type::TypeOf: | ||||
4476 | case Type::UnaryTransform: | ||||
4477 | case Type::Attributed: | ||||
4478 | case Type::SubstTemplateTypeParm: | ||||
4479 | case Type::MacroQualified: | ||||
4480 | // Keep walking after single level desugaring. | ||||
4481 | T = T.getSingleStepDesugaredType(Context); | ||||
4482 | break; | ||||
4483 | case Type::Typedef: | ||||
4484 | T = cast<TypedefType>(Ty)->desugar(); | ||||
4485 | break; | ||||
4486 | case Type::Decltype: | ||||
4487 | T = cast<DecltypeType>(Ty)->desugar(); | ||||
4488 | break; | ||||
4489 | case Type::Auto: | ||||
4490 | case Type::DeducedTemplateSpecialization: | ||||
4491 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||
4492 | break; | ||||
4493 | case Type::TypeOfExpr: | ||||
4494 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||
4495 | break; | ||||
4496 | case Type::Atomic: | ||||
4497 | T = cast<AtomicType>(Ty)->getValueType(); | ||||
4498 | break; | ||||
4499 | } | ||||
4500 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||
4501 | } | ||||
4502 | |||||
4503 | /// Build a sizeof or alignof expression given a type operand. | ||||
4504 | ExprResult | ||||
4505 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||
4506 | SourceLocation OpLoc, | ||||
4507 | UnaryExprOrTypeTrait ExprKind, | ||||
4508 | SourceRange R) { | ||||
4509 | if (!TInfo) | ||||
4510 | return ExprError(); | ||||
4511 | |||||
4512 | QualType T = TInfo->getType(); | ||||
4513 | |||||
4514 | if (!T->isDependentType() && | ||||
4515 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||
4516 | return ExprError(); | ||||
4517 | |||||
4518 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||
4519 | if (auto *TT = T->getAs<TypedefType>()) { | ||||
4520 | for (auto I = FunctionScopes.rbegin(), | ||||
4521 | E = std::prev(FunctionScopes.rend()); | ||||
4522 | I != E; ++I) { | ||||
4523 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
4524 | if (CSI == nullptr) | ||||
4525 | break; | ||||
4526 | DeclContext *DC = nullptr; | ||||
4527 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
4528 | DC = LSI->CallOperator; | ||||
4529 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
4530 | DC = CRSI->TheCapturedDecl; | ||||
4531 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
4532 | DC = BSI->TheDecl; | ||||
4533 | if (DC) { | ||||
4534 | if (DC->containsDecl(TT->getDecl())) | ||||
4535 | break; | ||||
4536 | captureVariablyModifiedType(Context, T, CSI); | ||||
4537 | } | ||||
4538 | } | ||||
4539 | } | ||||
4540 | } | ||||
4541 | |||||
4542 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4543 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4544 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||
4545 | } | ||||
4546 | |||||
4547 | /// Build a sizeof or alignof expression given an expression | ||||
4548 | /// operand. | ||||
4549 | ExprResult | ||||
4550 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||
4551 | UnaryExprOrTypeTrait ExprKind) { | ||||
4552 | ExprResult PE = CheckPlaceholderExpr(E); | ||||
4553 | if (PE.isInvalid()) | ||||
4554 | return ExprError(); | ||||
4555 | |||||
4556 | E = PE.get(); | ||||
4557 | |||||
4558 | // Verify that the operand is valid. | ||||
4559 | bool isInvalid = false; | ||||
4560 | if (E->isTypeDependent()) { | ||||
4561 | // Delay type-checking for type-dependent expressions. | ||||
4562 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4563 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||
4564 | } else if (ExprKind == UETT_VecStep) { | ||||
4565 | isInvalid = CheckVecStepExpr(E); | ||||
4566 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||
4567 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||
4568 | isInvalid = true; | ||||
4569 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||
4570 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||
4571 | isInvalid = true; | ||||
4572 | } else { | ||||
4573 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||
4574 | } | ||||
4575 | |||||
4576 | if (isInvalid) | ||||
4577 | return ExprError(); | ||||
4578 | |||||
4579 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||
4580 | PE = TransformToPotentiallyEvaluated(E); | ||||
4581 | if (PE.isInvalid()) return ExprError(); | ||||
4582 | E = PE.get(); | ||||
4583 | } | ||||
4584 | |||||
4585 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4586 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4587 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||
4588 | } | ||||
4589 | |||||
4590 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||
4591 | /// expr and the same for @c alignof and @c __alignof | ||||
4592 | /// Note that the ArgRange is invalid if isType is false. | ||||
4593 | ExprResult | ||||
4594 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||
4595 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||
4596 | void *TyOrEx, SourceRange ArgRange) { | ||||
4597 | // If error parsing type, ignore. | ||||
4598 | if (!TyOrEx) return ExprError(); | ||||
4599 | |||||
4600 | if (IsType) { | ||||
4601 | TypeSourceInfo *TInfo; | ||||
4602 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||
4603 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||
4604 | } | ||||
4605 | |||||
4606 | Expr *ArgEx = (Expr *)TyOrEx; | ||||
4607 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||
4608 | return Result; | ||||
4609 | } | ||||
4610 | |||||
4611 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||
4612 | bool IsReal) { | ||||
4613 | if (V.get()->isTypeDependent()) | ||||
4614 | return S.Context.DependentTy; | ||||
4615 | |||||
4616 | // _Real and _Imag are only l-values for normal l-values. | ||||
4617 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||
4618 | V = S.DefaultLvalueConversion(V.get()); | ||||
4619 | if (V.isInvalid()) | ||||
4620 | return QualType(); | ||||
4621 | } | ||||
4622 | |||||
4623 | // These operators return the element type of a complex type. | ||||
4624 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||
4625 | return CT->getElementType(); | ||||
4626 | |||||
4627 | // Otherwise they pass through real integer and floating point types here. | ||||
4628 | if (V.get()->getType()->isArithmeticType()) | ||||
4629 | return V.get()->getType(); | ||||
4630 | |||||
4631 | // Test for placeholders. | ||||
4632 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||
4633 | if (PR.isInvalid()) return QualType(); | ||||
4634 | if (PR.get() != V.get()) { | ||||
4635 | V = PR; | ||||
4636 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||
4637 | } | ||||
4638 | |||||
4639 | // Reject anything else. | ||||
4640 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||
4641 | << (IsReal ? "__real" : "__imag"); | ||||
4642 | return QualType(); | ||||
4643 | } | ||||
4644 | |||||
4645 | |||||
4646 | |||||
4647 | ExprResult | ||||
4648 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
4649 | tok::TokenKind Kind, Expr *Input) { | ||||
4650 | UnaryOperatorKind Opc; | ||||
4651 | switch (Kind) { | ||||
4652 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4652); | ||||
4653 | case tok::plusplus: Opc = UO_PostInc; break; | ||||
4654 | case tok::minusminus: Opc = UO_PostDec; break; | ||||
4655 | } | ||||
4656 | |||||
4657 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||
4658 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||
4659 | if (Result.isInvalid()) return ExprError(); | ||||
4660 | Input = Result.get(); | ||||
4661 | |||||
4662 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||
4663 | } | ||||
4664 | |||||
4665 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||
4666 | /// | ||||
4667 | /// \return true on error | ||||
4668 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||
4669 | SourceLocation opLoc, | ||||
4670 | Expr *op) { | ||||
4671 | assert(op->getType()->isObjCObjectPointerType())(static_cast <bool> (op->getType()->isObjCObjectPointerType ()) ? void (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4671, __extension__ __PRETTY_FUNCTION__)); | ||||
4672 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||
4673 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||
4674 | return false; | ||||
4675 | |||||
4676 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||
4677 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||
4678 | << op->getSourceRange(); | ||||
4679 | return true; | ||||
4680 | } | ||||
4681 | |||||
4682 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||
4683 | auto *BaseNoParens = Base->IgnoreParens(); | ||||
4684 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||
4685 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||
4686 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||
4687 | } | ||||
4688 | |||||
4689 | ExprResult | ||||
4690 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||
4691 | Expr *idx, SourceLocation rbLoc) { | ||||
4692 | if (base && !base->getType().isNull() && | ||||
4693 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||
4694 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||
4695 | SourceLocation(), /*Length*/ nullptr, | ||||
4696 | /*Stride=*/nullptr, rbLoc); | ||||
4697 | |||||
4698 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
4699 | if (isa<ParenListExpr>(base)) { | ||||
4700 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||
4701 | if (result.isInvalid()) return ExprError(); | ||||
4702 | base = result.get(); | ||||
4703 | } | ||||
4704 | |||||
4705 | // Check if base and idx form a MatrixSubscriptExpr. | ||||
4706 | // | ||||
4707 | // Helper to check for comma expressions, which are not allowed as indices for | ||||
4708 | // matrix subscript expressions. | ||||
4709 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||
4710 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||
4711 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||
4712 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4713 | return true; | ||||
4714 | } | ||||
4715 | return false; | ||||
4716 | }; | ||||
4717 | // The matrix subscript operator ([][])is considered a single operator. | ||||
4718 | // Separating the index expressions by parenthesis is not allowed. | ||||
4719 | if (base->getType()->isSpecificPlaceholderType( | ||||
4720 | BuiltinType::IncompleteMatrixIdx) && | ||||
4721 | !isa<MatrixSubscriptExpr>(base)) { | ||||
4722 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||
4723 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4724 | return ExprError(); | ||||
4725 | } | ||||
4726 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||
4727 | // MatrixSubscriptExpr. | ||||
4728 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||
4729 | if (matSubscriptE) { | ||||
4730 | if (CheckAndReportCommaError(idx)) | ||||
4731 | return ExprError(); | ||||
4732 | |||||
4733 | assert(matSubscriptE->isIncomplete() &&(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4734, __extension__ __PRETTY_FUNCTION__)) | ||||
4734 | "base has to be an incomplete matrix subscript")(static_cast <bool> (matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript") ? void (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4734, __extension__ __PRETTY_FUNCTION__)); | ||||
4735 | return CreateBuiltinMatrixSubscriptExpr( | ||||
4736 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||
4737 | } | ||||
4738 | |||||
4739 | // Handle any non-overload placeholder types in the base and index | ||||
4740 | // expressions. We can't handle overloads here because the other | ||||
4741 | // operand might be an overloadable type, in which case the overload | ||||
4742 | // resolution for the operator overload should get the first crack | ||||
4743 | // at the overload. | ||||
4744 | bool IsMSPropertySubscript = false; | ||||
4745 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||
4746 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||
4747 | if (!IsMSPropertySubscript) { | ||||
4748 | ExprResult result = CheckPlaceholderExpr(base); | ||||
4749 | if (result.isInvalid()) | ||||
4750 | return ExprError(); | ||||
4751 | base = result.get(); | ||||
4752 | } | ||||
4753 | } | ||||
4754 | |||||
4755 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||
4756 | if (base->getType()->isMatrixType()) { | ||||
4757 | if (CheckAndReportCommaError(idx)) | ||||
4758 | return ExprError(); | ||||
4759 | |||||
4760 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||
4761 | } | ||||
4762 | |||||
4763 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||
4764 | if (getLangOpts().CPlusPlus20 && | ||||
4765 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||
4766 | (isa<CXXOperatorCallExpr>(idx) && | ||||
4767 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||
4768 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||
4769 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4770 | } | ||||
4771 | |||||
4772 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||
4773 | ExprResult result = CheckPlaceholderExpr(idx); | ||||
4774 | if (result.isInvalid()) return ExprError(); | ||||
4775 | idx = result.get(); | ||||
4776 | } | ||||
4777 | |||||
4778 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4779 | if (getLangOpts().CPlusPlus && | ||||
4780 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||
4781 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||
4782 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4783 | } | ||||
4784 | |||||
4785 | // MSDN, property (C++) | ||||
4786 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||
4787 | // This attribute can also be used in the declaration of an empty array in a | ||||
4788 | // class or structure definition. For example: | ||||
4789 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||
4790 | // The above statement indicates that x[] can be used with one or more array | ||||
4791 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||
4792 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||
4793 | if (IsMSPropertySubscript) { | ||||
4794 | // Build MS property subscript expression if base is MS property reference | ||||
4795 | // or MS property subscript. | ||||
4796 | return new (Context) MSPropertySubscriptExpr( | ||||
4797 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||
4798 | } | ||||
4799 | |||||
4800 | // Use C++ overloaded-operator rules if either operand has record | ||||
4801 | // type. The spec says to do this if either type is *overloadable*, | ||||
4802 | // but enum types can't declare subscript operators or conversion | ||||
4803 | // operators, so there's nothing interesting for overload resolution | ||||
4804 | // to do if there aren't any record types involved. | ||||
4805 | // | ||||
4806 | // ObjC pointers have their own subscripting logic that is not tied | ||||
4807 | // to overload resolution and so should not take this path. | ||||
4808 | if (getLangOpts().CPlusPlus && | ||||
4809 | (base->getType()->isRecordType() || | ||||
4810 | (!base->getType()->isObjCObjectPointerType() && | ||||
4811 | idx->getType()->isRecordType()))) { | ||||
4812 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||
4813 | } | ||||
4814 | |||||
4815 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||
4816 | |||||
4817 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||
4818 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||
4819 | |||||
4820 | return Res; | ||||
4821 | } | ||||
4822 | |||||
4823 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||
4824 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||
4825 | InitializationKind Kind = | ||||
4826 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||
4827 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||
4828 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||
4829 | } | ||||
4830 | |||||
4831 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||
4832 | Expr *ColumnIdx, | ||||
4833 | SourceLocation RBLoc) { | ||||
4834 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||
4835 | if (BaseR.isInvalid()) | ||||
4836 | return BaseR; | ||||
4837 | Base = BaseR.get(); | ||||
4838 | |||||
4839 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||
4840 | if (RowR.isInvalid()) | ||||
4841 | return RowR; | ||||
4842 | RowIdx = RowR.get(); | ||||
4843 | |||||
4844 | if (!ColumnIdx) | ||||
4845 | return new (Context) MatrixSubscriptExpr( | ||||
4846 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||
4847 | |||||
4848 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||
4849 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||
4850 | ColumnIdx->isTypeDependent()) | ||||
4851 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4852 | Context.DependentTy, RBLoc); | ||||
4853 | |||||
4854 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||
4855 | if (ColumnR.isInvalid()) | ||||
4856 | return ColumnR; | ||||
4857 | ColumnIdx = ColumnR.get(); | ||||
4858 | |||||
4859 | // Check that IndexExpr is an integer expression. If it is a constant | ||||
4860 | // expression, check that it is less than Dim (= the number of elements in the | ||||
4861 | // corresponding dimension). | ||||
4862 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||
4863 | bool IsColumnIdx) -> Expr * { | ||||
4864 | if (!IndexExpr->getType()->isIntegerType() && | ||||
4865 | !IndexExpr->isTypeDependent()) { | ||||
4866 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||
4867 | << IsColumnIdx; | ||||
4868 | return nullptr; | ||||
4869 | } | ||||
4870 | |||||
4871 | if (Optional<llvm::APSInt> Idx = | ||||
4872 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||
4873 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||
4874 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||
4875 | << IsColumnIdx << Dim; | ||||
4876 | return nullptr; | ||||
4877 | } | ||||
4878 | } | ||||
4879 | |||||
4880 | ExprResult ConvExpr = | ||||
4881 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||
4882 | assert(!ConvExpr.isInvalid() &&(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4883, __extension__ __PRETTY_FUNCTION__)) | ||||
4883 | "should be able to convert any integer type to size type")(static_cast <bool> (!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? void (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 4883, __extension__ __PRETTY_FUNCTION__)); | ||||
4884 | return ConvExpr.get(); | ||||
4885 | }; | ||||
4886 | |||||
4887 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||
4888 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||
4889 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||
4890 | if (!RowIdx || !ColumnIdx) | ||||
4891 | return ExprError(); | ||||
4892 | |||||
4893 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4894 | MTy->getElementType(), RBLoc); | ||||
4895 | } | ||||
4896 | |||||
4897 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||
4898 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4899 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||
4900 | |||||
4901 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||
4902 | // checked. | ||||
4903 | const MemberExpr *Member = nullptr; | ||||
4904 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||
4905 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||
4906 | |||||
4907 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||
4908 | } | ||||
4909 | |||||
4910 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||
4911 | if (isUnevaluatedContext()) | ||||
4912 | return; | ||||
4913 | |||||
4914 | QualType ResultTy = E->getType(); | ||||
4915 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4916 | |||||
4917 | // Bail if the element is an array since it is not memory access. | ||||
4918 | if (isa<ArrayType>(ResultTy)) | ||||
4919 | return; | ||||
4920 | |||||
4921 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||
4922 | LastRecord.PossibleDerefs.insert(E); | ||||
4923 | return; | ||||
4924 | } | ||||
4925 | |||||
4926 | // Check if the base type is a pointer to a member access of a struct | ||||
4927 | // marked with noderef. | ||||
4928 | const Expr *Base = E->getBase(); | ||||
4929 | QualType BaseTy = Base->getType(); | ||||
4930 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||
4931 | // Not a pointer access | ||||
4932 | return; | ||||
4933 | |||||
4934 | const MemberExpr *Member = nullptr; | ||||
4935 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||
4936 | Member->isArrow()) | ||||
4937 | Base = Member->getBase(); | ||||
4938 | |||||
4939 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||
4940 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||
4941 | LastRecord.PossibleDerefs.insert(E); | ||||
4942 | } | ||||
4943 | } | ||||
4944 | |||||
4945 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||
4946 | Expr *LowerBound, | ||||
4947 | SourceLocation ColonLocFirst, | ||||
4948 | SourceLocation ColonLocSecond, | ||||
4949 | Expr *Length, Expr *Stride, | ||||
4950 | SourceLocation RBLoc) { | ||||
4951 | if (Base->getType()->isPlaceholderType() && | ||||
4952 | !Base->getType()->isSpecificPlaceholderType( | ||||
4953 | BuiltinType::OMPArraySection)) { | ||||
4954 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
4955 | if (Result.isInvalid()) | ||||
4956 | return ExprError(); | ||||
4957 | Base = Result.get(); | ||||
4958 | } | ||||
4959 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||
4960 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||
4961 | if (Result.isInvalid()) | ||||
4962 | return ExprError(); | ||||
4963 | Result = DefaultLvalueConversion(Result.get()); | ||||
4964 | if (Result.isInvalid()) | ||||
4965 | return ExprError(); | ||||
4966 | LowerBound = Result.get(); | ||||
4967 | } | ||||
4968 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||
4969 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||
4970 | if (Result.isInvalid()) | ||||
4971 | return ExprError(); | ||||
4972 | Result = DefaultLvalueConversion(Result.get()); | ||||
4973 | if (Result.isInvalid()) | ||||
4974 | return ExprError(); | ||||
4975 | Length = Result.get(); | ||||
4976 | } | ||||
4977 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||
4978 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||
4979 | if (Result.isInvalid()) | ||||
4980 | return ExprError(); | ||||
4981 | Result = DefaultLvalueConversion(Result.get()); | ||||
4982 | if (Result.isInvalid()) | ||||
4983 | return ExprError(); | ||||
4984 | Stride = Result.get(); | ||||
4985 | } | ||||
4986 | |||||
4987 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4988 | if (Base->isTypeDependent() || | ||||
4989 | (LowerBound && | ||||
4990 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||
4991 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||
4992 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||
4993 | return new (Context) OMPArraySectionExpr( | ||||
4994 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||
4995 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
4996 | } | ||||
4997 | |||||
4998 | // Perform default conversions. | ||||
4999 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||
5000 | QualType ResultTy; | ||||
5001 | if (OriginalTy->isAnyPointerType()) { | ||||
5002 | ResultTy = OriginalTy->getPointeeType(); | ||||
5003 | } else if (OriginalTy->isArrayType()) { | ||||
5004 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||
5005 | } else { | ||||
5006 | return ExprError( | ||||
5007 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||
5008 | << Base->getSourceRange()); | ||||
5009 | } | ||||
5010 | // C99 6.5.2.1p1 | ||||
5011 | if (LowerBound) { | ||||
5012 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||
5013 | LowerBound); | ||||
5014 | if (Res.isInvalid()) | ||||
5015 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||
5016 | diag::err_omp_typecheck_section_not_integer) | ||||
5017 | << 0 << LowerBound->getSourceRange()); | ||||
5018 | LowerBound = Res.get(); | ||||
5019 | |||||
5020 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5021 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5022 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5023 | << 0 << LowerBound->getSourceRange(); | ||||
5024 | } | ||||
5025 | if (Length) { | ||||
5026 | auto Res = | ||||
5027 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||
5028 | if (Res.isInvalid()) | ||||
5029 | return ExprError(Diag(Length->getExprLoc(), | ||||
5030 | diag::err_omp_typecheck_section_not_integer) | ||||
5031 | << 1 << Length->getSourceRange()); | ||||
5032 | Length = Res.get(); | ||||
5033 | |||||
5034 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5035 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5036 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5037 | << 1 << Length->getSourceRange(); | ||||
5038 | } | ||||
5039 | if (Stride) { | ||||
5040 | ExprResult Res = | ||||
5041 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||
5042 | if (Res.isInvalid()) | ||||
5043 | return ExprError(Diag(Stride->getExprLoc(), | ||||
5044 | diag::err_omp_typecheck_section_not_integer) | ||||
5045 | << 1 << Stride->getSourceRange()); | ||||
5046 | Stride = Res.get(); | ||||
5047 | |||||
5048 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5049 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5050 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||
5051 | << 1 << Stride->getSourceRange(); | ||||
5052 | } | ||||
5053 | |||||
5054 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5055 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5056 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||
5057 | // incomplete types are not object types. | ||||
5058 | if (ResultTy->isFunctionType()) { | ||||
5059 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||
5060 | << ResultTy << Base->getSourceRange(); | ||||
5061 | return ExprError(); | ||||
5062 | } | ||||
5063 | |||||
5064 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||
5065 | diag::err_omp_section_incomplete_type, Base)) | ||||
5066 | return ExprError(); | ||||
5067 | |||||
5068 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||
5069 | Expr::EvalResult Result; | ||||
5070 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||
5071 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5072 | // The array section must be a subset of the original array. | ||||
5073 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||
5074 | if (LowerBoundValue.isNegative()) { | ||||
5075 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||
5076 | << LowerBound->getSourceRange(); | ||||
5077 | return ExprError(); | ||||
5078 | } | ||||
5079 | } | ||||
5080 | } | ||||
5081 | |||||
5082 | if (Length) { | ||||
5083 | Expr::EvalResult Result; | ||||
5084 | if (Length->EvaluateAsInt(Result, Context)) { | ||||
5085 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5086 | // The length must evaluate to non-negative integers. | ||||
5087 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||
5088 | if (LengthValue.isNegative()) { | ||||
5089 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||
5090 | << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) | ||||
5091 | << Length->getSourceRange(); | ||||
5092 | return ExprError(); | ||||
5093 | } | ||||
5094 | } | ||||
5095 | } else if (ColonLocFirst.isValid() && | ||||
5096 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||
5097 | !OriginalTy->isVariableArrayType()))) { | ||||
5098 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5099 | // When the size of the array dimension is not known, the length must be | ||||
5100 | // specified explicitly. | ||||
5101 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||
5102 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||
5103 | return ExprError(); | ||||
5104 | } | ||||
5105 | |||||
5106 | if (Stride) { | ||||
5107 | Expr::EvalResult Result; | ||||
5108 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||
5109 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5110 | // The stride must evaluate to a positive integer. | ||||
5111 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||
5112 | if (!StrideValue.isStrictlyPositive()) { | ||||
5113 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||
5114 | << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) | ||||
5115 | << Stride->getSourceRange(); | ||||
5116 | return ExprError(); | ||||
5117 | } | ||||
5118 | } | ||||
5119 | } | ||||
5120 | |||||
5121 | if (!Base->getType()->isSpecificPlaceholderType( | ||||
5122 | BuiltinType::OMPArraySection)) { | ||||
5123 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||
5124 | if (Result.isInvalid()) | ||||
5125 | return ExprError(); | ||||
5126 | Base = Result.get(); | ||||
5127 | } | ||||
5128 | return new (Context) OMPArraySectionExpr( | ||||
5129 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||
5130 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5131 | } | ||||
5132 | |||||
5133 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||
5134 | SourceLocation RParenLoc, | ||||
5135 | ArrayRef<Expr *> Dims, | ||||
5136 | ArrayRef<SourceRange> Brackets) { | ||||
5137 | if (Base->getType()->isPlaceholderType()) { | ||||
5138 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5139 | if (Result.isInvalid()) | ||||
5140 | return ExprError(); | ||||
5141 | Result = DefaultLvalueConversion(Result.get()); | ||||
5142 | if (Result.isInvalid()) | ||||
5143 | return ExprError(); | ||||
5144 | Base = Result.get(); | ||||
5145 | } | ||||
5146 | QualType BaseTy = Base->getType(); | ||||
5147 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||
5148 | // required. | ||||
5149 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||
5150 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||
5151 | LParenLoc, RParenLoc, Dims, Brackets); | ||||
5152 | if (!BaseTy->isPointerType() || | ||||
5153 | (!Base->isTypeDependent() && | ||||
5154 | BaseTy->getPointeeType()->isIncompleteType())) | ||||
5155 | return ExprError(Diag(Base->getExprLoc(), | ||||
5156 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||
5157 | << Base->getSourceRange()); | ||||
5158 | |||||
5159 | SmallVector<Expr *, 4> NewDims; | ||||
5160 | bool ErrorFound = false; | ||||
5161 | for (Expr *Dim : Dims) { | ||||
5162 | if (Dim->getType()->isPlaceholderType()) { | ||||
5163 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||
5164 | if (Result.isInvalid()) { | ||||
5165 | ErrorFound = true; | ||||
5166 | continue; | ||||
5167 | } | ||||
5168 | Result = DefaultLvalueConversion(Result.get()); | ||||
5169 | if (Result.isInvalid()) { | ||||
5170 | ErrorFound = true; | ||||
5171 | continue; | ||||
5172 | } | ||||
5173 | Dim = Result.get(); | ||||
5174 | } | ||||
5175 | if (!Dim->isTypeDependent()) { | ||||
5176 | ExprResult Result = | ||||
5177 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||
5178 | if (Result.isInvalid()) { | ||||
5179 | ErrorFound = true; | ||||
5180 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||
5181 | << Dim->getSourceRange(); | ||||
5182 | continue; | ||||
5183 | } | ||||
5184 | Dim = Result.get(); | ||||
5185 | Expr::EvalResult EvResult; | ||||
5186 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||
5187 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||
5188 | // Each si is an integral type expression that must evaluate to a | ||||
5189 | // positive integer. | ||||
5190 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||
5191 | if (!Value.isStrictlyPositive()) { | ||||
5192 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||
5193 | << toString(Value, /*Radix=*/10, /*Signed=*/true) | ||||
5194 | << Dim->getSourceRange(); | ||||
5195 | ErrorFound = true; | ||||
5196 | continue; | ||||
5197 | } | ||||
5198 | } | ||||
5199 | } | ||||
5200 | NewDims.push_back(Dim); | ||||
5201 | } | ||||
5202 | if (ErrorFound) | ||||
5203 | return ExprError(); | ||||
5204 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||
5205 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||
5206 | } | ||||
5207 | |||||
5208 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||
5209 | SourceLocation LLoc, SourceLocation RLoc, | ||||
5210 | ArrayRef<OMPIteratorData> Data) { | ||||
5211 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||
5212 | bool IsCorrect = true; | ||||
5213 | for (const OMPIteratorData &D : Data) { | ||||
5214 | TypeSourceInfo *TInfo = nullptr; | ||||
5215 | SourceLocation StartLoc; | ||||
5216 | QualType DeclTy; | ||||
5217 | if (!D.Type.getAsOpaquePtr()) { | ||||
5218 | // OpenMP 5.0, 2.1.6 Iterators | ||||
5219 | // In an iterator-specifier, if the iterator-type is not specified then | ||||
5220 | // the type of that iterator is of int type. | ||||
5221 | DeclTy = Context.IntTy; | ||||
5222 | StartLoc = D.DeclIdentLoc; | ||||
5223 | } else { | ||||
5224 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||
5225 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5226 | } | ||||
5227 | |||||
5228 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||
5229 | DeclTy->containsUnexpandedParameterPack() || | ||||
5230 | DeclTy->isInstantiationDependentType(); | ||||
5231 | if (!IsDeclTyDependent) { | ||||
5232 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||
5233 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5234 | // The iterator-type must be an integral or pointer type. | ||||
5235 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5236 | << DeclTy; | ||||
5237 | IsCorrect = false; | ||||
5238 | continue; | ||||
5239 | } | ||||
5240 | if (DeclTy.isConstant(Context)) { | ||||
5241 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5242 | // The iterator-type must not be const qualified. | ||||
5243 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5244 | << DeclTy; | ||||
5245 | IsCorrect = false; | ||||
5246 | continue; | ||||
5247 | } | ||||
5248 | } | ||||
5249 | |||||
5250 | // Iterator declaration. | ||||
5251 | assert(D.DeclIdent && "Identifier expected.")(static_cast <bool> (D.DeclIdent && "Identifier expected." ) ? void (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5251, __extension__ __PRETTY_FUNCTION__)); | ||||
5252 | // Always try to create iterator declarator to avoid extra error messages | ||||
5253 | // about unknown declarations use. | ||||
5254 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||
5255 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||
5256 | VD->setImplicit(); | ||||
5257 | if (S) { | ||||
5258 | // Check for conflicting previous declaration. | ||||
5259 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||
5260 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5261 | ForVisibleRedeclaration); | ||||
5262 | Previous.suppressDiagnostics(); | ||||
5263 | LookupName(Previous, S); | ||||
5264 | |||||
5265 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||
5266 | /*AllowInlineNamespace=*/false); | ||||
5267 | if (!Previous.empty()) { | ||||
5268 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||
5269 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||
5270 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
5271 | } else { | ||||
5272 | PushOnScopeChains(VD, S); | ||||
5273 | } | ||||
5274 | } else { | ||||
5275 | CurContext->addDecl(VD); | ||||
5276 | } | ||||
5277 | Expr *Begin = D.Range.Begin; | ||||
5278 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||
5279 | ExprResult BeginRes = | ||||
5280 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||
5281 | Begin = BeginRes.get(); | ||||
5282 | } | ||||
5283 | Expr *End = D.Range.End; | ||||
5284 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||
5285 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||
5286 | End = EndRes.get(); | ||||
5287 | } | ||||
5288 | Expr *Step = D.Range.Step; | ||||
5289 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||
5290 | if (!Step->getType()->isIntegralType(Context)) { | ||||
5291 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||
5292 | << Step << Step->getSourceRange(); | ||||
5293 | IsCorrect = false; | ||||
5294 | continue; | ||||
5295 | } | ||||
5296 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||
5297 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||
5298 | // If the step expression of a range-specification equals zero, the | ||||
5299 | // behavior is unspecified. | ||||
5300 | if (Result && Result->isNullValue()) { | ||||
5301 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||
5302 | << Step << Step->getSourceRange(); | ||||
5303 | IsCorrect = false; | ||||
5304 | continue; | ||||
5305 | } | ||||
5306 | } | ||||
5307 | if (!Begin || !End || !IsCorrect) { | ||||
5308 | IsCorrect = false; | ||||
5309 | continue; | ||||
5310 | } | ||||
5311 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||
5312 | IDElem.IteratorDecl = VD; | ||||
5313 | IDElem.AssignmentLoc = D.AssignLoc; | ||||
5314 | IDElem.Range.Begin = Begin; | ||||
5315 | IDElem.Range.End = End; | ||||
5316 | IDElem.Range.Step = Step; | ||||
5317 | IDElem.ColonLoc = D.ColonLoc; | ||||
5318 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||
5319 | } | ||||
5320 | if (!IsCorrect) { | ||||
5321 | // Invalidate all created iterator declarations if error is found. | ||||
5322 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5323 | if (Decl *ID = D.IteratorDecl) | ||||
5324 | ID->setInvalidDecl(); | ||||
5325 | } | ||||
5326 | return ExprError(); | ||||
5327 | } | ||||
5328 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||
5329 | if (!CurContext->isDependentContext()) { | ||||
5330 | // Build number of ityeration for each iteration range. | ||||
5331 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||
5332 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||
5333 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5334 | // (Endi - Begini) | ||||
5335 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||
5336 | D.Range.Begin); | ||||
5337 | if(!Res.isUsable()) { | ||||
5338 | IsCorrect = false; | ||||
5339 | continue; | ||||
5340 | } | ||||
5341 | ExprResult St, St1; | ||||
5342 | if (D.Range.Step) { | ||||
5343 | St = D.Range.Step; | ||||
5344 | // (Endi - Begini) + Stepi | ||||
5345 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||
5346 | if (!Res.isUsable()) { | ||||
5347 | IsCorrect = false; | ||||
5348 | continue; | ||||
5349 | } | ||||
5350 | // (Endi - Begini) + Stepi - 1 | ||||
5351 | Res = | ||||
5352 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||
5353 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5354 | if (!Res.isUsable()) { | ||||
5355 | IsCorrect = false; | ||||
5356 | continue; | ||||
5357 | } | ||||
5358 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||
5359 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||
5360 | if (!Res.isUsable()) { | ||||
5361 | IsCorrect = false; | ||||
5362 | continue; | ||||
5363 | } | ||||
5364 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||
5365 | // (Begini - Endi) | ||||
5366 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||
5367 | D.Range.Begin, D.Range.End); | ||||
5368 | if (!Res1.isUsable()) { | ||||
5369 | IsCorrect = false; | ||||
5370 | continue; | ||||
5371 | } | ||||
5372 | // (Begini - Endi) - Stepi | ||||
5373 | Res1 = | ||||
5374 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||
5375 | if (!Res1.isUsable()) { | ||||
5376 | IsCorrect = false; | ||||
5377 | continue; | ||||
5378 | } | ||||
5379 | // (Begini - Endi) - Stepi - 1 | ||||
5380 | Res1 = | ||||
5381 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||
5382 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5383 | if (!Res1.isUsable()) { | ||||
5384 | IsCorrect = false; | ||||
5385 | continue; | ||||
5386 | } | ||||
5387 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||
5388 | Res1 = | ||||
5389 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||
5390 | if (!Res1.isUsable()) { | ||||
5391 | IsCorrect = false; | ||||
5392 | continue; | ||||
5393 | } | ||||
5394 | // Stepi > 0. | ||||
5395 | ExprResult CmpRes = | ||||
5396 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||
5397 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||
5398 | if (!CmpRes.isUsable()) { | ||||
5399 | IsCorrect = false; | ||||
5400 | continue; | ||||
5401 | } | ||||
5402 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||
5403 | Res.get(), Res1.get()); | ||||
5404 | if (!Res.isUsable()) { | ||||
5405 | IsCorrect = false; | ||||
5406 | continue; | ||||
5407 | } | ||||
5408 | } | ||||
5409 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||
5410 | if (!Res.isUsable()) { | ||||
5411 | IsCorrect = false; | ||||
5412 | continue; | ||||
5413 | } | ||||
5414 | |||||
5415 | // Build counter update. | ||||
5416 | // Build counter. | ||||
5417 | auto *CounterVD = | ||||
5418 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||
5419 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||
5420 | Res.get()->getType(), nullptr, SC_None); | ||||
5421 | CounterVD->setImplicit(); | ||||
5422 | ExprResult RefRes = | ||||
5423 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||
5424 | D.IteratorDecl->getBeginLoc()); | ||||
5425 | // Build counter update. | ||||
5426 | // I = Begini + counter * Stepi; | ||||
5427 | ExprResult UpdateRes; | ||||
5428 | if (D.Range.Step) { | ||||
5429 | UpdateRes = CreateBuiltinBinOp( | ||||
5430 | D.AssignmentLoc, BO_Mul, | ||||
5431 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||
5432 | } else { | ||||
5433 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||
5434 | } | ||||
5435 | if (!UpdateRes.isUsable()) { | ||||
5436 | IsCorrect = false; | ||||
5437 | continue; | ||||
5438 | } | ||||
5439 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||
5440 | UpdateRes.get()); | ||||
5441 | if (!UpdateRes.isUsable()) { | ||||
5442 | IsCorrect = false; | ||||
5443 | continue; | ||||
5444 | } | ||||
5445 | ExprResult VDRes = | ||||
5446 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||
5447 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||
5448 | D.IteratorDecl->getBeginLoc()); | ||||
5449 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||
5450 | UpdateRes.get()); | ||||
5451 | if (!UpdateRes.isUsable()) { | ||||
5452 | IsCorrect = false; | ||||
5453 | continue; | ||||
5454 | } | ||||
5455 | UpdateRes = | ||||
5456 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||
5457 | if (!UpdateRes.isUsable()) { | ||||
5458 | IsCorrect = false; | ||||
5459 | continue; | ||||
5460 | } | ||||
5461 | ExprResult CounterUpdateRes = | ||||
5462 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||
5463 | if (!CounterUpdateRes.isUsable()) { | ||||
5464 | IsCorrect = false; | ||||
5465 | continue; | ||||
5466 | } | ||||
5467 | CounterUpdateRes = | ||||
5468 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||
5469 | if (!CounterUpdateRes.isUsable()) { | ||||
5470 | IsCorrect = false; | ||||
5471 | continue; | ||||
5472 | } | ||||
5473 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||
5474 | HD.CounterVD = CounterVD; | ||||
5475 | HD.Upper = Res.get(); | ||||
5476 | HD.Update = UpdateRes.get(); | ||||
5477 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||
5478 | } | ||||
5479 | } else { | ||||
5480 | Helpers.assign(ID.size(), {}); | ||||
5481 | } | ||||
5482 | if (!IsCorrect) { | ||||
5483 | // Invalidate all created iterator declarations if error is found. | ||||
5484 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5485 | if (Decl *ID = D.IteratorDecl) | ||||
5486 | ID->setInvalidDecl(); | ||||
5487 | } | ||||
5488 | return ExprError(); | ||||
5489 | } | ||||
5490 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||
5491 | LLoc, RLoc, ID, Helpers); | ||||
5492 | } | ||||
5493 | |||||
5494 | ExprResult | ||||
5495 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||
5496 | Expr *Idx, SourceLocation RLoc) { | ||||
5497 | Expr *LHSExp = Base; | ||||
5498 | Expr *RHSExp = Idx; | ||||
5499 | |||||
5500 | ExprValueKind VK = VK_LValue; | ||||
5501 | ExprObjectKind OK = OK_Ordinary; | ||||
5502 | |||||
5503 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||
5504 | // a non-lvalue array, and an lvalue otherwise. | ||||
5505 | if (getLangOpts().CPlusPlus11) { | ||||
5506 | for (auto *Op : {LHSExp, RHSExp}) { | ||||
5507 | Op = Op->IgnoreImplicit(); | ||||
5508 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||
5509 | VK = VK_XValue; | ||||
5510 | } | ||||
5511 | } | ||||
5512 | |||||
5513 | // Perform default conversions. | ||||
5514 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||
5515 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||
5516 | if (Result.isInvalid()) | ||||
5517 | return ExprError(); | ||||
5518 | LHSExp = Result.get(); | ||||
5519 | } | ||||
5520 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||
5521 | if (Result.isInvalid()) | ||||
5522 | return ExprError(); | ||||
5523 | RHSExp = Result.get(); | ||||
5524 | |||||
5525 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||
5526 | |||||
5527 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||
5528 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||
5529 | // in the subscript position. As a result, we need to derive the array base | ||||
5530 | // and index from the expression types. | ||||
5531 | Expr *BaseExpr, *IndexExpr; | ||||
5532 | QualType ResultType; | ||||
5533 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||
5534 | BaseExpr = LHSExp; | ||||
5535 | IndexExpr = RHSExp; | ||||
5536 | ResultType = Context.DependentTy; | ||||
5537 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||
5538 | BaseExpr = LHSExp; | ||||
5539 | IndexExpr = RHSExp; | ||||
5540 | ResultType = PTy->getPointeeType(); | ||||
5541 | } else if (const ObjCObjectPointerType *PTy = | ||||
5542 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5543 | BaseExpr = LHSExp; | ||||
5544 | IndexExpr = RHSExp; | ||||
5545 | |||||
5546 | // Use custom logic if this should be the pseudo-object subscript | ||||
5547 | // expression. | ||||
5548 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||
5549 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||
5550 | nullptr); | ||||
5551 | |||||
5552 | ResultType = PTy->getPointeeType(); | ||||
5553 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||
5554 | // Handle the uncommon case of "123[Ptr]". | ||||
5555 | BaseExpr = RHSExp; | ||||
5556 | IndexExpr = LHSExp; | ||||
5557 | ResultType = PTy->getPointeeType(); | ||||
5558 | } else if (const ObjCObjectPointerType *PTy = | ||||
5559 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5560 | // Handle the uncommon case of "123[Ptr]". | ||||
5561 | BaseExpr = RHSExp; | ||||
5562 | IndexExpr = LHSExp; | ||||
5563 | ResultType = PTy->getPointeeType(); | ||||
5564 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||
5565 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||
5566 | << ResultType << BaseExpr->getSourceRange(); | ||||
5567 | return ExprError(); | ||||
5568 | } | ||||
5569 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||
5570 | BaseExpr = LHSExp; // vectors: V[123] | ||||
5571 | IndexExpr = RHSExp; | ||||
5572 | // We apply C++ DR1213 to vector subscripting too. | ||||
5573 | if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { | ||||
5574 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5575 | if (Materialized.isInvalid()) | ||||
5576 | return ExprError(); | ||||
5577 | LHSExp = Materialized.get(); | ||||
5578 | } | ||||
5579 | VK = LHSExp->getValueKind(); | ||||
5580 | if (VK != VK_PRValue) | ||||
5581 | OK = OK_VectorComponent; | ||||
5582 | |||||
5583 | ResultType = VTy->getElementType(); | ||||
5584 | QualType BaseType = BaseExpr->getType(); | ||||
5585 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5586 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5587 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5588 | if (Combined != MemberQuals) | ||||
5589 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5590 | } else if (LHSTy->isArrayType()) { | ||||
5591 | // If we see an array that wasn't promoted by | ||||
5592 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||
5593 | // wasn't promoted because of the C90 rule that doesn't | ||||
5594 | // allow promoting non-lvalue arrays. Warn, then | ||||
5595 | // force the promotion here. | ||||
5596 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5597 | << LHSExp->getSourceRange(); | ||||
5598 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||
5599 | CK_ArrayToPointerDecay).get(); | ||||
5600 | LHSTy = LHSExp->getType(); | ||||
5601 | |||||
5602 | BaseExpr = LHSExp; | ||||
5603 | IndexExpr = RHSExp; | ||||
5604 | ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5605 | } else if (RHSTy->isArrayType()) { | ||||
5606 | // Same as previous, except for 123[f().a] case | ||||
5607 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5608 | << RHSExp->getSourceRange(); | ||||
5609 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||
5610 | CK_ArrayToPointerDecay).get(); | ||||
5611 | RHSTy = RHSExp->getType(); | ||||
5612 | |||||
5613 | BaseExpr = RHSExp; | ||||
5614 | IndexExpr = LHSExp; | ||||
5615 | ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
5616 | } else { | ||||
5617 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||
5618 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5619 | } | ||||
5620 | // C99 6.5.2.1p1 | ||||
5621 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||
5622 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||
5623 | << IndexExpr->getSourceRange()); | ||||
5624 | |||||
5625 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5626 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5627 | && !IndexExpr->isTypeDependent()) | ||||
5628 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||
5629 | |||||
5630 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5631 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5632 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||
5633 | // incomplete types are not object types. | ||||
5634 | if (ResultType->isFunctionType()) { | ||||
5635 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||
5636 | << ResultType << BaseExpr->getSourceRange(); | ||||
5637 | return ExprError(); | ||||
5638 | } | ||||
5639 | |||||
5640 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||
5641 | // GNU extension: subscripting on pointer to void | ||||
5642 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||
5643 | << BaseExpr->getSourceRange(); | ||||
5644 | |||||
5645 | // C forbids expressions of unqualified void type from being l-values. | ||||
5646 | // See IsCForbiddenLValueType. | ||||
5647 | if (!ResultType.hasQualifiers()) | ||||
5648 | VK = VK_PRValue; | ||||
5649 | } else if (!ResultType->isDependentType() && | ||||
5650 | RequireCompleteSizedType( | ||||
5651 | LLoc, ResultType, | ||||
5652 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||
5653 | return ExprError(); | ||||
5654 | |||||
5655 | assert(VK == VK_PRValue || LangOpts.CPlusPlus ||(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5656, __extension__ __PRETTY_FUNCTION__)) | ||||
5656 | !ResultType.isCForbiddenLValueType())(static_cast <bool> (VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()) ? void (0) : __assert_fail ("VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5656, __extension__ __PRETTY_FUNCTION__)); | ||||
5657 | |||||
5658 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||
5659 | FunctionScopes.size() > 1) { | ||||
5660 | if (auto *TT = | ||||
5661 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||
5662 | for (auto I = FunctionScopes.rbegin(), | ||||
5663 | E = std::prev(FunctionScopes.rend()); | ||||
5664 | I != E; ++I) { | ||||
5665 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
5666 | if (CSI == nullptr) | ||||
5667 | break; | ||||
5668 | DeclContext *DC = nullptr; | ||||
5669 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
5670 | DC = LSI->CallOperator; | ||||
5671 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
5672 | DC = CRSI->TheCapturedDecl; | ||||
5673 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
5674 | DC = BSI->TheDecl; | ||||
5675 | if (DC) { | ||||
5676 | if (DC->containsDecl(TT->getDecl())) | ||||
5677 | break; | ||||
5678 | captureVariablyModifiedType( | ||||
5679 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||
5680 | } | ||||
5681 | } | ||||
5682 | } | ||||
5683 | } | ||||
5684 | |||||
5685 | return new (Context) | ||||
5686 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||
5687 | } | ||||
5688 | |||||
5689 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||
5690 | ParmVarDecl *Param) { | ||||
5691 | if (Param->hasUnparsedDefaultArg()) { | ||||
5692 | // If we've already cleared out the location for the default argument, | ||||
5693 | // that means we're parsing it right now. | ||||
5694 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||
5695 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||
5696 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||
5697 | Param->setInvalidDecl(); | ||||
5698 | return true; | ||||
5699 | } | ||||
5700 | |||||
5701 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||
5702 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||
5703 | Diag(UnparsedDefaultArgLocs[Param], | ||||
5704 | diag::note_default_argument_declared_here); | ||||
5705 | return true; | ||||
5706 | } | ||||
5707 | |||||
5708 | if (Param->hasUninstantiatedDefaultArg() && | ||||
5709 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
5710 | return true; | ||||
5711 | |||||
5712 | assert(Param->hasInit() && "default argument but no initializer?")(static_cast <bool> (Param->hasInit() && "default argument but no initializer?" ) ? void (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5712, __extension__ __PRETTY_FUNCTION__)); | ||||
5713 | |||||
5714 | // If the default expression creates temporaries, we need to | ||||
5715 | // push them to the current stack of expression temporaries so they'll | ||||
5716 | // be properly destroyed. | ||||
5717 | // FIXME: We should really be rebuilding the default argument with new | ||||
5718 | // bound temporaries; see the comment in PR5810. | ||||
5719 | // We don't need to do that with block decls, though, because | ||||
5720 | // blocks in default argument expression can never capture anything. | ||||
5721 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||
5722 | // Set the "needs cleanups" bit regardless of whether there are | ||||
5723 | // any explicit objects. | ||||
5724 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||
5725 | |||||
5726 | // Append all the objects to the cleanup list. Right now, this | ||||
5727 | // should always be a no-op, because blocks in default argument | ||||
5728 | // expressions should never be able to capture anything. | ||||
5729 | assert(!Init->getNumObjects() &&(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5730, __extension__ __PRETTY_FUNCTION__)) | ||||
5730 | "default argument expression has capturing blocks?")(static_cast <bool> (!Init->getNumObjects() && "default argument expression has capturing blocks?") ? void ( 0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5730, __extension__ __PRETTY_FUNCTION__)); | ||||
5731 | } | ||||
5732 | |||||
5733 | // We already type-checked the argument, so we know it works. | ||||
5734 | // Just mark all of the declarations in this potentially-evaluated expression | ||||
5735 | // as being "referenced". | ||||
5736 | EnterExpressionEvaluationContext EvalContext( | ||||
5737 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
5738 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||
5739 | /*SkipLocalVariables=*/true); | ||||
5740 | return false; | ||||
5741 | } | ||||
5742 | |||||
5743 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||
5744 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||
5745 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")(static_cast <bool> (Param->hasDefaultArg() && "can't build nonexistent default arg") ? void (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5745, __extension__ __PRETTY_FUNCTION__)); | ||||
5746 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||
5747 | return ExprError(); | ||||
5748 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||
5749 | } | ||||
5750 | |||||
5751 | Sema::VariadicCallType | ||||
5752 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||
5753 | Expr *Fn) { | ||||
5754 | if (Proto && Proto->isVariadic()) { | ||||
5755 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||
5756 | return VariadicConstructor; | ||||
5757 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||
5758 | return VariadicBlock; | ||||
5759 | else if (FDecl) { | ||||
5760 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
5761 | if (Method->isInstance()) | ||||
5762 | return VariadicMethod; | ||||
5763 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||
5764 | return VariadicMethod; | ||||
5765 | return VariadicFunction; | ||||
5766 | } | ||||
5767 | return VariadicDoesNotApply; | ||||
5768 | } | ||||
5769 | |||||
5770 | namespace { | ||||
5771 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||
5772 | public: | ||||
5773 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||
5774 | unsigned NumArgs, MemberExpr *ME) | ||||
5775 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||
5776 | FunctionName(FuncName) {} | ||||
5777 | |||||
5778 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
5779 | if (!candidate.getCorrectionSpecifier() || | ||||
5780 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||
5781 | return false; | ||||
5782 | } | ||||
5783 | |||||
5784 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||
5785 | } | ||||
5786 | |||||
5787 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
5788 | return std::make_unique<FunctionCallCCC>(*this); | ||||
5789 | } | ||||
5790 | |||||
5791 | private: | ||||
5792 | const IdentifierInfo *const FunctionName; | ||||
5793 | }; | ||||
5794 | } | ||||
5795 | |||||
5796 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||
5797 | FunctionDecl *FDecl, | ||||
5798 | ArrayRef<Expr *> Args) { | ||||
5799 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||
5800 | DeclarationName FuncName = FDecl->getDeclName(); | ||||
5801 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||
5802 | |||||
5803 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||
5804 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||
5805 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||
5806 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||
5807 | Sema::CTK_ErrorRecovery)) { | ||||
5808 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||
5809 | if (Corrected.isOverloaded()) { | ||||
5810 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||
5811 | OverloadCandidateSet::iterator Best; | ||||
5812 | for (NamedDecl *CD : Corrected) { | ||||
5813 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
5814 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||
5815 | OCS); | ||||
5816 | } | ||||
5817 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||
5818 | case OR_Success: | ||||
5819 | ND = Best->FoundDecl; | ||||
5820 | Corrected.setCorrectionDecl(ND); | ||||
5821 | break; | ||||
5822 | default: | ||||
5823 | break; | ||||
5824 | } | ||||
5825 | } | ||||
5826 | ND = ND->getUnderlyingDecl(); | ||||
5827 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||
5828 | return Corrected; | ||||
5829 | } | ||||
5830 | } | ||||
5831 | return TypoCorrection(); | ||||
5832 | } | ||||
5833 | |||||
5834 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||
5835 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||
5836 | /// function prototype Proto. Call is the call expression itself, and | ||||
5837 | /// Fn is the function expression. For a C++ member function, this | ||||
5838 | /// routine does not attempt to convert the object argument. Returns | ||||
5839 | /// true if the call is ill-formed. | ||||
5840 | bool | ||||
5841 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||
5842 | FunctionDecl *FDecl, | ||||
5843 | const FunctionProtoType *Proto, | ||||
5844 | ArrayRef<Expr *> Args, | ||||
5845 | SourceLocation RParenLoc, | ||||
5846 | bool IsExecConfig) { | ||||
5847 | // Bail out early if calling a builtin with custom typechecking. | ||||
5848 | if (FDecl) | ||||
5849 | if (unsigned ID = FDecl->getBuiltinID()) | ||||
5850 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||
5851 | return false; | ||||
5852 | |||||
5853 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||
5854 | // assignment, to the types of the corresponding parameter, ... | ||||
5855 | unsigned NumParams = Proto->getNumParams(); | ||||
5856 | bool Invalid = false; | ||||
5857 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||
5858 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||
5859 | ? 1 /* block */ | ||||
5860 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||
5861 | : 0 /* function */); | ||||
5862 | |||||
5863 | // If too few arguments are available (and we don't have default | ||||
5864 | // arguments for the remaining parameters), don't make the call. | ||||
5865 | if (Args.size() < NumParams) { | ||||
5866 | if (Args.size() < MinArgs) { | ||||
5867 | TypoCorrection TC; | ||||
5868 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5869 | unsigned diag_id = | ||||
5870 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5871 | ? diag::err_typecheck_call_too_few_args_suggest | ||||
5872 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||
5873 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||
5874 | << static_cast<unsigned>(Args.size()) | ||||
5875 | << TC.getCorrectionRange()); | ||||
5876 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||
5877 | Diag(RParenLoc, | ||||
5878 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5879 | ? diag::err_typecheck_call_too_few_args_one | ||||
5880 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||
5881 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||
5882 | else | ||||
5883 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||
5884 | ? diag::err_typecheck_call_too_few_args | ||||
5885 | : diag::err_typecheck_call_too_few_args_at_least) | ||||
5886 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||
5887 | << Fn->getSourceRange(); | ||||
5888 | |||||
5889 | // Emit the location of the prototype. | ||||
5890 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5891 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5892 | |||||
5893 | return true; | ||||
5894 | } | ||||
5895 | // We reserve space for the default arguments when we create | ||||
5896 | // the call expression, before calling ConvertArgumentsForCall. | ||||
5897 | assert((Call->getNumArgs() == NumParams) &&(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5898, __extension__ __PRETTY_FUNCTION__)) | ||||
5898 | "We should have reserved space for the default arguments before!")(static_cast <bool> ((Call->getNumArgs() == NumParams ) && "We should have reserved space for the default arguments before!" ) ? void (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 5898, __extension__ __PRETTY_FUNCTION__)); | ||||
5899 | } | ||||
5900 | |||||
5901 | // If too many are passed and not variadic, error on the extras and drop | ||||
5902 | // them. | ||||
5903 | if (Args.size() > NumParams) { | ||||
5904 | if (!Proto->isVariadic()) { | ||||
5905 | TypoCorrection TC; | ||||
5906 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5907 | unsigned diag_id = | ||||
5908 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5909 | ? diag::err_typecheck_call_too_many_args_suggest | ||||
5910 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||
5911 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||
5912 | << static_cast<unsigned>(Args.size()) | ||||
5913 | << TC.getCorrectionRange()); | ||||
5914 | } else if (NumParams == 1 && FDecl && | ||||
5915 | FDecl->getParamDecl(0)->getDeclName()) | ||||
5916 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5917 | MinArgs == NumParams | ||||
5918 | ? diag::err_typecheck_call_too_many_args_one | ||||
5919 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||
5920 | << FnKind << FDecl->getParamDecl(0) | ||||
5921 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||
5922 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5923 | Args.back()->getEndLoc()); | ||||
5924 | else | ||||
5925 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5926 | MinArgs == NumParams | ||||
5927 | ? diag::err_typecheck_call_too_many_args | ||||
5928 | : diag::err_typecheck_call_too_many_args_at_most) | ||||
5929 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||
5930 | << Fn->getSourceRange() | ||||
5931 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5932 | Args.back()->getEndLoc()); | ||||
5933 | |||||
5934 | // Emit the location of the prototype. | ||||
5935 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5936 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5937 | |||||
5938 | // This deletes the extra arguments. | ||||
5939 | Call->shrinkNumArgs(NumParams); | ||||
5940 | return true; | ||||
5941 | } | ||||
5942 | } | ||||
5943 | SmallVector<Expr *, 8> AllArgs; | ||||
5944 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||
5945 | |||||
5946 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||
5947 | AllArgs, CallType); | ||||
5948 | if (Invalid) | ||||
5949 | return true; | ||||
5950 | unsigned TotalNumArgs = AllArgs.size(); | ||||
5951 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||
5952 | Call->setArg(i, AllArgs[i]); | ||||
5953 | |||||
5954 | Call->computeDependence(); | ||||
5955 | return false; | ||||
5956 | } | ||||
5957 | |||||
5958 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||
5959 | const FunctionProtoType *Proto, | ||||
5960 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||
5961 | SmallVectorImpl<Expr *> &AllArgs, | ||||
5962 | VariadicCallType CallType, bool AllowExplicit, | ||||
5963 | bool IsListInitialization) { | ||||
5964 | unsigned NumParams = Proto->getNumParams(); | ||||
5965 | bool Invalid = false; | ||||
5966 | size_t ArgIx = 0; | ||||
5967 | // Continue to check argument types (even if we have too few/many args). | ||||
5968 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||
5969 | QualType ProtoArgType = Proto->getParamType(i); | ||||
5970 | |||||
5971 | Expr *Arg; | ||||
5972 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||
5973 | if (ArgIx < Args.size()) { | ||||
5974 | Arg = Args[ArgIx++]; | ||||
5975 | |||||
5976 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||
5977 | diag::err_call_incomplete_argument, Arg)) | ||||
5978 | return true; | ||||
5979 | |||||
5980 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
5981 | bool CFAudited = false; | ||||
5982 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||
5983 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5984 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5985 | Arg = stripARCUnbridgedCast(Arg); | ||||
5986 | else if (getLangOpts().ObjCAutoRefCount && | ||||
5987 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5988 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5989 | CFAudited = true; | ||||
5990 | |||||
5991 | if (Proto->getExtParameterInfo(i).isNoEscape() && | ||||
5992 | ProtoArgType->isBlockPointerType()) | ||||
5993 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||
5994 | BE->getBlockDecl()->setDoesNotEscape(); | ||||
5995 | |||||
5996 | InitializedEntity Entity = | ||||
5997 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||
5998 | ProtoArgType) | ||||
5999 | : InitializedEntity::InitializeParameter( | ||||
6000 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||
6001 | |||||
6002 | // Remember that parameter belongs to a CF audited API. | ||||
6003 | if (CFAudited) | ||||
6004 | Entity.setParameterCFAudited(); | ||||
6005 | |||||
6006 | ExprResult ArgE = PerformCopyInitialization( | ||||
6007 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||
6008 | if (ArgE.isInvalid()) | ||||
6009 | return true; | ||||
6010 | |||||
6011 | Arg = ArgE.getAs<Expr>(); | ||||
6012 | } else { | ||||
6013 | assert(Param && "can't use default arguments without a known callee")(static_cast <bool> (Param && "can't use default arguments without a known callee" ) ? void (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6013, __extension__ __PRETTY_FUNCTION__)); | ||||
6014 | |||||
6015 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||
6016 | if (ArgExpr.isInvalid()) | ||||
6017 | return true; | ||||
6018 | |||||
6019 | Arg = ArgExpr.getAs<Expr>(); | ||||
6020 | } | ||||
6021 | |||||
6022 | // Check for array bounds violations for each argument to the call. This | ||||
6023 | // check only triggers warnings when the argument isn't a more complex Expr | ||||
6024 | // with its own checking, such as a BinaryOperator. | ||||
6025 | CheckArrayAccess(Arg); | ||||
6026 | |||||
6027 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||
6028 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||
6029 | |||||
6030 | AllArgs.push_back(Arg); | ||||
6031 | } | ||||
6032 | |||||
6033 | // If this is a variadic call, handle args passed through "...". | ||||
6034 | if (CallType != VariadicDoesNotApply) { | ||||
6035 | // Assume that extern "C" functions with variadic arguments that | ||||
6036 | // return __unknown_anytype aren't *really* variadic. | ||||
6037 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||
6038 | FDecl->isExternC()) { | ||||
6039 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6040 | QualType paramType; // ignored | ||||
6041 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||
6042 | Invalid |= arg.isInvalid(); | ||||
6043 | AllArgs.push_back(arg.get()); | ||||
6044 | } | ||||
6045 | |||||
6046 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||
6047 | } else { | ||||
6048 | for (Expr *A : Args.slice(ArgIx)) { | ||||
6049 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||
6050 | Invalid |= Arg.isInvalid(); | ||||
6051 | AllArgs.push_back(Arg.get()); | ||||
6052 | } | ||||
6053 | } | ||||
6054 | |||||
6055 | // Check for array bounds violations. | ||||
6056 | for (Expr *A : Args.slice(ArgIx)) | ||||
6057 | CheckArrayAccess(A); | ||||
6058 | } | ||||
6059 | return Invalid; | ||||
6060 | } | ||||
6061 | |||||
6062 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||
6063 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||
6064 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||
6065 | TL = DTL.getOriginalLoc(); | ||||
6066 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||
6067 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||
6068 | << ATL.getLocalSourceRange(); | ||||
6069 | } | ||||
6070 | |||||
6071 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||
6072 | /// array parameter, check that it is non-null, and that if it is formed by | ||||
6073 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||
6074 | /// | ||||
6075 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||
6076 | /// array type derivation, then for each call to the function, the value of the | ||||
6077 | /// corresponding actual argument shall provide access to the first element of | ||||
6078 | /// an array with at least as many elements as specified by the size expression. | ||||
6079 | void | ||||
6080 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||
6081 | ParmVarDecl *Param, | ||||
6082 | const Expr *ArgExpr) { | ||||
6083 | // Static array parameters are not supported in C++. | ||||
6084 | if (!Param || getLangOpts().CPlusPlus) | ||||
6085 | return; | ||||
6086 | |||||
6087 | QualType OrigTy = Param->getOriginalType(); | ||||
6088 | |||||
6089 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||
6090 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||
6091 | return; | ||||
6092 | |||||
6093 | if (ArgExpr->isNullPointerConstant(Context, | ||||
6094 | Expr::NPC_NeverValueDependent)) { | ||||
6095 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||
6096 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6097 | return; | ||||
6098 | } | ||||
6099 | |||||
6100 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||
6101 | if (!CAT) | ||||
6102 | return; | ||||
6103 | |||||
6104 | const ConstantArrayType *ArgCAT = | ||||
6105 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||
6106 | if (!ArgCAT) | ||||
6107 | return; | ||||
6108 | |||||
6109 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||
6110 | ArgCAT->getElementType())) { | ||||
6111 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||
6112 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6113 | << ArgExpr->getSourceRange() | ||||
6114 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||
6115 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||
6116 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6117 | } | ||||
6118 | return; | ||||
6119 | } | ||||
6120 | |||||
6121 | Optional<CharUnits> ArgSize = | ||||
6122 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||
6123 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||
6124 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||
6125 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6126 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||
6127 | << (unsigned)ParmSize->getQuantity() << 1; | ||||
6128 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6129 | } | ||||
6130 | } | ||||
6131 | |||||
6132 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
6133 | /// to have a function type. | ||||
6134 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||
6135 | |||||
6136 | /// Is the given type a placeholder that we need to lower out | ||||
6137 | /// immediately during argument processing? | ||||
6138 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||
6139 | // Placeholders are never sugared. | ||||
6140 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||
6141 | if (!placeholder) return false; | ||||
6142 | |||||
6143 | switch (placeholder->getKind()) { | ||||
6144 | // Ignore all the non-placeholder types. | ||||
6145 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
6146 | case BuiltinType::Id: | ||||
6147 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
6148 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
6149 | case BuiltinType::Id: | ||||
6150 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
6151 | // In practice we'll never use this, since all SVE types are sugared | ||||
6152 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||
6153 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
6154 | case BuiltinType::Id: | ||||
6155 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
6156 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
6157 | case BuiltinType::Id: | ||||
6158 | #include "clang/Basic/PPCTypes.def" | ||||
6159 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6160 | #include "clang/Basic/RISCVVTypes.def" | ||||
6161 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||
6162 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||
6163 | #include "clang/AST/BuiltinTypes.def" | ||||
6164 | return false; | ||||
6165 | |||||
6166 | // We cannot lower out overload sets; they might validly be resolved | ||||
6167 | // by the call machinery. | ||||
6168 | case BuiltinType::Overload: | ||||
6169 | return false; | ||||
6170 | |||||
6171 | // Unbridged casts in ARC can be handled in some call positions and | ||||
6172 | // should be left in place. | ||||
6173 | case BuiltinType::ARCUnbridgedCast: | ||||
6174 | return false; | ||||
6175 | |||||
6176 | // Pseudo-objects should be converted as soon as possible. | ||||
6177 | case BuiltinType::PseudoObject: | ||||
6178 | return true; | ||||
6179 | |||||
6180 | // The debugger mode could theoretically but currently does not try | ||||
6181 | // to resolve unknown-typed arguments based on known parameter types. | ||||
6182 | case BuiltinType::UnknownAny: | ||||
6183 | return true; | ||||
6184 | |||||
6185 | // These are always invalid as call arguments and should be reported. | ||||
6186 | case BuiltinType::BoundMember: | ||||
6187 | case BuiltinType::BuiltinFn: | ||||
6188 | case BuiltinType::IncompleteMatrixIdx: | ||||
6189 | case BuiltinType::OMPArraySection: | ||||
6190 | case BuiltinType::OMPArrayShaping: | ||||
6191 | case BuiltinType::OMPIterator: | ||||
6192 | return true; | ||||
6193 | |||||
6194 | } | ||||
6195 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6195); | ||||
6196 | } | ||||
6197 | |||||
6198 | /// Check an argument list for placeholders that we won't try to | ||||
6199 | /// handle later. | ||||
6200 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||
6201 | // Apply this processing to all the arguments at once instead of | ||||
6202 | // dying at the first failure. | ||||
6203 | bool hasInvalid = false; | ||||
6204 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||
6205 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||
6206 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||
6207 | if (result.isInvalid()) hasInvalid = true; | ||||
6208 | else args[i] = result.get(); | ||||
6209 | } | ||||
6210 | } | ||||
6211 | return hasInvalid; | ||||
6212 | } | ||||
6213 | |||||
6214 | /// If a builtin function has a pointer argument with no explicit address | ||||
6215 | /// space, then it should be able to accept a pointer to any address | ||||
6216 | /// space as input. In order to do this, we need to replace the | ||||
6217 | /// standard builtin declaration with one that uses the same address space | ||||
6218 | /// as the call. | ||||
6219 | /// | ||||
6220 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||
6221 | /// it does not contain any pointer arguments without | ||||
6222 | /// an address space qualifer. Otherwise the rewritten | ||||
6223 | /// FunctionDecl is returned. | ||||
6224 | /// TODO: Handle pointer return types. | ||||
6225 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||
6226 | FunctionDecl *FDecl, | ||||
6227 | MultiExprArg ArgExprs) { | ||||
6228 | |||||
6229 | QualType DeclType = FDecl->getType(); | ||||
6230 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||
6231 | |||||
6232 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||
6233 | ArgExprs.size() < FT->getNumParams()) | ||||
6234 | return nullptr; | ||||
6235 | |||||
6236 | bool NeedsNewDecl = false; | ||||
6237 | unsigned i = 0; | ||||
6238 | SmallVector<QualType, 8> OverloadParams; | ||||
6239 | |||||
6240 | for (QualType ParamType : FT->param_types()) { | ||||
6241 | |||||
6242 | // Convert array arguments to pointer to simplify type lookup. | ||||
6243 | ExprResult ArgRes = | ||||
6244 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||
6245 | if (ArgRes.isInvalid()) | ||||
6246 | return nullptr; | ||||
6247 | Expr *Arg = ArgRes.get(); | ||||
6248 | QualType ArgType = Arg->getType(); | ||||
6249 | if (!ParamType->isPointerType() || | ||||
6250 | ParamType.hasAddressSpace() || | ||||
6251 | !ArgType->isPointerType() || | ||||
6252 | !ArgType->getPointeeType().hasAddressSpace()) { | ||||
6253 | OverloadParams.push_back(ParamType); | ||||
6254 | continue; | ||||
6255 | } | ||||
6256 | |||||
6257 | QualType PointeeType = ParamType->getPointeeType(); | ||||
6258 | if (PointeeType.hasAddressSpace()) | ||||
6259 | continue; | ||||
6260 | |||||
6261 | NeedsNewDecl = true; | ||||
6262 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||
6263 | |||||
6264 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||
6265 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||
6266 | } | ||||
6267 | |||||
6268 | if (!NeedsNewDecl) | ||||
6269 | return nullptr; | ||||
6270 | |||||
6271 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6272 | EPI.Variadic = FT->isVariadic(); | ||||
6273 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||
6274 | OverloadParams, EPI); | ||||
6275 | DeclContext *Parent = FDecl->getParent(); | ||||
6276 | FunctionDecl *OverloadDecl = FunctionDecl::Create( | ||||
6277 | Context, Parent, FDecl->getLocation(), FDecl->getLocation(), | ||||
6278 | FDecl->getIdentifier(), OverloadTy, | ||||
6279 | /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), | ||||
6280 | false, | ||||
6281 | /*hasPrototype=*/true); | ||||
6282 | SmallVector<ParmVarDecl*, 16> Params; | ||||
6283 | FT = cast<FunctionProtoType>(OverloadTy); | ||||
6284 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
6285 | QualType ParamType = FT->getParamType(i); | ||||
6286 | ParmVarDecl *Parm = | ||||
6287 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||
6288 | SourceLocation(), nullptr, ParamType, | ||||
6289 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||
6290 | Parm->setScopeInfo(0, i); | ||||
6291 | Params.push_back(Parm); | ||||
6292 | } | ||||
6293 | OverloadDecl->setParams(Params); | ||||
6294 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||
6295 | return OverloadDecl; | ||||
6296 | } | ||||
6297 | |||||
6298 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||
6299 | FunctionDecl *Callee, | ||||
6300 | MultiExprArg ArgExprs) { | ||||
6301 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||
6302 | // similar attributes) really don't like it when functions are called with an | ||||
6303 | // invalid number of args. | ||||
6304 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||
6305 | /*PartialOverloading=*/false) && | ||||
6306 | !Callee->isVariadic()) | ||||
6307 | return; | ||||
6308 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||
6309 | return; | ||||
6310 | |||||
6311 | if (const EnableIfAttr *Attr = | ||||
6312 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||
6313 | S.Diag(Fn->getBeginLoc(), | ||||
6314 | isa<CXXMethodDecl>(Callee) | ||||
6315 | ? diag::err_ovl_no_viable_member_function_in_call | ||||
6316 | : diag::err_ovl_no_viable_function_in_call) | ||||
6317 | << Callee << Callee->getSourceRange(); | ||||
6318 | S.Diag(Callee->getLocation(), | ||||
6319 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||
6320 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||
6321 | return; | ||||
6322 | } | ||||
6323 | } | ||||
6324 | |||||
6325 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||
6326 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||
6327 | |||||
6328 | const auto GetFunctionLevelDCIfCXXClass = | ||||
6329 | [](Sema &S) -> const CXXRecordDecl * { | ||||
6330 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||
6331 | if (!DC || !DC->getParent()) | ||||
6332 | return nullptr; | ||||
6333 | |||||
6334 | // If the call to some member function was made from within a member | ||||
6335 | // function body 'M' return return 'M's parent. | ||||
6336 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
6337 | return MD->getParent()->getCanonicalDecl(); | ||||
6338 | // else the call was made from within a default member initializer of a | ||||
6339 | // class, so return the class. | ||||
6340 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
6341 | return RD->getCanonicalDecl(); | ||||
6342 | return nullptr; | ||||
6343 | }; | ||||
6344 | // If our DeclContext is neither a member function nor a class (in the | ||||
6345 | // case of a lambda in a default member initializer), we can't have an | ||||
6346 | // enclosing 'this'. | ||||
6347 | |||||
6348 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||
6349 | if (!CurParentClass) | ||||
6350 | return false; | ||||
6351 | |||||
6352 | // The naming class for implicit member functions call is the class in which | ||||
6353 | // name lookup starts. | ||||
6354 | const CXXRecordDecl *const NamingClass = | ||||
6355 | UME->getNamingClass()->getCanonicalDecl(); | ||||
6356 | assert(NamingClass && "Must have naming class even for implicit access")(static_cast <bool> (NamingClass && "Must have naming class even for implicit access" ) ? void (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6356, __extension__ __PRETTY_FUNCTION__)); | ||||
6357 | |||||
6358 | // If the unresolved member functions were found in a 'naming class' that is | ||||
6359 | // related (either the same or derived from) to the class that contains the | ||||
6360 | // member function that itself contained the implicit member access. | ||||
6361 | |||||
6362 | return CurParentClass == NamingClass || | ||||
6363 | CurParentClass->isDerivedFrom(NamingClass); | ||||
6364 | } | ||||
6365 | |||||
6366 | static void | ||||
6367 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6368 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||
6369 | |||||
6370 | if (!UME) | ||||
6371 | return; | ||||
6372 | |||||
6373 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||
6374 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||
6375 | // already been captured, or if this is an implicit member function call (if | ||||
6376 | // it isn't, an attempt to capture 'this' should already have been made). | ||||
6377 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||
6378 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||
6379 | return; | ||||
6380 | |||||
6381 | // Check if the naming class in which the unresolved members were found is | ||||
6382 | // related (same as or is a base of) to the enclosing class. | ||||
6383 | |||||
6384 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||
6385 | return; | ||||
6386 | |||||
6387 | |||||
6388 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||
6389 | // If the enclosing function is not dependent, then this lambda is | ||||
6390 | // capture ready, so if we can capture this, do so. | ||||
6391 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||
6392 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||
6393 | // then go ahead and capture 'this' (since our unresolved overload set | ||||
6394 | // contains at least one non-static member function). | ||||
6395 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||
6396 | S.CheckCXXThisCapture(CallLoc); | ||||
6397 | } else if (S.CurContext->isDependentContext()) { | ||||
6398 | // ... since this is an implicit member reference, that might potentially | ||||
6399 | // involve a 'this' capture, mark 'this' for potential capture in | ||||
6400 | // enclosing lambdas. | ||||
6401 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||
6402 | CurLSI->addPotentialThisCapture(CallLoc); | ||||
6403 | } | ||||
6404 | } | ||||
6405 | |||||
6406 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6407 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6408 | Expr *ExecConfig) { | ||||
6409 | ExprResult Call = | ||||
6410 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6411 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | ||||
6412 | if (Call.isInvalid()) | ||||
6413 | return Call; | ||||
6414 | |||||
6415 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||
6416 | // language modes. | ||||
6417 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||
6418 | if (ULE->hasExplicitTemplateArgs() && | ||||
6419 | ULE->decls_begin() == ULE->decls_end()) { | ||||
6420 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||
6421 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||
6422 | : diag::ext_adl_only_template_id) | ||||
6423 | << ULE->getName(); | ||||
6424 | } | ||||
6425 | } | ||||
6426 | |||||
6427 | if (LangOpts.OpenMP) | ||||
6428 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||
6429 | ExecConfig); | ||||
6430 | |||||
6431 | return Call; | ||||
6432 | } | ||||
6433 | |||||
6434 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||
6435 | /// This provides the location of the left/right parens and a list of comma | ||||
6436 | /// locations. | ||||
6437 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6438 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6439 | Expr *ExecConfig, bool IsExecConfig, | ||||
6440 | bool AllowRecovery) { | ||||
6441 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
6442 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||
6443 | if (Result.isInvalid()) return ExprError(); | ||||
6444 | Fn = Result.get(); | ||||
6445 | |||||
6446 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
6447 | return ExprError(); | ||||
6448 | |||||
6449 | if (getLangOpts().CPlusPlus) { | ||||
6450 | // If this is a pseudo-destructor expression, build the call immediately. | ||||
6451 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||
6452 | if (!ArgExprs.empty()) { | ||||
6453 | // Pseudo-destructor calls should not have any arguments. | ||||
6454 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||
6455 | << FixItHint::CreateRemoval( | ||||
6456 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||
6457 | ArgExprs.back()->getEndLoc())); | ||||
6458 | } | ||||
6459 | |||||
6460 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||
6461 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6462 | } | ||||
6463 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||
6464 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||
6465 | if (result.isInvalid()) return ExprError(); | ||||
6466 | Fn = result.get(); | ||||
6467 | } | ||||
6468 | |||||
6469 | // Determine whether this is a dependent call inside a C++ template, | ||||
6470 | // in which case we won't do any semantic analysis now. | ||||
6471 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||
6472 | if (ExecConfig) { | ||||
6473 | return CUDAKernelCallExpr::Create(Context, Fn, | ||||
6474 | cast<CallExpr>(ExecConfig), ArgExprs, | ||||
6475 | Context.DependentTy, VK_PRValue, | ||||
6476 | RParenLoc, CurFPFeatureOverrides()); | ||||
6477 | } else { | ||||
6478 | |||||
6479 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6480 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||
6481 | Fn->getBeginLoc()); | ||||
6482 | |||||
6483 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6484 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6485 | } | ||||
6486 | } | ||||
6487 | |||||
6488 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||
6489 | if (Fn->getType()->isRecordType()) | ||||
6490 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||
6491 | RParenLoc); | ||||
6492 | |||||
6493 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6494 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6495 | if (result.isInvalid()) return ExprError(); | ||||
6496 | Fn = result.get(); | ||||
6497 | } | ||||
6498 | |||||
6499 | if (Fn->getType() == Context.BoundMemberTy) { | ||||
6500 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6501 | RParenLoc, AllowRecovery); | ||||
6502 | } | ||||
6503 | } | ||||
6504 | |||||
6505 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||
6506 | if (Fn->getType() == Context.OverloadTy) { | ||||
6507 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||
6508 | |||||
6509 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||
6510 | if (!find.HasFormOfMemberPointer) { | ||||
6511 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||
6512 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6513 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6514 | OverloadExpr *ovl = find.Expression; | ||||
6515 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||
6516 | return BuildOverloadedCallExpr( | ||||
6517 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6518 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||
6519 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6520 | RParenLoc, AllowRecovery); | ||||
6521 | } | ||||
6522 | } | ||||
6523 | |||||
6524 | // If we're directly calling a function, get the appropriate declaration. | ||||
6525 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6526 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6527 | if (result.isInvalid()) return ExprError(); | ||||
6528 | Fn = result.get(); | ||||
6529 | } | ||||
6530 | |||||
6531 | Expr *NakedFn = Fn->IgnoreParens(); | ||||
6532 | |||||
6533 | bool CallingNDeclIndirectly = false; | ||||
6534 | NamedDecl *NDecl = nullptr; | ||||
6535 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||
6536 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||
6537 | CallingNDeclIndirectly = true; | ||||
6538 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||
6539 | } | ||||
6540 | } | ||||
6541 | |||||
6542 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||
6543 | NDecl = DRE->getDecl(); | ||||
6544 | |||||
6545 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||
6546 | if (FDecl && FDecl->getBuiltinID()) { | ||||
6547 | // Rewrite the function decl for this builtin by replacing parameters | ||||
6548 | // with no explicit address space with the address space of the arguments | ||||
6549 | // in ArgExprs. | ||||
6550 | if ((FDecl = | ||||
6551 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||
6552 | NDecl = FDecl; | ||||
6553 | Fn = DeclRefExpr::Create( | ||||
6554 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||
6555 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||
6556 | nullptr, DRE->isNonOdrUse()); | ||||
6557 | } | ||||
6558 | } | ||||
6559 | } else if (isa<MemberExpr>(NakedFn)) | ||||
6560 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | ||||
6561 | |||||
6562 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||
6563 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||
6564 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||
6565 | return ExprError(); | ||||
6566 | |||||
6567 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||
6568 | |||||
6569 | // If this expression is a call to a builtin function in HIP device | ||||
6570 | // compilation, allow a pointer-type argument to default address space to be | ||||
6571 | // passed as a pointer-type parameter to a non-default address space. | ||||
6572 | // If Arg is declared in the default address space and Param is declared | ||||
6573 | // in a non-default address space, perform an implicit address space cast to | ||||
6574 | // the parameter type. | ||||
6575 | if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && | ||||
6576 | FD->getBuiltinID()) { | ||||
6577 | for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { | ||||
6578 | ParmVarDecl *Param = FD->getParamDecl(Idx); | ||||
6579 | if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || | ||||
6580 | !ArgExprs[Idx]->getType()->isPointerType()) | ||||
6581 | continue; | ||||
6582 | |||||
6583 | auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); | ||||
6584 | auto ArgTy = ArgExprs[Idx]->getType(); | ||||
6585 | auto ArgPtTy = ArgTy->getPointeeType(); | ||||
6586 | auto ArgAS = ArgPtTy.getAddressSpace(); | ||||
6587 | |||||
6588 | // Only allow implicit casting from a non-default address space pointee | ||||
6589 | // type to a default address space pointee type | ||||
6590 | if (ArgAS != LangAS::Default || ParamAS == LangAS::Default) | ||||
6591 | continue; | ||||
6592 | |||||
6593 | // First, ensure that the Arg is an RValue. | ||||
6594 | if (ArgExprs[Idx]->isGLValue()) { | ||||
6595 | ArgExprs[Idx] = ImplicitCastExpr::Create( | ||||
6596 | Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], | ||||
6597 | nullptr, VK_PRValue, FPOptionsOverride()); | ||||
6598 | } | ||||
6599 | |||||
6600 | // Construct a new arg type with address space of Param | ||||
6601 | Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); | ||||
6602 | ArgPtQuals.setAddressSpace(ParamAS); | ||||
6603 | auto NewArgPtTy = | ||||
6604 | Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); | ||||
6605 | auto NewArgTy = | ||||
6606 | Context.getQualifiedType(Context.getPointerType(NewArgPtTy), | ||||
6607 | ArgTy.getQualifiers()); | ||||
6608 | |||||
6609 | // Finally perform an implicit address space cast | ||||
6610 | ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, | ||||
6611 | CK_AddressSpaceConversion) | ||||
6612 | .get(); | ||||
6613 | } | ||||
6614 | } | ||||
6615 | } | ||||
6616 | |||||
6617 | if (Context.isDependenceAllowed() && | ||||
6618 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
6619 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6619, __extension__ __PRETTY_FUNCTION__)); | ||||
6620 | assert((Fn->containsErrors() ||(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6623, __extension__ __PRETTY_FUNCTION__)) | ||||
6621 | llvm::any_of(ArgExprs,(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6623, __extension__ __PRETTY_FUNCTION__)) | ||||
6622 | [](clang::Expr *E) { return E->containsErrors(); })) &&(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6623, __extension__ __PRETTY_FUNCTION__)) | ||||
6623 | "should only occur in error-recovery path.")(static_cast <bool> ((Fn->containsErrors() || llvm:: any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors (); })) && "should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang::Expr *E) { return E->containsErrors(); })) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6623, __extension__ __PRETTY_FUNCTION__)); | ||||
6624 | QualType ReturnType = | ||||
6625 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||
6626 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | ||||
6627 | : Context.DependentTy; | ||||
6628 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||
6629 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||
6630 | CurFPFeatureOverrides()); | ||||
6631 | } | ||||
6632 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||
6633 | ExecConfig, IsExecConfig); | ||||
6634 | } | ||||
6635 | |||||
6636 | /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id | ||||
6637 | // with the specified CallArgs | ||||
6638 | Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, | ||||
6639 | MultiExprArg CallArgs) { | ||||
6640 | StringRef Name = Context.BuiltinInfo.getName(Id); | ||||
6641 | LookupResult R(*this, &Context.Idents.get(Name), Loc, | ||||
6642 | Sema::LookupOrdinaryName); | ||||
6643 | LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); | ||||
6644 | |||||
6645 | auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); | ||||
6646 | assert(BuiltInDecl && "failed to find builtin declaration")(static_cast <bool> (BuiltInDecl && "failed to find builtin declaration" ) ? void (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6646, __extension__ __PRETTY_FUNCTION__)); | ||||
6647 | |||||
6648 | ExprResult DeclRef = | ||||
6649 | BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); | ||||
6650 | assert(DeclRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (DeclRef.isUsable() && "Builtin reference cannot fail" ) ? void (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6650, __extension__ __PRETTY_FUNCTION__)); | ||||
6651 | |||||
6652 | ExprResult Call = | ||||
6653 | BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); | ||||
6654 | |||||
6655 | assert(!Call.isInvalid() && "Call to builtin cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to builtin cannot fail!" ) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6655, __extension__ __PRETTY_FUNCTION__)); | ||||
6656 | return Call.get(); | ||||
6657 | } | ||||
6658 | |||||
6659 | /// Parse a __builtin_astype expression. | ||||
6660 | /// | ||||
6661 | /// __builtin_astype( value, dst type ) | ||||
6662 | /// | ||||
6663 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6664 | SourceLocation BuiltinLoc, | ||||
6665 | SourceLocation RParenLoc) { | ||||
6666 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||
6667 | return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); | ||||
6668 | } | ||||
6669 | |||||
6670 | /// Create a new AsTypeExpr node (bitcast) from the arguments. | ||||
6671 | ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, | ||||
6672 | SourceLocation BuiltinLoc, | ||||
6673 | SourceLocation RParenLoc) { | ||||
6674 | ExprValueKind VK = VK_PRValue; | ||||
6675 | ExprObjectKind OK = OK_Ordinary; | ||||
6676 | QualType SrcTy = E->getType(); | ||||
6677 | if (!SrcTy->isDependentType() && | ||||
6678 | Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) | ||||
6679 | return ExprError( | ||||
6680 | Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) | ||||
6681 | << DestTy << SrcTy << E->getSourceRange()); | ||||
6682 | return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); | ||||
6683 | } | ||||
6684 | |||||
6685 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||
6686 | /// provided arguments. | ||||
6687 | /// | ||||
6688 | /// __builtin_convertvector( value, dst type ) | ||||
6689 | /// | ||||
6690 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6691 | SourceLocation BuiltinLoc, | ||||
6692 | SourceLocation RParenLoc) { | ||||
6693 | TypeSourceInfo *TInfo; | ||||
6694 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||
6695 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||
6696 | } | ||||
6697 | |||||
6698 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||
6699 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||
6700 | /// unary-convert to an expression of function-pointer or | ||||
6701 | /// block-pointer type. | ||||
6702 | /// | ||||
6703 | /// \param NDecl the declaration being called, if available | ||||
6704 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||
6705 | SourceLocation LParenLoc, | ||||
6706 | ArrayRef<Expr *> Args, | ||||
6707 | SourceLocation RParenLoc, Expr *Config, | ||||
6708 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||
6709 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||
| |||||
6710 | unsigned BuiltinID = (FDecl
| ||||
6711 | |||||
6712 | // Functions with 'interrupt' attribute cannot be called directly. | ||||
6713 | if (FDecl
| ||||
6714 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||
6715 | return ExprError(); | ||||
6716 | } | ||||
6717 | |||||
6718 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||
6719 | // so there's some risk when calling out to non-interrupt handler functions | ||||
6720 | // that the callee might not preserve them. This is easy to diagnose here, | ||||
6721 | // but can be very challenging to debug. | ||||
6722 | // Likewise, X86 interrupt handlers may only call routines with attribute | ||||
6723 | // no_caller_saved_registers since there is no efficient way to | ||||
6724 | // save and restore the non-GPR state. | ||||
6725 | if (auto *Caller = getCurFunctionDecl()) { | ||||
6726 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||
6727 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||
6728 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { | ||||
6729 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||
6730 | if (FDecl) | ||||
6731 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6732 | } | ||||
6733 | } | ||||
6734 | if (Caller->hasAttr<AnyX86InterruptAttr>() && | ||||
6735 | ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { | ||||
6736 | Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); | ||||
6737 | if (FDecl) | ||||
6738 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
6739 | } | ||||
6740 | } | ||||
6741 | |||||
6742 | // Promote the function operand. | ||||
6743 | // We special-case function promotion here because we only allow promoting | ||||
6744 | // builtin functions to function pointers in the callee of a call. | ||||
6745 | ExprResult Result; | ||||
6746 | QualType ResultTy; | ||||
6747 | if (BuiltinID
| ||||
6748 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||
6749 | // Extract the return type from the (builtin) function pointer type. | ||||
6750 | // FIXME Several builtins still have setType in | ||||
6751 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||
6752 | // Builtins.def to ensure they are correct before removing setType calls. | ||||
6753 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||
6754 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||
6755 | ResultTy = FDecl->getCallResultType(); | ||||
6756 | } else { | ||||
6757 | Result = CallExprUnaryConversions(Fn); | ||||
6758 | ResultTy = Context.BoolTy; | ||||
6759 | } | ||||
6760 | if (Result.isInvalid()) | ||||
6761 | return ExprError(); | ||||
6762 | Fn = Result.get(); | ||||
6763 | |||||
6764 | // Check for a valid function type, but only if it is not a builtin which | ||||
6765 | // requires custom type checking. These will be handled by | ||||
6766 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||
6767 | const FunctionType *FuncT = nullptr; | ||||
6768 | if (!BuiltinID
| ||||
6769 | retry: | ||||
6770 | if (const PointerType *PT
| ||||
6771 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||
6772 | // have type pointer to function". | ||||
6773 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||
6774 | if (!FuncT) | ||||
6775 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6776 | << Fn->getType() << Fn->getSourceRange()); | ||||
6777 | } else if (const BlockPointerType *BPT = | ||||
6778 | Fn->getType()->getAs<BlockPointerType>()) { | ||||
6779 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||
6780 | } else { | ||||
6781 | // Handle calls to expressions of unknown-any type. | ||||
6782 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6783 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||
6784 | if (rewrite.isInvalid()) | ||||
6785 | return ExprError(); | ||||
6786 | Fn = rewrite.get(); | ||||
6787 | goto retry; | ||||
6788 | } | ||||
6789 | |||||
6790 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6791 | << Fn->getType() << Fn->getSourceRange()); | ||||
6792 | } | ||||
6793 | } | ||||
6794 | |||||
6795 | // Get the number of parameters in the function prototype, if any. | ||||
6796 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||
6797 | // in the call expression. | ||||
6798 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||
6799 | unsigned NumParams = Proto
| ||||
6800 | |||||
6801 | CallExpr *TheCall; | ||||
6802 | if (Config) { | ||||
6803 | assert(UsesADL == ADLCallKind::NotADL &&(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6804, __extension__ __PRETTY_FUNCTION__)) | ||||
6804 | "CUDAKernelCallExpr should not use ADL")(static_cast <bool> (UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL") ? void (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6804, __extension__ __PRETTY_FUNCTION__)); | ||||
6805 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||
6806 | Args, ResultTy, VK_PRValue, RParenLoc, | ||||
6807 | CurFPFeatureOverrides(), NumParams); | ||||
6808 | } else { | ||||
6809 | TheCall = | ||||
6810 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
6811 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6812 | } | ||||
6813 | |||||
6814 | if (!Context.isDependenceAllowed()) { | ||||
6815 | // Forget about the nulled arguments since typo correction | ||||
6816 | // do not handle them well. | ||||
6817 | TheCall->shrinkNumArgs(Args.size()); | ||||
6818 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||
6819 | // function calls as their argument checking don't necessarily handle | ||||
6820 | // dependent types properly, so make sure any TypoExprs have been | ||||
6821 | // dealt with. | ||||
6822 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||
6823 | if (!Result.isUsable()) return ExprError(); | ||||
6824 | CallExpr *TheOldCall = TheCall; | ||||
6825 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||
6826 | bool CorrectedTypos = TheCall != TheOldCall; | ||||
6827 | if (!TheCall) return Result; | ||||
6828 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||
6829 | |||||
6830 | // A new call expression node was created if some typos were corrected. | ||||
6831 | // However it may not have been constructed with enough storage. In this | ||||
6832 | // case, rebuild the node with enough storage. The waste of space is | ||||
6833 | // immaterial since this only happens when some typos were corrected. | ||||
6834 | if (CorrectedTypos && Args.size() < NumParams) { | ||||
6835 | if (Config) | ||||
6836 | TheCall = CUDAKernelCallExpr::Create( | ||||
6837 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, | ||||
6838 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||
6839 | else | ||||
6840 | TheCall = | ||||
6841 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, | ||||
6842 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6843 | } | ||||
6844 | // We can now handle the nulled arguments for the default arguments. | ||||
6845 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||
6846 | } | ||||
6847 | |||||
6848 | // Bail out early if calling a builtin with custom type checking. | ||||
6849 | if (BuiltinID
| ||||
6850 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6851 | |||||
6852 | if (getLangOpts().CUDA) { | ||||
6853 | if (Config
| ||||
6854 | // CUDA: Kernel calls must be to global functions | ||||
6855 | if (FDecl
| ||||
6856 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||
6857 | << FDecl << Fn->getSourceRange()); | ||||
6858 | |||||
6859 | // CUDA: Kernel function must have 'void' return type | ||||
6860 | if (!FuncT->getReturnType()->isVoidType() && | ||||
| |||||
6861 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||
6862 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||
6863 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||
6864 | << Fn->getType() << Fn->getSourceRange()); | ||||
6865 | } else { | ||||
6866 | // CUDA: Calls to global functions must be configured | ||||
6867 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
6868 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||
6869 | << FDecl << Fn->getSourceRange()); | ||||
6870 | } | ||||
6871 | } | ||||
6872 | |||||
6873 | // Check for a valid return type | ||||
6874 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||
6875 | FDecl)) | ||||
6876 | return ExprError(); | ||||
6877 | |||||
6878 | // We know the result type of the call, set it. | ||||
6879 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||
6880 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||
6881 | |||||
6882 | if (Proto) { | ||||
6883 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||
6884 | IsExecConfig)) | ||||
6885 | return ExprError(); | ||||
6886 | } else { | ||||
6887 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")(static_cast <bool> (isa<FunctionNoProtoType>(FuncT ) && "Unknown FunctionType!") ? void (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6887, __extension__ __PRETTY_FUNCTION__)); | ||||
6888 | |||||
6889 | if (FDecl) { | ||||
6890 | // Check if we have too few/too many template arguments, based | ||||
6891 | // on our knowledge of the function definition. | ||||
6892 | const FunctionDecl *Def = nullptr; | ||||
6893 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||
6894 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||
6895 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||
6896 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||
6897 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||
6898 | } | ||||
6899 | |||||
6900 | // If the function we're calling isn't a function prototype, but we have | ||||
6901 | // a function prototype from a prior declaratiom, use that prototype. | ||||
6902 | if (!FDecl->hasPrototype()) | ||||
6903 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||
6904 | } | ||||
6905 | |||||
6906 | // Promote the arguments (C99 6.5.2.2p6). | ||||
6907 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6908 | Expr *Arg = Args[i]; | ||||
6909 | |||||
6910 | if (Proto && i < Proto->getNumParams()) { | ||||
6911 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
6912 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||
6913 | ExprResult ArgE = | ||||
6914 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||
6915 | if (ArgE.isInvalid()) | ||||
6916 | return true; | ||||
6917 | |||||
6918 | Arg = ArgE.getAs<Expr>(); | ||||
6919 | |||||
6920 | } else { | ||||
6921 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||
6922 | |||||
6923 | if (ArgE.isInvalid()) | ||||
6924 | return true; | ||||
6925 | |||||
6926 | Arg = ArgE.getAs<Expr>(); | ||||
6927 | } | ||||
6928 | |||||
6929 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||
6930 | diag::err_call_incomplete_argument, Arg)) | ||||
6931 | return ExprError(); | ||||
6932 | |||||
6933 | TheCall->setArg(i, Arg); | ||||
6934 | } | ||||
6935 | TheCall->computeDependence(); | ||||
6936 | } | ||||
6937 | |||||
6938 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
6939 | if (!Method->isStatic()) | ||||
6940 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||
6941 | << Fn->getSourceRange()); | ||||
6942 | |||||
6943 | // Check for sentinels | ||||
6944 | if (NDecl) | ||||
6945 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||
6946 | |||||
6947 | // Warn for unions passing across security boundary (CMSE). | ||||
6948 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||
6949 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6950 | if (const auto *RT = | ||||
6951 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||
6952 | if (RT->getDecl()->isOrContainsUnion()) | ||||
6953 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||
6954 | << 0 << i; | ||||
6955 | } | ||||
6956 | } | ||||
6957 | } | ||||
6958 | |||||
6959 | // Do special checking on direct calls to functions. | ||||
6960 | if (FDecl) { | ||||
6961 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||
6962 | return ExprError(); | ||||
6963 | |||||
6964 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||
6965 | |||||
6966 | if (BuiltinID) | ||||
6967 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6968 | } else if (NDecl) { | ||||
6969 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||
6970 | return ExprError(); | ||||
6971 | } else { | ||||
6972 | if (CheckOtherCall(TheCall, Proto)) | ||||
6973 | return ExprError(); | ||||
6974 | } | ||||
6975 | |||||
6976 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||
6977 | } | ||||
6978 | |||||
6979 | ExprResult | ||||
6980 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||
6981 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||
6982 | assert(Ty && "ActOnCompoundLiteral(): missing type")(static_cast <bool> (Ty && "ActOnCompoundLiteral(): missing type" ) ? void (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6982, __extension__ __PRETTY_FUNCTION__)); | ||||
6983 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")(static_cast <bool> (InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? void (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 6983, __extension__ __PRETTY_FUNCTION__)); | ||||
6984 | |||||
6985 | TypeSourceInfo *TInfo; | ||||
6986 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||
6987 | if (!TInfo) | ||||
6988 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||
6989 | |||||
6990 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||
6991 | } | ||||
6992 | |||||
6993 | ExprResult | ||||
6994 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||
6995 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||
6996 | QualType literalType = TInfo->getType(); | ||||
6997 | |||||
6998 | if (literalType->isArrayType()) { | ||||
6999 | if (RequireCompleteSizedType( | ||||
7000 | LParenLoc, Context.getBaseElementType(literalType), | ||||
7001 | diag::err_array_incomplete_or_sizeless_type, | ||||
7002 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7003 | return ExprError(); | ||||
7004 | if (literalType->isVariableArrayType()) { | ||||
7005 | if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, | ||||
7006 | diag::err_variable_object_no_init)) { | ||||
7007 | return ExprError(); | ||||
7008 | } | ||||
7009 | } | ||||
7010 | } else if (!literalType->isDependentType() && | ||||
7011 | RequireCompleteType(LParenLoc, literalType, | ||||
7012 | diag::err_typecheck_decl_incomplete_type, | ||||
7013 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
7014 | return ExprError(); | ||||
7015 | |||||
7016 | InitializedEntity Entity | ||||
7017 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||
7018 | InitializationKind Kind | ||||
7019 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||
7020 | SourceRange(LParenLoc, RParenLoc), | ||||
7021 | /*InitList=*/true); | ||||
7022 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||
7023 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||
7024 | &literalType); | ||||
7025 | if (Result.isInvalid()) | ||||
7026 | return ExprError(); | ||||
7027 | LiteralExpr = Result.get(); | ||||
7028 | |||||
7029 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||
7030 | |||||
7031 | // In C, compound literals are l-values for some reason. | ||||
7032 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||
7033 | // constant initializers are also l-values, and compound literals are | ||||
7034 | // otherwise prvalues. | ||||
7035 | // | ||||
7036 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||
7037 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||
7038 | // follow it there.) | ||||
7039 | // | ||||
7040 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||
7041 | // lifetime-extending a temporary object, but our materialized temporaries | ||||
7042 | // representation only supports lifetime extension from a variable, not "out | ||||
7043 | // of thin air". | ||||
7044 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||
7045 | // is bound to the result of applying array-to-pointer decay to the compound | ||||
7046 | // literal. | ||||
7047 | // FIXME: GCC supports compound literals of reference type, which should | ||||
7048 | // obviously have a value kind derived from the kind of reference involved. | ||||
7049 | ExprValueKind VK = | ||||
7050 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||
7051 | ? VK_PRValue | ||||
7052 | : VK_LValue; | ||||
7053 | |||||
7054 | if (isFileScope) | ||||
7055 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||
7056 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||
7057 | Expr *Init = ILE->getInit(i); | ||||
7058 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||
7059 | } | ||||
7060 | |||||
7061 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||
7062 | VK, LiteralExpr, isFileScope); | ||||
7063 | if (isFileScope) { | ||||
7064 | if (!LiteralExpr->isTypeDependent() && | ||||
7065 | !LiteralExpr->isValueDependent() && | ||||
7066 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||
7067 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||
7068 | return ExprError(); | ||||
7069 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||
7070 | literalType.getAddressSpace() != LangAS::Default) { | ||||
7071 | // Embedded-C extensions to C99 6.5.2.5: | ||||
7072 | // "If the compound literal occurs inside the body of a function, the | ||||
7073 | // type name shall not be qualified by an address-space qualifier." | ||||
7074 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||
7075 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||
7076 | return ExprError(); | ||||
7077 | } | ||||
7078 | |||||
7079 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||
7080 | // Compound literals that have automatic storage duration are destroyed at | ||||
7081 | // the end of the scope in C; in C++, they're just temporaries. | ||||
7082 | |||||
7083 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||
7084 | // to destruct. | ||||
7085 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||
7086 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
7087 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||
7088 | |||||
7089 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||
7090 | if (literalType.isDestructedType()) { | ||||
7091 | Cleanup.setExprNeedsCleanups(true); | ||||
7092 | ExprCleanupObjects.push_back(E); | ||||
7093 | getCurFunction()->setHasBranchProtectedScope(); | ||||
7094 | } | ||||
7095 | } | ||||
7096 | |||||
7097 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
7098 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
7099 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||
7100 | E->getInitializer()->getExprLoc()); | ||||
7101 | |||||
7102 | return MaybeBindToTemporary(E); | ||||
7103 | } | ||||
7104 | |||||
7105 | ExprResult | ||||
7106 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7107 | SourceLocation RBraceLoc) { | ||||
7108 | // Only produce each kind of designated initialization diagnostic once. | ||||
7109 | SourceLocation FirstDesignator; | ||||
7110 | bool DiagnosedArrayDesignator = false; | ||||
7111 | bool DiagnosedNestedDesignator = false; | ||||
7112 | bool DiagnosedMixedDesignator = false; | ||||
7113 | |||||
7114 | // Check that any designated initializers are syntactically valid in the | ||||
7115 | // current language mode. | ||||
7116 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7117 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||
7118 | if (FirstDesignator.isInvalid()) | ||||
7119 | FirstDesignator = DIE->getBeginLoc(); | ||||
7120 | |||||
7121 | if (!getLangOpts().CPlusPlus) | ||||
7122 | break; | ||||
7123 | |||||
7124 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||
7125 | DiagnosedNestedDesignator = true; | ||||
7126 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||
7127 | << DIE->getDesignatorsSourceRange(); | ||||
7128 | } | ||||
7129 | |||||
7130 | for (auto &Desig : DIE->designators()) { | ||||
7131 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||
7132 | DiagnosedArrayDesignator = true; | ||||
7133 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||
7134 | << Desig.getSourceRange(); | ||||
7135 | } | ||||
7136 | } | ||||
7137 | |||||
7138 | if (!DiagnosedMixedDesignator && | ||||
7139 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7140 | DiagnosedMixedDesignator = true; | ||||
7141 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7142 | << DIE->getSourceRange(); | ||||
7143 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7144 | << InitArgList[0]->getSourceRange(); | ||||
7145 | } | ||||
7146 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||
7147 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
7148 | DiagnosedMixedDesignator = true; | ||||
7149 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||
7150 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
7151 | << DIE->getSourceRange(); | ||||
7152 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
7153 | << InitArgList[I]->getSourceRange(); | ||||
7154 | } | ||||
7155 | } | ||||
7156 | |||||
7157 | if (FirstDesignator.isValid()) { | ||||
7158 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||
7159 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||
7160 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||
7161 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||
7162 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||
7163 | ? diag::warn_cxx17_compat_designated_init | ||||
7164 | : diag::ext_cxx_designated_init); | ||||
7165 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||
7166 | Diag(FirstDesignator, diag::ext_designated_init); | ||||
7167 | } | ||||
7168 | } | ||||
7169 | |||||
7170 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||
7171 | } | ||||
7172 | |||||
7173 | ExprResult | ||||
7174 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
7175 | SourceLocation RBraceLoc) { | ||||
7176 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||
7177 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||
7178 | |||||
7179 | // Immediately handle non-overload placeholders. Overloads can be | ||||
7180 | // resolved contextually, but everything else here can't. | ||||
7181 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
7182 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
7183 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||
7184 | |||||
7185 | // Ignore failures; dropping the entire initializer list because | ||||
7186 | // of one failure would be terrible for indexing/etc. | ||||
7187 | if (result.isInvalid()) continue; | ||||
7188 | |||||
7189 | InitArgList[I] = result.get(); | ||||
7190 | } | ||||
7191 | } | ||||
7192 | |||||
7193 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||
7194 | RBraceLoc); | ||||
7195 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||
7196 | return E; | ||||
7197 | } | ||||
7198 | |||||
7199 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||
7200 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||
7201 | assert(E.get()->getType()->isBlockPointerType())(static_cast <bool> (E.get()->getType()->isBlockPointerType ()) ? void (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7201, __extension__ __PRETTY_FUNCTION__)); | ||||
7202 | assert(E.get()->isPRValue())(static_cast <bool> (E.get()->isPRValue()) ? void (0 ) : __assert_fail ("E.get()->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7202, __extension__ __PRETTY_FUNCTION__)); | ||||
7203 | |||||
7204 | // Only do this in an r-value context. | ||||
7205 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||
7206 | |||||
7207 | E = ImplicitCastExpr::Create( | ||||
7208 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||
7209 | /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); | ||||
7210 | Cleanup.setExprNeedsCleanups(true); | ||||
7211 | } | ||||
7212 | |||||
7213 | /// Prepare a conversion of the given expression to an ObjC object | ||||
7214 | /// pointer type. | ||||
7215 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||
7216 | QualType type = E.get()->getType(); | ||||
7217 | if (type->isObjCObjectPointerType()) { | ||||
7218 | return CK_BitCast; | ||||
7219 | } else if (type->isBlockPointerType()) { | ||||
7220 | maybeExtendBlockObject(E); | ||||
7221 | return CK_BlockPointerToObjCPointerCast; | ||||
7222 | } else { | ||||
7223 | assert(type->isPointerType())(static_cast <bool> (type->isPointerType()) ? void ( 0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7223, __extension__ __PRETTY_FUNCTION__)); | ||||
7224 | return CK_CPointerToObjCPointerCast; | ||||
7225 | } | ||||
7226 | } | ||||
7227 | |||||
7228 | /// Prepares for a scalar cast, performing all the necessary stages | ||||
7229 | /// except the final cast and returning the kind required. | ||||
7230 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||
7231 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||
7232 | // Also, callers should have filtered out the invalid cases with | ||||
7233 | // pointers. Everything else should be possible. | ||||
7234 | |||||
7235 | QualType SrcTy = Src.get()->getType(); | ||||
7236 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||
7237 | return CK_NoOp; | ||||
7238 | |||||
7239 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||
7240 | case Type::STK_MemberPointer: | ||||
7241 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7241); | ||||
7242 | |||||
7243 | case Type::STK_CPointer: | ||||
7244 | case Type::STK_BlockPointer: | ||||
7245 | case Type::STK_ObjCObjectPointer: | ||||
7246 | switch (DestTy->getScalarTypeKind()) { | ||||
7247 | case Type::STK_CPointer: { | ||||
7248 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||
7249 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||
7250 | if (SrcAS != DestAS) | ||||
7251 | return CK_AddressSpaceConversion; | ||||
7252 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||
7253 | return CK_NoOp; | ||||
7254 | return CK_BitCast; | ||||
7255 | } | ||||
7256 | case Type::STK_BlockPointer: | ||||
7257 | return (SrcKind == Type::STK_BlockPointer | ||||
7258 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||
7259 | case Type::STK_ObjCObjectPointer: | ||||
7260 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||
7261 | return CK_BitCast; | ||||
7262 | if (SrcKind == Type::STK_CPointer) | ||||
7263 | return CK_CPointerToObjCPointerCast; | ||||
7264 | maybeExtendBlockObject(Src); | ||||
7265 | return CK_BlockPointerToObjCPointerCast; | ||||
7266 | case Type::STK_Bool: | ||||
7267 | return CK_PointerToBoolean; | ||||
7268 | case Type::STK_Integral: | ||||
7269 | return CK_PointerToIntegral; | ||||
7270 | case Type::STK_Floating: | ||||
7271 | case Type::STK_FloatingComplex: | ||||
7272 | case Type::STK_IntegralComplex: | ||||
7273 | case Type::STK_MemberPointer: | ||||
7274 | case Type::STK_FixedPoint: | ||||
7275 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7275); | ||||
7276 | } | ||||
7277 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7277); | ||||
7278 | |||||
7279 | case Type::STK_FixedPoint: | ||||
7280 | switch (DestTy->getScalarTypeKind()) { | ||||
7281 | case Type::STK_FixedPoint: | ||||
7282 | return CK_FixedPointCast; | ||||
7283 | case Type::STK_Bool: | ||||
7284 | return CK_FixedPointToBoolean; | ||||
7285 | case Type::STK_Integral: | ||||
7286 | return CK_FixedPointToIntegral; | ||||
7287 | case Type::STK_Floating: | ||||
7288 | return CK_FixedPointToFloating; | ||||
7289 | case Type::STK_IntegralComplex: | ||||
7290 | case Type::STK_FloatingComplex: | ||||
7291 | Diag(Src.get()->getExprLoc(), | ||||
7292 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7293 | << DestTy; | ||||
7294 | return CK_IntegralCast; | ||||
7295 | case Type::STK_CPointer: | ||||
7296 | case Type::STK_ObjCObjectPointer: | ||||
7297 | case Type::STK_BlockPointer: | ||||
7298 | case Type::STK_MemberPointer: | ||||
7299 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7299); | ||||
7300 | } | ||||
7301 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7301); | ||||
7302 | |||||
7303 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||
7304 | case Type::STK_Integral: | ||||
7305 | switch (DestTy->getScalarTypeKind()) { | ||||
7306 | case Type::STK_CPointer: | ||||
7307 | case Type::STK_ObjCObjectPointer: | ||||
7308 | case Type::STK_BlockPointer: | ||||
7309 | if (Src.get()->isNullPointerConstant(Context, | ||||
7310 | Expr::NPC_ValueDependentIsNull)) | ||||
7311 | return CK_NullToPointer; | ||||
7312 | return CK_IntegralToPointer; | ||||
7313 | case Type::STK_Bool: | ||||
7314 | return CK_IntegralToBoolean; | ||||
7315 | case Type::STK_Integral: | ||||
7316 | return CK_IntegralCast; | ||||
7317 | case Type::STK_Floating: | ||||
7318 | return CK_IntegralToFloating; | ||||
7319 | case Type::STK_IntegralComplex: | ||||
7320 | Src = ImpCastExprToType(Src.get(), | ||||
7321 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7322 | CK_IntegralCast); | ||||
7323 | return CK_IntegralRealToComplex; | ||||
7324 | case Type::STK_FloatingComplex: | ||||
7325 | Src = ImpCastExprToType(Src.get(), | ||||
7326 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7327 | CK_IntegralToFloating); | ||||
7328 | return CK_FloatingRealToComplex; | ||||
7329 | case Type::STK_MemberPointer: | ||||
7330 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7330); | ||||
7331 | case Type::STK_FixedPoint: | ||||
7332 | return CK_IntegralToFixedPoint; | ||||
7333 | } | ||||
7334 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7334); | ||||
7335 | |||||
7336 | case Type::STK_Floating: | ||||
7337 | switch (DestTy->getScalarTypeKind()) { | ||||
7338 | case Type::STK_Floating: | ||||
7339 | return CK_FloatingCast; | ||||
7340 | case Type::STK_Bool: | ||||
7341 | return CK_FloatingToBoolean; | ||||
7342 | case Type::STK_Integral: | ||||
7343 | return CK_FloatingToIntegral; | ||||
7344 | case Type::STK_FloatingComplex: | ||||
7345 | Src = ImpCastExprToType(Src.get(), | ||||
7346 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7347 | CK_FloatingCast); | ||||
7348 | return CK_FloatingRealToComplex; | ||||
7349 | case Type::STK_IntegralComplex: | ||||
7350 | Src = ImpCastExprToType(Src.get(), | ||||
7351 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7352 | CK_FloatingToIntegral); | ||||
7353 | return CK_IntegralRealToComplex; | ||||
7354 | case Type::STK_CPointer: | ||||
7355 | case Type::STK_ObjCObjectPointer: | ||||
7356 | case Type::STK_BlockPointer: | ||||
7357 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7357); | ||||
7358 | case Type::STK_MemberPointer: | ||||
7359 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7359); | ||||
7360 | case Type::STK_FixedPoint: | ||||
7361 | return CK_FloatingToFixedPoint; | ||||
7362 | } | ||||
7363 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7363); | ||||
7364 | |||||
7365 | case Type::STK_FloatingComplex: | ||||
7366 | switch (DestTy->getScalarTypeKind()) { | ||||
7367 | case Type::STK_FloatingComplex: | ||||
7368 | return CK_FloatingComplexCast; | ||||
7369 | case Type::STK_IntegralComplex: | ||||
7370 | return CK_FloatingComplexToIntegralComplex; | ||||
7371 | case Type::STK_Floating: { | ||||
7372 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7373 | if (Context.hasSameType(ET, DestTy)) | ||||
7374 | return CK_FloatingComplexToReal; | ||||
7375 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||
7376 | return CK_FloatingCast; | ||||
7377 | } | ||||
7378 | case Type::STK_Bool: | ||||
7379 | return CK_FloatingComplexToBoolean; | ||||
7380 | case Type::STK_Integral: | ||||
7381 | Src = ImpCastExprToType(Src.get(), | ||||
7382 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7383 | CK_FloatingComplexToReal); | ||||
7384 | return CK_FloatingToIntegral; | ||||
7385 | case Type::STK_CPointer: | ||||
7386 | case Type::STK_ObjCObjectPointer: | ||||
7387 | case Type::STK_BlockPointer: | ||||
7388 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7388); | ||||
7389 | case Type::STK_MemberPointer: | ||||
7390 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7390); | ||||
7391 | case Type::STK_FixedPoint: | ||||
7392 | Diag(Src.get()->getExprLoc(), | ||||
7393 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7394 | << SrcTy; | ||||
7395 | return CK_IntegralCast; | ||||
7396 | } | ||||
7397 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7397); | ||||
7398 | |||||
7399 | case Type::STK_IntegralComplex: | ||||
7400 | switch (DestTy->getScalarTypeKind()) { | ||||
7401 | case Type::STK_FloatingComplex: | ||||
7402 | return CK_IntegralComplexToFloatingComplex; | ||||
7403 | case Type::STK_IntegralComplex: | ||||
7404 | return CK_IntegralComplexCast; | ||||
7405 | case Type::STK_Integral: { | ||||
7406 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7407 | if (Context.hasSameType(ET, DestTy)) | ||||
7408 | return CK_IntegralComplexToReal; | ||||
7409 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||
7410 | return CK_IntegralCast; | ||||
7411 | } | ||||
7412 | case Type::STK_Bool: | ||||
7413 | return CK_IntegralComplexToBoolean; | ||||
7414 | case Type::STK_Floating: | ||||
7415 | Src = ImpCastExprToType(Src.get(), | ||||
7416 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7417 | CK_IntegralComplexToReal); | ||||
7418 | return CK_IntegralToFloating; | ||||
7419 | case Type::STK_CPointer: | ||||
7420 | case Type::STK_ObjCObjectPointer: | ||||
7421 | case Type::STK_BlockPointer: | ||||
7422 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7422); | ||||
7423 | case Type::STK_MemberPointer: | ||||
7424 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7424); | ||||
7425 | case Type::STK_FixedPoint: | ||||
7426 | Diag(Src.get()->getExprLoc(), | ||||
7427 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7428 | << SrcTy; | ||||
7429 | return CK_IntegralCast; | ||||
7430 | } | ||||
7431 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7431); | ||||
7432 | } | ||||
7433 | |||||
7434 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7434); | ||||
7435 | } | ||||
7436 | |||||
7437 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||
7438 | QualType &eltType) { | ||||
7439 | // Vectors are simple. | ||||
7440 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||
7441 | len = vecType->getNumElements(); | ||||
7442 | eltType = vecType->getElementType(); | ||||
7443 | assert(eltType->isScalarType())(static_cast <bool> (eltType->isScalarType()) ? void (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7443, __extension__ __PRETTY_FUNCTION__)); | ||||
7444 | return true; | ||||
7445 | } | ||||
7446 | |||||
7447 | // We allow lax conversion to and from non-vector types, but only if | ||||
7448 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||
7449 | if (!type->isRealType()) return false; | ||||
7450 | |||||
7451 | len = 1; | ||||
7452 | eltType = type; | ||||
7453 | return true; | ||||
7454 | } | ||||
7455 | |||||
7456 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | ||||
7457 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | ||||
7458 | /// allowed? | ||||
7459 | /// | ||||
7460 | /// This will also return false if the two given types do not make sense from | ||||
7461 | /// the perspective of SVE bitcasts. | ||||
7462 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | ||||
7463 | assert(srcTy->isVectorType() || destTy->isVectorType())(static_cast <bool> (srcTy->isVectorType() || destTy ->isVectorType()) ? void (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7463, __extension__ __PRETTY_FUNCTION__)); | ||||
7464 | |||||
7465 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | ||||
7466 | if (!FirstType->isSizelessBuiltinType()) | ||||
7467 | return false; | ||||
7468 | |||||
7469 | const auto *VecTy = SecondType->getAs<VectorType>(); | ||||
7470 | return VecTy && | ||||
7471 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | ||||
7472 | }; | ||||
7473 | |||||
7474 | return ValidScalableConversion(srcTy, destTy) || | ||||
7475 | ValidScalableConversion(destTy, srcTy); | ||||
7476 | } | ||||
7477 | |||||
7478 | /// Are the two types matrix types and do they have the same dimensions i.e. | ||||
7479 | /// do they have the same number of rows and the same number of columns? | ||||
7480 | bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { | ||||
7481 | if (!destTy->isMatrixType() || !srcTy->isMatrixType()) | ||||
7482 | return false; | ||||
7483 | |||||
7484 | const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); | ||||
7485 | const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); | ||||
7486 | |||||
7487 | return matSrcType->getNumRows() == matDestType->getNumRows() && | ||||
7488 | matSrcType->getNumColumns() == matDestType->getNumColumns(); | ||||
7489 | } | ||||
7490 | |||||
7491 | bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { | ||||
7492 | assert(DestTy->isVectorType() || SrcTy->isVectorType())(static_cast <bool> (DestTy->isVectorType() || SrcTy ->isVectorType()) ? void (0) : __assert_fail ("DestTy->isVectorType() || SrcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7492, __extension__ __PRETTY_FUNCTION__)); | ||||
7493 | |||||
7494 | uint64_t SrcLen, DestLen; | ||||
7495 | QualType SrcEltTy, DestEltTy; | ||||
7496 | if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) | ||||
7497 | return false; | ||||
7498 | if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) | ||||
7499 | return false; | ||||
7500 | |||||
7501 | // ASTContext::getTypeSize will return the size rounded up to a | ||||
7502 | // power of 2, so instead of using that, we need to use the raw | ||||
7503 | // element size multiplied by the element count. | ||||
7504 | uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); | ||||
7505 | uint64_t DestEltSize = Context.getTypeSize(DestEltTy); | ||||
7506 | |||||
7507 | return (SrcLen * SrcEltSize == DestLen * DestEltSize); | ||||
7508 | } | ||||
7509 | |||||
7510 | /// Are the two types lax-compatible vector types? That is, given | ||||
7511 | /// that one of them is a vector, do they have equal storage sizes, | ||||
7512 | /// where the storage size is the number of elements times the element | ||||
7513 | /// size? | ||||
7514 | /// | ||||
7515 | /// This will also return false if either of the types is neither a | ||||
7516 | /// vector nor a real type. | ||||
7517 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||
7518 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7518, __extension__ __PRETTY_FUNCTION__)); | ||||
7519 | |||||
7520 | // Disallow lax conversions between scalars and ExtVectors (these | ||||
7521 | // conversions are allowed for other vector types because common headers | ||||
7522 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||
7523 | // splat path anyway, which does what we want (convert, not bitcast). | ||||
7524 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||
7525 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||
7526 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||
7527 | |||||
7528 | return areVectorTypesSameSize(srcTy, destTy); | ||||
7529 | } | ||||
7530 | |||||
7531 | /// Is this a legal conversion between two types, one of which is | ||||
7532 | /// known to be a vector type? | ||||
7533 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||
7534 | assert(destTy->isVectorType() || srcTy->isVectorType())(static_cast <bool> (destTy->isVectorType() || srcTy ->isVectorType()) ? void (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7534, __extension__ __PRETTY_FUNCTION__)); | ||||
7535 | |||||
7536 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||
7537 | case LangOptions::LaxVectorConversionKind::None: | ||||
7538 | return false; | ||||
7539 | |||||
7540 | case LangOptions::LaxVectorConversionKind::Integer: | ||||
7541 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||
7542 | auto *Vec = srcTy->getAs<VectorType>(); | ||||
7543 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7544 | return false; | ||||
7545 | } | ||||
7546 | if (!destTy->isIntegralOrEnumerationType()) { | ||||
7547 | auto *Vec = destTy->getAs<VectorType>(); | ||||
7548 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7549 | return false; | ||||
7550 | } | ||||
7551 | // OK, integer (vector) -> integer (vector) bitcast. | ||||
7552 | break; | ||||
7553 | |||||
7554 | case LangOptions::LaxVectorConversionKind::All: | ||||
7555 | break; | ||||
7556 | } | ||||
7557 | |||||
7558 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||
7559 | } | ||||
7560 | |||||
7561 | bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, | ||||
7562 | CastKind &Kind) { | ||||
7563 | if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { | ||||
7564 | if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { | ||||
7565 | return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) | ||||
7566 | << DestTy << SrcTy << R; | ||||
7567 | } | ||||
7568 | } else if (SrcTy->isMatrixType()) { | ||||
7569 | return Diag(R.getBegin(), | ||||
7570 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
7571 | << SrcTy << DestTy << R; | ||||
7572 | } else if (DestTy->isMatrixType()) { | ||||
7573 | return Diag(R.getBegin(), | ||||
7574 | diag::err_invalid_conversion_between_matrix_and_type) | ||||
7575 | << DestTy << SrcTy << R; | ||||
7576 | } | ||||
7577 | |||||
7578 | Kind = CK_MatrixCast; | ||||
7579 | return false; | ||||
7580 | } | ||||
7581 | |||||
7582 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||
7583 | CastKind &Kind) { | ||||
7584 | assert(VectorTy->isVectorType() && "Not a vector type!")(static_cast <bool> (VectorTy->isVectorType() && "Not a vector type!") ? void (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7584, __extension__ __PRETTY_FUNCTION__)); | ||||
7585 | |||||
7586 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||
7587 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||
7588 | return Diag(R.getBegin(), | ||||
7589 | Ty->isVectorType() ? | ||||
7590 | diag::err_invalid_conversion_between_vectors : | ||||
7591 | diag::err_invalid_conversion_between_vector_and_integer) | ||||
7592 | << VectorTy << Ty << R; | ||||
7593 | } else | ||||
7594 | return Diag(R.getBegin(), | ||||
7595 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7596 | << VectorTy << Ty << R; | ||||
7597 | |||||
7598 | Kind = CK_BitCast; | ||||
7599 | return false; | ||||
7600 | } | ||||
7601 | |||||
7602 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||
7603 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||
7604 | |||||
7605 | if (DestElemTy == SplattedExpr->getType()) | ||||
7606 | return SplattedExpr; | ||||
7607 | |||||
7608 | assert(DestElemTy->isFloatingType() ||(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7609, __extension__ __PRETTY_FUNCTION__)) | ||||
7609 | DestElemTy->isIntegralOrEnumerationType())(static_cast <bool> (DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7609, __extension__ __PRETTY_FUNCTION__)); | ||||
7610 | |||||
7611 | CastKind CK; | ||||
7612 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||
7613 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||
7614 | // only when splatting vectors. | ||||
7615 | if (DestElemTy->isFloatingType()) { | ||||
7616 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||
7617 | // in two steps: boolean to signed integral, then to floating. | ||||
7618 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||
7619 | CK_BooleanToSignedIntegral); | ||||
7620 | SplattedExpr = CastExprRes.get(); | ||||
7621 | CK = CK_IntegralToFloating; | ||||
7622 | } else { | ||||
7623 | CK = CK_BooleanToSignedIntegral; | ||||
7624 | } | ||||
7625 | } else { | ||||
7626 | ExprResult CastExprRes = SplattedExpr; | ||||
7627 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||
7628 | if (CastExprRes.isInvalid()) | ||||
7629 | return ExprError(); | ||||
7630 | SplattedExpr = CastExprRes.get(); | ||||
7631 | } | ||||
7632 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||
7633 | } | ||||
7634 | |||||
7635 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||
7636 | Expr *CastExpr, CastKind &Kind) { | ||||
7637 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")(static_cast <bool> (DestTy->isExtVectorType() && "Not an extended vector type!") ? void (0) : __assert_fail ( "DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7637, __extension__ __PRETTY_FUNCTION__)); | ||||
7638 | |||||
7639 | QualType SrcTy = CastExpr->getType(); | ||||
7640 | |||||
7641 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||
7642 | // an ExtVectorType. | ||||
7643 | // In OpenCL, casts between vectors of different types are not allowed. | ||||
7644 | // (See OpenCL 6.2). | ||||
7645 | if (SrcTy->isVectorType()) { | ||||
7646 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||
7647 | (getLangOpts().OpenCL && | ||||
7648 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||
7649 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||
7650 | << DestTy << SrcTy << R; | ||||
7651 | return ExprError(); | ||||
7652 | } | ||||
7653 | Kind = CK_BitCast; | ||||
7654 | return CastExpr; | ||||
7655 | } | ||||
7656 | |||||
7657 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||
7658 | // conversion will take place first from scalar to elt type, and then | ||||
7659 | // splat from elt type to vector. | ||||
7660 | if (SrcTy->isPointerType()) | ||||
7661 | return Diag(R.getBegin(), | ||||
7662 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7663 | << DestTy << SrcTy << R; | ||||
7664 | |||||
7665 | Kind = CK_VectorSplat; | ||||
7666 | return prepareVectorSplat(DestTy, CastExpr); | ||||
7667 | } | ||||
7668 | |||||
7669 | ExprResult | ||||
7670 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||
7671 | Declarator &D, ParsedType &Ty, | ||||
7672 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||
7673 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7674, __extension__ __PRETTY_FUNCTION__)) | ||||
7674 | "ActOnCastExpr(): missing type or expr")(static_cast <bool> (!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr" ) ? void (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7674, __extension__ __PRETTY_FUNCTION__)); | ||||
7675 | |||||
7676 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||
7677 | if (D.isInvalidType()) | ||||
7678 | return ExprError(); | ||||
7679 | |||||
7680 | if (getLangOpts().CPlusPlus) { | ||||
7681 | // Check that there are no default arguments (C++ only). | ||||
7682 | CheckExtraCXXDefaultArguments(D); | ||||
7683 | } else { | ||||
7684 | // Make sure any TypoExprs have been dealt with. | ||||
7685 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||
7686 | if (!Res.isUsable()) | ||||
7687 | return ExprError(); | ||||
7688 | CastExpr = Res.get(); | ||||
7689 | } | ||||
7690 | |||||
7691 | checkUnusedDeclAttributes(D); | ||||
7692 | |||||
7693 | QualType castType = castTInfo->getType(); | ||||
7694 | Ty = CreateParsedType(castType, castTInfo); | ||||
7695 | |||||
7696 | bool isVectorLiteral = false; | ||||
7697 | |||||
7698 | // Check for an altivec or OpenCL literal, | ||||
7699 | // i.e. all the elements are integer constants. | ||||
7700 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||
7701 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||
7702 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||
7703 | && castType->isVectorType() && (PE || PLE)) { | ||||
7704 | if (PLE && PLE->getNumExprs() == 0) { | ||||
7705 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||
7706 | return ExprError(); | ||||
7707 | } | ||||
7708 | if (PE || PLE->getNumExprs() == 1) { | ||||
7709 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||
7710 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||
7711 | isVectorLiteral = true; | ||||
7712 | } | ||||
7713 | else | ||||
7714 | isVectorLiteral = true; | ||||
7715 | } | ||||
7716 | |||||
7717 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||
7718 | // then handle it as such. | ||||
7719 | if (isVectorLiteral) | ||||
7720 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||
7721 | |||||
7722 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||
7723 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||
7724 | // sequence of BinOp comma operators. | ||||
7725 | if (isa<ParenListExpr>(CastExpr)) { | ||||
7726 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||
7727 | if (Result.isInvalid()) return ExprError(); | ||||
7728 | CastExpr = Result.get(); | ||||
7729 | } | ||||
7730 | |||||
7731 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | ||||
7732 | !getSourceManager().isInSystemMacro(LParenLoc)) | ||||
7733 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||
7734 | |||||
7735 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||
7736 | |||||
7737 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||
7738 | |||||
7739 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||
7740 | |||||
7741 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||
7742 | } | ||||
7743 | |||||
7744 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||
7745 | SourceLocation RParenLoc, Expr *E, | ||||
7746 | TypeSourceInfo *TInfo) { | ||||
7747 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7748, __extension__ __PRETTY_FUNCTION__)) | ||||
7748 | "Expected paren or paren list expression")(static_cast <bool> ((isa<ParenListExpr>(E) || isa <ParenExpr>(E)) && "Expected paren or paren list expression" ) ? void (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7748, __extension__ __PRETTY_FUNCTION__)); | ||||
7749 | |||||
7750 | Expr **exprs; | ||||
7751 | unsigned numExprs; | ||||
7752 | Expr *subExpr; | ||||
7753 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||
7754 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||
7755 | LiteralLParenLoc = PE->getLParenLoc(); | ||||
7756 | LiteralRParenLoc = PE->getRParenLoc(); | ||||
7757 | exprs = PE->getExprs(); | ||||
7758 | numExprs = PE->getNumExprs(); | ||||
7759 | } else { // isa<ParenExpr> by assertion at function entrance | ||||
7760 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||
7761 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||
7762 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||
7763 | exprs = &subExpr; | ||||
7764 | numExprs = 1; | ||||
7765 | } | ||||
7766 | |||||
7767 | QualType Ty = TInfo->getType(); | ||||
7768 | assert(Ty->isVectorType() && "Expected vector type")(static_cast <bool> (Ty->isVectorType() && "Expected vector type" ) ? void (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 7768, __extension__ __PRETTY_FUNCTION__)); | ||||
7769 | |||||
7770 | SmallVector<Expr *, 8> initExprs; | ||||
7771 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||
7772 | unsigned numElems = VTy->getNumElements(); | ||||
7773 | |||||
7774 | // '(...)' form of vector initialization in AltiVec: the number of | ||||
7775 | // initializers must be one or must match the size of the vector. | ||||
7776 | // If a single value is specified in the initializer then it will be | ||||
7777 | // replicated to all the components of the vector | ||||
7778 | if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, | ||||
7779 | VTy->getElementType())) | ||||
7780 | return ExprError(); | ||||
7781 | if (ShouldSplatAltivecScalarInCast(VTy)) { | ||||
7782 | // The number of initializers must be one or must match the size of the | ||||
7783 | // vector. If a single value is specified in the initializer then it will | ||||
7784 | // be replicated to all the components of the vector | ||||
7785 | if (numExprs == 1) { | ||||
7786 | QualType ElemTy = VTy->getElementType(); | ||||
7787 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7788 | if (Literal.isInvalid()) | ||||
7789 | return ExprError(); | ||||
7790 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7791 | PrepareScalarCast(Literal, ElemTy)); | ||||
7792 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7793 | } | ||||
7794 | else if (numExprs < numElems) { | ||||
7795 | Diag(E->getExprLoc(), | ||||
7796 | diag::err_incorrect_number_of_vector_initializers); | ||||
7797 | return ExprError(); | ||||
7798 | } | ||||
7799 | else | ||||
7800 | initExprs.append(exprs, exprs + numExprs); | ||||
7801 | } | ||||
7802 | else { | ||||
7803 | // For OpenCL, when the number of initializers is a single value, | ||||
7804 | // it will be replicated to all components of the vector. | ||||
7805 | if (getLangOpts().OpenCL && | ||||
7806 | VTy->getVectorKind() == VectorType::GenericVector && | ||||
7807 | numExprs == 1) { | ||||
7808 | QualType ElemTy = VTy->getElementType(); | ||||
7809 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7810 | if (Literal.isInvalid()) | ||||
7811 | return ExprError(); | ||||
7812 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7813 | PrepareScalarCast(Literal, ElemTy)); | ||||
7814 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7815 | } | ||||
7816 | |||||
7817 | initExprs.append(exprs, exprs + numExprs); | ||||
7818 | } | ||||
7819 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||
7820 | // braces instead of the original commas. | ||||
7821 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||
7822 | initExprs, LiteralRParenLoc); | ||||
7823 | initE->setType(Ty); | ||||
7824 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||
7825 | } | ||||
7826 | |||||
7827 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||
7828 | /// the ParenListExpr into a sequence of comma binary operators. | ||||
7829 | ExprResult | ||||
7830 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||
7831 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||
7832 | if (!E) | ||||
7833 | return OrigExpr; | ||||
7834 | |||||
7835 | ExprResult Result(E->getExpr(0)); | ||||
7836 | |||||
7837 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||
7838 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||
7839 | E->getExpr(i)); | ||||
7840 | |||||
7841 | if (Result.isInvalid()) return ExprError(); | ||||
7842 | |||||
7843 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||
7844 | } | ||||
7845 | |||||
7846 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||
7847 | SourceLocation R, | ||||
7848 | MultiExprArg Val) { | ||||
7849 | return ParenListExpr::Create(Context, L, Val, R); | ||||
7850 | } | ||||
7851 | |||||
7852 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||
7853 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||
7854 | /// emitted. | ||||
7855 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||
7856 | SourceLocation QuestionLoc) { | ||||
7857 | Expr *NullExpr = LHSExpr; | ||||
7858 | Expr *NonPointerExpr = RHSExpr; | ||||
7859 | Expr::NullPointerConstantKind NullKind = | ||||
7860 | NullExpr->isNullPointerConstant(Context, | ||||
7861 | Expr::NPC_ValueDependentIsNotNull); | ||||
7862 | |||||
7863 | if (NullKind == Expr::NPCK_NotNull) { | ||||
7864 | NullExpr = RHSExpr; | ||||
7865 | NonPointerExpr = LHSExpr; | ||||
7866 | NullKind = | ||||
7867 | NullExpr->isNullPointerConstant(Context, | ||||
7868 | Expr::NPC_ValueDependentIsNotNull); | ||||
7869 | } | ||||
7870 | |||||
7871 | if (NullKind == Expr::NPCK_NotNull) | ||||
7872 | return false; | ||||
7873 | |||||
7874 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||
7875 | return false; | ||||
7876 | |||||
7877 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||
7878 | // In this case, check to make sure that we got here from a "NULL" | ||||
7879 | // string in the source code. | ||||
7880 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||
7881 | SourceLocation loc = NullExpr->getExprLoc(); | ||||
7882 | if (!findMacroSpelling(loc, "NULL")) | ||||
7883 | return false; | ||||
7884 | } | ||||
7885 | |||||
7886 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||
7887 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||
7888 | << NonPointerExpr->getType() << DiagType | ||||
7889 | << NonPointerExpr->getSourceRange(); | ||||
7890 | return true; | ||||
7891 | } | ||||
7892 | |||||
7893 | /// Return false if the condition expression is valid, true otherwise. | ||||
7894 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||
7895 | QualType CondTy = Cond->getType(); | ||||
7896 | |||||
7897 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||
7898 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||
7899 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
7900 | << CondTy << Cond->getSourceRange(); | ||||
7901 | return true; | ||||
7902 | } | ||||
7903 | |||||
7904 | // C99 6.5.15p2 | ||||
7905 | if (CondTy->isScalarType()) return false; | ||||
7906 | |||||
7907 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||
7908 | << CondTy << Cond->getSourceRange(); | ||||
7909 | return true; | ||||
7910 | } | ||||
7911 | |||||
7912 | /// Handle when one or both operands are void type. | ||||
7913 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | ||||
7914 | ExprResult &RHS) { | ||||
7915 | Expr *LHSExpr = LHS.get(); | ||||
7916 | Expr *RHSExpr = RHS.get(); | ||||
7917 | |||||
7918 | if (!LHSExpr->getType()->isVoidType()) | ||||
7919 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7920 | << RHSExpr->getSourceRange(); | ||||
7921 | if (!RHSExpr->getType()->isVoidType()) | ||||
7922 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7923 | << LHSExpr->getSourceRange(); | ||||
7924 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7925 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7926 | return S.Context.VoidTy; | ||||
7927 | } | ||||
7928 | |||||
7929 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||
7930 | /// true otherwise. | ||||
7931 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||
7932 | QualType PointerTy) { | ||||
7933 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||
7934 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||
7935 | Expr::NPC_ValueDependentIsNull)) | ||||
7936 | return true; | ||||
7937 | |||||
7938 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||
7939 | return false; | ||||
7940 | } | ||||
7941 | |||||
7942 | /// Checks compatibility between two pointers and return the resulting | ||||
7943 | /// type. | ||||
7944 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||
7945 | ExprResult &RHS, | ||||
7946 | SourceLocation Loc) { | ||||
7947 | QualType LHSTy = LHS.get()->getType(); | ||||
7948 | QualType RHSTy = RHS.get()->getType(); | ||||
7949 | |||||
7950 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||
7951 | // Two identical pointers types are always compatible. | ||||
7952 | return LHSTy; | ||||
7953 | } | ||||
7954 | |||||
7955 | QualType lhptee, rhptee; | ||||
7956 | |||||
7957 | // Get the pointee types. | ||||
7958 | bool IsBlockPointer = false; | ||||
7959 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||
7960 | lhptee = LHSBTy->getPointeeType(); | ||||
7961 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||
7962 | IsBlockPointer = true; | ||||
7963 | } else { | ||||
7964 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7965 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7966 | } | ||||
7967 | |||||
7968 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||
7969 | // differently qualified versions of compatible types, the result type is | ||||
7970 | // a pointer to an appropriately qualified version of the composite | ||||
7971 | // type. | ||||
7972 | |||||
7973 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||
7974 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||
7975 | // be incompatible with address space 3: they may live on different devices or | ||||
7976 | // anything. | ||||
7977 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||
7978 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||
7979 | |||||
7980 | LangAS ResultAddrSpace = LangAS::Default; | ||||
7981 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||
7982 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||
7983 | |||||
7984 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||
7985 | // spaces is disallowed. | ||||
7986 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||
7987 | ResultAddrSpace = LAddrSpace; | ||||
7988 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||
7989 | ResultAddrSpace = RAddrSpace; | ||||
7990 | else { | ||||
7991 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
7992 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||
7993 | << RHS.get()->getSourceRange(); | ||||
7994 | return QualType(); | ||||
7995 | } | ||||
7996 | |||||
7997 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||
7998 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||
7999 | lhQual.removeCVRQualifiers(); | ||||
8000 | rhQual.removeCVRQualifiers(); | ||||
8001 | |||||
8002 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||
8003 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||
8004 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||
8005 | // qual types are compatible iff | ||||
8006 | // * corresponded types are compatible | ||||
8007 | // * CVR qualifiers are equal | ||||
8008 | // * address spaces are equal | ||||
8009 | // Thus for conditional operator we merge CVR and address space unqualified | ||||
8010 | // pointees and if there is a composite type we return a pointer to it with | ||||
8011 | // merged qualifiers. | ||||
8012 | LHSCastKind = | ||||
8013 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8014 | RHSCastKind = | ||||
8015 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
8016 | lhQual.removeAddressSpace(); | ||||
8017 | rhQual.removeAddressSpace(); | ||||
8018 | |||||
8019 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||
8020 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||
8021 | |||||
8022 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | ||||
8023 | |||||
8024 | if (CompositeTy.isNull()) { | ||||
8025 | // In this situation, we assume void* type. No especially good | ||||
8026 | // reason, but this is what gcc does, and we do have to pick | ||||
8027 | // to get a consistent AST. | ||||
8028 | QualType incompatTy; | ||||
8029 | incompatTy = S.Context.getPointerType( | ||||
8030 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||
8031 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||
8032 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||
8033 | |||||
8034 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||
8035 | // for casts between types with incompatible address space qualifiers. | ||||
8036 | // For the following code the compiler produces casts between global and | ||||
8037 | // local address spaces of the corresponded innermost pointees: | ||||
8038 | // local int *global *a; | ||||
8039 | // global int *global *b; | ||||
8040 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||
8041 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||
8042 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8043 | << RHS.get()->getSourceRange(); | ||||
8044 | |||||
8045 | return incompatTy; | ||||
8046 | } | ||||
8047 | |||||
8048 | // The pointer types are compatible. | ||||
8049 | // In case of OpenCL ResultTy should have the address space qualifier | ||||
8050 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||
8051 | // operands of the conditional operator. | ||||
8052 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||
8053 | if (S.getLangOpts().OpenCL) { | ||||
8054 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||
8055 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||
8056 | return S.Context | ||||
8057 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||
8058 | .withCVRQualifiers(MergedCVRQual); | ||||
8059 | } | ||||
8060 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||
8061 | }(); | ||||
8062 | if (IsBlockPointer) | ||||
8063 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||
8064 | else | ||||
8065 | ResultTy = S.Context.getPointerType(ResultTy); | ||||
8066 | |||||
8067 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||
8068 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||
8069 | return ResultTy; | ||||
8070 | } | ||||
8071 | |||||
8072 | /// Return the resulting type when the operands are both block pointers. | ||||
8073 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||
8074 | ExprResult &LHS, | ||||
8075 | ExprResult &RHS, | ||||
8076 | SourceLocation Loc) { | ||||
8077 | QualType LHSTy = LHS.get()->getType(); | ||||
8078 | QualType RHSTy = RHS.get()->getType(); | ||||
8079 | |||||
8080 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||
8081 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||
8082 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||
8083 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8084 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8085 | return destType; | ||||
8086 | } | ||||
8087 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||
8088 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8089 | << RHS.get()->getSourceRange(); | ||||
8090 | return QualType(); | ||||
8091 | } | ||||
8092 | |||||
8093 | // We have 2 block pointer types. | ||||
8094 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8095 | } | ||||
8096 | |||||
8097 | /// Return the resulting type when the operands are both pointers. | ||||
8098 | static QualType | ||||
8099 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||
8100 | ExprResult &RHS, | ||||
8101 | SourceLocation Loc) { | ||||
8102 | // get the pointer types | ||||
8103 | QualType LHSTy = LHS.get()->getType(); | ||||
8104 | QualType RHSTy = RHS.get()->getType(); | ||||
8105 | |||||
8106 | // get the "pointed to" types | ||||
8107 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8108 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8109 | |||||
8110 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||
8111 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||
8112 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||
8113 | QualType destPointee | ||||
8114 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8115 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8116 | // Add qualifiers if necessary. | ||||
8117 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8118 | // Promote to void*. | ||||
8119 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8120 | return destType; | ||||
8121 | } | ||||
8122 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||
8123 | QualType destPointee | ||||
8124 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8125 | QualType destType = S.Context.getPointerType(destPointee); | ||||
8126 | // Add qualifiers if necessary. | ||||
8127 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8128 | // Promote to void*. | ||||
8129 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8130 | return destType; | ||||
8131 | } | ||||
8132 | |||||
8133 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
8134 | } | ||||
8135 | |||||
8136 | /// Return false if the first expression is not an integer and the second | ||||
8137 | /// expression is not a pointer, true otherwise. | ||||
8138 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||
8139 | Expr* PointerExpr, SourceLocation Loc, | ||||
8140 | bool IsIntFirstExpr) { | ||||
8141 | if (!PointerExpr->getType()->isPointerType() || | ||||
8142 | !Int.get()->getType()->isIntegerType()) | ||||
8143 | return false; | ||||
8144 | |||||
8145 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||
8146 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||
8147 | |||||
8148 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||
8149 | << Expr1->getType() << Expr2->getType() | ||||
8150 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||
8151 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||
8152 | CK_IntegralToPointer); | ||||
8153 | return true; | ||||
8154 | } | ||||
8155 | |||||
8156 | /// Simple conversion between integer and floating point types. | ||||
8157 | /// | ||||
8158 | /// Used when handling the OpenCL conditional operator where the | ||||
8159 | /// condition is a vector while the other operands are scalar. | ||||
8160 | /// | ||||
8161 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||
8162 | /// types are either integer or floating type. Between the two | ||||
8163 | /// operands, the type with the higher rank is defined as the "result | ||||
8164 | /// type". The other operand needs to be promoted to the same type. No | ||||
8165 | /// other type promotion is allowed. We cannot use | ||||
8166 | /// UsualArithmeticConversions() for this purpose, since it always | ||||
8167 | /// promotes promotable types. | ||||
8168 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||
8169 | ExprResult &RHS, | ||||
8170 | SourceLocation QuestionLoc) { | ||||
8171 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
8172 | if (LHS.isInvalid()) | ||||
8173 | return QualType(); | ||||
8174 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
8175 | if (RHS.isInvalid()) | ||||
8176 | return QualType(); | ||||
8177 | |||||
8178 | // For conversion purposes, we ignore any qualifiers. | ||||
8179 | // For example, "const float" and "float" are equivalent. | ||||
8180 | QualType LHSType = | ||||
8181 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
8182 | QualType RHSType = | ||||
8183 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
8184 | |||||
8185 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||
8186 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8187 | << LHSType << LHS.get()->getSourceRange(); | ||||
8188 | return QualType(); | ||||
8189 | } | ||||
8190 | |||||
8191 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||
8192 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
8193 | << RHSType << RHS.get()->getSourceRange(); | ||||
8194 | return QualType(); | ||||
8195 | } | ||||
8196 | |||||
8197 | // If both types are identical, no conversion is needed. | ||||
8198 | if (LHSType == RHSType) | ||||
8199 | return LHSType; | ||||
8200 | |||||
8201 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
8202 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
8203 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
8204 | /*IsCompAssign = */ false); | ||||
8205 | |||||
8206 | // Finally, we have two differing integer types. | ||||
8207 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
8208 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||
8209 | } | ||||
8210 | |||||
8211 | /// Convert scalar operands to a vector that matches the | ||||
8212 | /// condition in length. | ||||
8213 | /// | ||||
8214 | /// Used when handling the OpenCL conditional operator where the | ||||
8215 | /// condition is a vector while the other operands are scalar. | ||||
8216 | /// | ||||
8217 | /// We first compute the "result type" for the scalar operands | ||||
8218 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||
8219 | /// into a vector of that type where the length matches the condition | ||||
8220 | /// vector type. s6.11.6 requires that the element types of the result | ||||
8221 | /// and the condition must have the same number of bits. | ||||
8222 | static QualType | ||||
8223 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
8224 | QualType CondTy, SourceLocation QuestionLoc) { | ||||
8225 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||
8226 | if (ResTy.isNull()) return QualType(); | ||||
8227 | |||||
8228 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8229 | assert(CV)(static_cast <bool> (CV) ? void (0) : __assert_fail ("CV" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8229, __extension__ __PRETTY_FUNCTION__)); | ||||
8230 | |||||
8231 | // Determine the vector result type | ||||
8232 | unsigned NumElements = CV->getNumElements(); | ||||
8233 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||
8234 | |||||
8235 | // Ensure that all types have the same number of bits | ||||
8236 | if (S.Context.getTypeSize(CV->getElementType()) | ||||
8237 | != S.Context.getTypeSize(ResTy)) { | ||||
8238 | // Since VectorTy is created internally, it does not pretty print | ||||
8239 | // with an OpenCL name. Instead, we just print a description. | ||||
8240 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||
8241 | SmallString<64> Str; | ||||
8242 | llvm::raw_svector_ostream OS(Str); | ||||
8243 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||
8244 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8245 | << CondTy << OS.str(); | ||||
8246 | return QualType(); | ||||
8247 | } | ||||
8248 | |||||
8249 | // Convert operands to the vector result type | ||||
8250 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||
8251 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||
8252 | |||||
8253 | return VectorTy; | ||||
8254 | } | ||||
8255 | |||||
8256 | /// Return false if this is a valid OpenCL condition vector | ||||
8257 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||
8258 | SourceLocation QuestionLoc) { | ||||
8259 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||
8260 | // integral type. | ||||
8261 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||
8262 | assert(CondTy)(static_cast <bool> (CondTy) ? void (0) : __assert_fail ("CondTy", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8262, __extension__ __PRETTY_FUNCTION__)); | ||||
8263 | QualType EleTy = CondTy->getElementType(); | ||||
8264 | if (EleTy->isIntegerType()) return false; | ||||
8265 | |||||
8266 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8267 | << Cond->getType() << Cond->getSourceRange(); | ||||
8268 | return true; | ||||
8269 | } | ||||
8270 | |||||
8271 | /// Return false if the vector condition type and the vector | ||||
8272 | /// result type are compatible. | ||||
8273 | /// | ||||
8274 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||
8275 | /// number of elements, and their element types have the same number | ||||
8276 | /// of bits. | ||||
8277 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||
8278 | SourceLocation QuestionLoc) { | ||||
8279 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8280 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||
8281 | assert(CV && RV)(static_cast <bool> (CV && RV) ? void (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8281, __extension__ __PRETTY_FUNCTION__)); | ||||
8282 | |||||
8283 | if (CV->getNumElements() != RV->getNumElements()) { | ||||
8284 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||
8285 | << CondTy << VecResTy; | ||||
8286 | return true; | ||||
8287 | } | ||||
8288 | |||||
8289 | QualType CVE = CV->getElementType(); | ||||
8290 | QualType RVE = RV->getElementType(); | ||||
8291 | |||||
8292 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||
8293 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8294 | << CondTy << VecResTy; | ||||
8295 | return true; | ||||
8296 | } | ||||
8297 | |||||
8298 | return false; | ||||
8299 | } | ||||
8300 | |||||
8301 | /// Return the resulting type for the conditional operator in | ||||
8302 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||
8303 | /// s6.3.i) when the condition is a vector type. | ||||
8304 | static QualType | ||||
8305 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||
8306 | ExprResult &LHS, ExprResult &RHS, | ||||
8307 | SourceLocation QuestionLoc) { | ||||
8308 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||
8309 | if (Cond.isInvalid()) | ||||
8310 | return QualType(); | ||||
8311 | QualType CondTy = Cond.get()->getType(); | ||||
8312 | |||||
8313 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||
8314 | return QualType(); | ||||
8315 | |||||
8316 | // If either operand is a vector then find the vector type of the | ||||
8317 | // result as specified in OpenCL v1.1 s6.3.i. | ||||
8318 | if (LHS.get()->getType()->isVectorType() || | ||||
8319 | RHS.get()->getType()->isVectorType()) { | ||||
8320 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||
8321 | /*isCompAssign*/false, | ||||
8322 | /*AllowBothBool*/true, | ||||
8323 | /*AllowBoolConversions*/false); | ||||
8324 | if (VecResTy.isNull()) return QualType(); | ||||
8325 | // The result type must match the condition type as specified in | ||||
8326 | // OpenCL v1.1 s6.11.6. | ||||
8327 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||
8328 | return QualType(); | ||||
8329 | return VecResTy; | ||||
8330 | } | ||||
8331 | |||||
8332 | // Both operands are scalar. | ||||
8333 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||
8334 | } | ||||
8335 | |||||
8336 | /// Return true if the Expr is block type | ||||
8337 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||
8338 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
8339 | QualType Ty = CE->getCallee()->getType(); | ||||
8340 | if (Ty->isBlockPointerType()) { | ||||
8341 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||
8342 | return true; | ||||
8343 | } | ||||
8344 | } | ||||
8345 | return false; | ||||
8346 | } | ||||
8347 | |||||
8348 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||
8349 | /// In that case, LHS = cond. | ||||
8350 | /// C99 6.5.15 | ||||
8351 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||
8352 | ExprResult &RHS, ExprValueKind &VK, | ||||
8353 | ExprObjectKind &OK, | ||||
8354 | SourceLocation QuestionLoc) { | ||||
8355 | |||||
8356 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||
8357 | if (!LHSResult.isUsable()) return QualType(); | ||||
8358 | LHS = LHSResult; | ||||
8359 | |||||
8360 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||
8361 | if (!RHSResult.isUsable()) return QualType(); | ||||
8362 | RHS = RHSResult; | ||||
8363 | |||||
8364 | // C++ is sufficiently different to merit its own checker. | ||||
8365 | if (getLangOpts().CPlusPlus) | ||||
8366 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||
8367 | |||||
8368 | VK = VK_PRValue; | ||||
8369 | OK = OK_Ordinary; | ||||
8370 | |||||
8371 | if (Context.isDependenceAllowed() && | ||||
8372 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||
8373 | RHS.get()->isTypeDependent())) { | ||||
8374 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8374, __extension__ __PRETTY_FUNCTION__)); | ||||
8375 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8377, __extension__ __PRETTY_FUNCTION__)) | ||||
8376 | RHS.get()->containsErrors()) &&(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8377, __extension__ __PRETTY_FUNCTION__)) | ||||
8377 | "should only occur in error-recovery path.")(static_cast <bool> ((Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors ()) && "should only occur in error-recovery path.") ? void (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8377, __extension__ __PRETTY_FUNCTION__)); | ||||
8378 | return Context.DependentTy; | ||||
8379 | } | ||||
8380 | |||||
8381 | // The OpenCL operator with a vector condition is sufficiently | ||||
8382 | // different to merit its own checker. | ||||
8383 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||
8384 | Cond.get()->getType()->isExtVectorType()) | ||||
8385 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||
8386 | |||||
8387 | // First, check the condition. | ||||
8388 | Cond = UsualUnaryConversions(Cond.get()); | ||||
8389 | if (Cond.isInvalid()) | ||||
8390 | return QualType(); | ||||
8391 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||
8392 | return QualType(); | ||||
8393 | |||||
8394 | // Now check the two expressions. | ||||
8395 | if (LHS.get()->getType()->isVectorType() || | ||||
8396 | RHS.get()->getType()->isVectorType()) | ||||
8397 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | ||||
8398 | /*AllowBothBool*/true, | ||||
8399 | /*AllowBoolConversions*/false); | ||||
8400 | |||||
8401 | QualType ResTy = | ||||
8402 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||
8403 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8404 | return QualType(); | ||||
8405 | |||||
8406 | QualType LHSTy = LHS.get()->getType(); | ||||
8407 | QualType RHSTy = RHS.get()->getType(); | ||||
8408 | |||||
8409 | // Diagnose attempts to convert between __float128 and long double where | ||||
8410 | // such conversions currently can't be handled. | ||||
8411 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||
8412 | Diag(QuestionLoc, | ||||
8413 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||
8414 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8415 | return QualType(); | ||||
8416 | } | ||||
8417 | |||||
8418 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||
8419 | // selection operator (?:). | ||||
8420 | if (getLangOpts().OpenCL && | ||||
8421 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | ||||
8422 | return QualType(); | ||||
8423 | } | ||||
8424 | |||||
8425 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||
8426 | // to find a common type: C99 6.5.15p3,5. | ||||
8427 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||
8428 | // Disallow invalid arithmetic conversions, such as those between ExtInts of | ||||
8429 | // different sizes, or between ExtInts and other types. | ||||
8430 | if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { | ||||
8431 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8432 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8433 | << RHS.get()->getSourceRange(); | ||||
8434 | return QualType(); | ||||
8435 | } | ||||
8436 | |||||
8437 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||
8438 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||
8439 | |||||
8440 | return ResTy; | ||||
8441 | } | ||||
8442 | |||||
8443 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||
8444 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||
8445 | return LHSTy; | ||||
8446 | } | ||||
8447 | |||||
8448 | // If both operands are the same structure or union type, the result is that | ||||
8449 | // type. | ||||
8450 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||
8451 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||
8452 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||
8453 | // "If both the operands have structure or union type, the result has | ||||
8454 | // that type." This implies that CV qualifiers are dropped. | ||||
8455 | return LHSTy.getUnqualifiedType(); | ||||
8456 | // FIXME: Type of conditional expression must be complete in C mode. | ||||
8457 | } | ||||
8458 | |||||
8459 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||
8460 | // The following || allows only one side to be void (a GCC-ism). | ||||
8461 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||
8462 | return checkConditionalVoidType(*this, LHS, RHS); | ||||
8463 | } | ||||
8464 | |||||
8465 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||
8466 | // the type of the other operand." | ||||
8467 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||
8468 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||
8469 | |||||
8470 | // All objective-c pointer type analysis is done here. | ||||
8471 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||
8472 | QuestionLoc); | ||||
8473 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8474 | return QualType(); | ||||
8475 | if (!compositeType.isNull()) | ||||
8476 | return compositeType; | ||||
8477 | |||||
8478 | |||||
8479 | // Handle block pointer types. | ||||
8480 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||
8481 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||
8482 | QuestionLoc); | ||||
8483 | |||||
8484 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||
8485 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||
8486 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||
8487 | QuestionLoc); | ||||
8488 | |||||
8489 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||
8490 | // null pointers have been filtered out by this point. | ||||
8491 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||
8492 | /*IsIntFirstExpr=*/true)) | ||||
8493 | return RHSTy; | ||||
8494 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||
8495 | /*IsIntFirstExpr=*/false)) | ||||
8496 | return LHSTy; | ||||
8497 | |||||
8498 | // Allow ?: operations in which both operands have the same | ||||
8499 | // built-in sizeless type. | ||||
8500 | if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) | ||||
8501 | return LHSTy; | ||||
8502 | |||||
8503 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||
8504 | // constant and the other is not a pointer type. In this case, the user most | ||||
8505 | // likely forgot to take the address of the other expression. | ||||
8506 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||
8507 | return QualType(); | ||||
8508 | |||||
8509 | // Otherwise, the operands are not compatible. | ||||
8510 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8511 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8512 | << RHS.get()->getSourceRange(); | ||||
8513 | return QualType(); | ||||
8514 | } | ||||
8515 | |||||
8516 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||
8517 | /// two objective-c pointer types of the two input expressions. | ||||
8518 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||
8519 | SourceLocation QuestionLoc) { | ||||
8520 | QualType LHSTy = LHS.get()->getType(); | ||||
8521 | QualType RHSTy = RHS.get()->getType(); | ||||
8522 | |||||
8523 | // Handle things like Class and struct objc_class*. Here we case the result | ||||
8524 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||
8525 | // redefinition type if an attempt is made to access its fields. | ||||
8526 | if (LHSTy->isObjCClassType() && | ||||
8527 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8528 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8529 | return LHSTy; | ||||
8530 | } | ||||
8531 | if (RHSTy->isObjCClassType() && | ||||
8532 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8533 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8534 | return RHSTy; | ||||
8535 | } | ||||
8536 | // And the same for struct objc_object* / id | ||||
8537 | if (LHSTy->isObjCIdType() && | ||||
8538 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8539 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8540 | return LHSTy; | ||||
8541 | } | ||||
8542 | if (RHSTy->isObjCIdType() && | ||||
8543 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8544 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8545 | return RHSTy; | ||||
8546 | } | ||||
8547 | // And the same for struct objc_selector* / SEL | ||||
8548 | if (Context.isObjCSelType(LHSTy) && | ||||
8549 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8550 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||
8551 | return LHSTy; | ||||
8552 | } | ||||
8553 | if (Context.isObjCSelType(RHSTy) && | ||||
8554 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8555 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||
8556 | return RHSTy; | ||||
8557 | } | ||||
8558 | // Check constraints for Objective-C object pointers types. | ||||
8559 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8560 | |||||
8561 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||
8562 | // Two identical object pointer types are always compatible. | ||||
8563 | return LHSTy; | ||||
8564 | } | ||||
8565 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||
8566 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||
8567 | QualType compositeType = LHSTy; | ||||
8568 | |||||
8569 | // If both operands are interfaces and either operand can be | ||||
8570 | // assigned to the other, use that type as the composite | ||||
8571 | // type. This allows | ||||
8572 | // xxx ? (A*) a : (B*) b | ||||
8573 | // where B is a subclass of A. | ||||
8574 | // | ||||
8575 | // Additionally, as for assignment, if either type is 'id' | ||||
8576 | // allow silent coercion. Finally, if the types are | ||||
8577 | // incompatible then make sure to use 'id' as the composite | ||||
8578 | // type so the result is acceptable for sending messages to. | ||||
8579 | |||||
8580 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||
8581 | // It could return the composite type. | ||||
8582 | if (!(compositeType = | ||||
8583 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||
8584 | // Nothing more to do. | ||||
8585 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||
8586 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||
8587 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||
8588 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||
8589 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||
8590 | RHSOPT->isObjCQualifiedIdType()) && | ||||
8591 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||
8592 | true)) { | ||||
8593 | // Need to handle "id<xx>" explicitly. | ||||
8594 | // GCC allows qualified id and any Objective-C type to devolve to | ||||
8595 | // id. Currently localizing to here until clear this should be | ||||
8596 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||
8597 | compositeType = Context.getObjCIdType(); | ||||
8598 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||
8599 | compositeType = Context.getObjCIdType(); | ||||
8600 | } else { | ||||
8601 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||
8602 | << LHSTy << RHSTy | ||||
8603 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8604 | QualType incompatTy = Context.getObjCIdType(); | ||||
8605 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||
8606 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||
8607 | return incompatTy; | ||||
8608 | } | ||||
8609 | // The object pointer types are compatible. | ||||
8610 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||
8611 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||
8612 | return compositeType; | ||||
8613 | } | ||||
8614 | // Check Objective-C object pointer types and 'void *' | ||||
8615 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8616 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8617 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8618 | // so these types are not compatible. | ||||
8619 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8620 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8621 | LHS = RHS = true; | ||||
8622 | return QualType(); | ||||
8623 | } | ||||
8624 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8625 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8626 | QualType destPointee | ||||
8627 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8628 | QualType destType = Context.getPointerType(destPointee); | ||||
8629 | // Add qualifiers if necessary. | ||||
8630 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8631 | // Promote to void*. | ||||
8632 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8633 | return destType; | ||||
8634 | } | ||||
8635 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||
8636 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8637 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8638 | // so these types are not compatible. | ||||
8639 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8640 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8641 | LHS = RHS = true; | ||||
8642 | return QualType(); | ||||
8643 | } | ||||
8644 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8645 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8646 | QualType destPointee | ||||
8647 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8648 | QualType destType = Context.getPointerType(destPointee); | ||||
8649 | // Add qualifiers if necessary. | ||||
8650 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8651 | // Promote to void*. | ||||
8652 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8653 | return destType; | ||||
8654 | } | ||||
8655 | return QualType(); | ||||
8656 | } | ||||
8657 | |||||
8658 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||
8659 | /// ParenRange in parentheses. | ||||
8660 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||
8661 | const PartialDiagnostic &Note, | ||||
8662 | SourceRange ParenRange) { | ||||
8663 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||
8664 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||
8665 | EndLoc.isValid()) { | ||||
8666 | Self.Diag(Loc, Note) | ||||
8667 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||
8668 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||
8669 | } else { | ||||
8670 | // We can't display the parentheses, so just show the bare note. | ||||
8671 | Self.Diag(Loc, Note) << ParenRange; | ||||
8672 | } | ||||
8673 | } | ||||
8674 | |||||
8675 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||
8676 | return BinaryOperator::isAdditiveOp(Opc) || | ||||
8677 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||
8678 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||
8679 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||
8680 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||
8681 | // logical-xor because there is no logical-xor operator. The logical | ||||
8682 | // operators, including uses of xor, have a high false positive rate for | ||||
8683 | // precedence warnings. | ||||
8684 | } | ||||
8685 | |||||
8686 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||
8687 | /// expression, either using a built-in or overloaded operator, | ||||
8688 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||
8689 | /// expression. | ||||
8690 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||
8691 | Expr **RHSExprs) { | ||||
8692 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||
8693 | E = E->IgnoreImpCasts(); | ||||
8694 | E = E->IgnoreConversionOperatorSingleStep(); | ||||
8695 | E = E->IgnoreImpCasts(); | ||||
8696 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||
8697 | E = MTE->getSubExpr(); | ||||
8698 | E = E->IgnoreImpCasts(); | ||||
8699 | } | ||||
8700 | |||||
8701 | // Built-in binary operator. | ||||
8702 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||
8703 | if (IsArithmeticOp(OP->getOpcode())) { | ||||
8704 | *Opcode = OP->getOpcode(); | ||||
8705 | *RHSExprs = OP->getRHS(); | ||||
8706 | return true; | ||||
8707 | } | ||||
8708 | } | ||||
8709 | |||||
8710 | // Overloaded operator. | ||||
8711 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
8712 | if (Call->getNumArgs() != 2) | ||||
8713 | return false; | ||||
8714 | |||||
8715 | // Make sure this is really a binary operator that is safe to pass into | ||||
8716 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||
8717 | OverloadedOperatorKind OO = Call->getOperator(); | ||||
8718 | if (OO < OO_Plus || OO > OO_Arrow || | ||||
8719 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||
8720 | return false; | ||||
8721 | |||||
8722 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||
8723 | if (IsArithmeticOp(OpKind)) { | ||||
8724 | *Opcode = OpKind; | ||||
8725 | *RHSExprs = Call->getArg(1); | ||||
8726 | return true; | ||||
8727 | } | ||||
8728 | } | ||||
8729 | |||||
8730 | return false; | ||||
8731 | } | ||||
8732 | |||||
8733 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||
8734 | /// or is a logical expression such as (x==y) which has int type, but is | ||||
8735 | /// commonly interpreted as boolean. | ||||
8736 | static bool ExprLooksBoolean(Expr *E) { | ||||
8737 | E = E->IgnoreParenImpCasts(); | ||||
8738 | |||||
8739 | if (E->getType()->isBooleanType()) | ||||
8740 | return true; | ||||
8741 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||
8742 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||
8743 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||
8744 | return OP->getOpcode() == UO_LNot; | ||||
8745 | if (E->getType()->isPointerType()) | ||||
8746 | return true; | ||||
8747 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||
8748 | // type"s (commonly pointer-to-members)? | ||||
8749 | |||||
8750 | return false; | ||||
8751 | } | ||||
8752 | |||||
8753 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||
8754 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||
8755 | /// the conditional operator has higher precedence, for example: | ||||
8756 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||
8757 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||
8758 | SourceLocation OpLoc, | ||||
8759 | Expr *Condition, | ||||
8760 | Expr *LHSExpr, | ||||
8761 | Expr *RHSExpr) { | ||||
8762 | BinaryOperatorKind CondOpcode; | ||||
8763 | Expr *CondRHS; | ||||
8764 | |||||
8765 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||
8766 | return; | ||||
8767 | if (!ExprLooksBoolean(CondRHS)) | ||||
8768 | return; | ||||
8769 | |||||
8770 | // The condition is an arithmetic binary expression, with a right- | ||||
8771 | // hand side that looks boolean, so warn. | ||||
8772 | |||||
8773 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||
8774 | ? diag::warn_precedence_bitwise_conditional | ||||
8775 | : diag::warn_precedence_conditional; | ||||
8776 | |||||
8777 | Self.Diag(OpLoc, DiagID) | ||||
8778 | << Condition->getSourceRange() | ||||
8779 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||
8780 | |||||
8781 | SuggestParentheses( | ||||
8782 | Self, OpLoc, | ||||
8783 | Self.PDiag(diag::note_precedence_silence) | ||||
8784 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||
8785 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||
8786 | |||||
8787 | SuggestParentheses(Self, OpLoc, | ||||
8788 | Self.PDiag(diag::note_precedence_conditional_first), | ||||
8789 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
8790 | } | ||||
8791 | |||||
8792 | /// Compute the nullability of a conditional expression. | ||||
8793 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||
8794 | QualType LHSTy, QualType RHSTy, | ||||
8795 | ASTContext &Ctx) { | ||||
8796 | if (!ResTy->isAnyPointerType()) | ||||
8797 | return ResTy; | ||||
8798 | |||||
8799 | auto GetNullability = [&Ctx](QualType Ty) { | ||||
8800 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | ||||
8801 | if (Kind) { | ||||
8802 | // For our purposes, treat _Nullable_result as _Nullable. | ||||
8803 | if (*Kind == NullabilityKind::NullableResult) | ||||
8804 | return NullabilityKind::Nullable; | ||||
8805 | return *Kind; | ||||
8806 | } | ||||
8807 | return NullabilityKind::Unspecified; | ||||
8808 | }; | ||||
8809 | |||||
8810 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||
8811 | NullabilityKind MergedKind; | ||||
8812 | |||||
8813 | // Compute nullability of a binary conditional expression. | ||||
8814 | if (IsBin) { | ||||
8815 | if (LHSKind == NullabilityKind::NonNull) | ||||
8816 | MergedKind = NullabilityKind::NonNull; | ||||
8817 | else | ||||
8818 | MergedKind = RHSKind; | ||||
8819 | // Compute nullability of a normal conditional expression. | ||||
8820 | } else { | ||||
8821 | if (LHSKind == NullabilityKind::Nullable || | ||||
8822 | RHSKind == NullabilityKind::Nullable) | ||||
8823 | MergedKind = NullabilityKind::Nullable; | ||||
8824 | else if (LHSKind == NullabilityKind::NonNull) | ||||
8825 | MergedKind = RHSKind; | ||||
8826 | else if (RHSKind == NullabilityKind::NonNull) | ||||
8827 | MergedKind = LHSKind; | ||||
8828 | else | ||||
8829 | MergedKind = NullabilityKind::Unspecified; | ||||
8830 | } | ||||
8831 | |||||
8832 | // Return if ResTy already has the correct nullability. | ||||
8833 | if (GetNullability(ResTy) == MergedKind) | ||||
8834 | return ResTy; | ||||
8835 | |||||
8836 | // Strip all nullability from ResTy. | ||||
8837 | while (ResTy->getNullability(Ctx)) | ||||
8838 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||
8839 | |||||
8840 | // Create a new AttributedType with the new nullability kind. | ||||
8841 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||
8842 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||
8843 | } | ||||
8844 | |||||
8845 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||
8846 | /// in the case of a the GNU conditional expr extension. | ||||
8847 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||
8848 | SourceLocation ColonLoc, | ||||
8849 | Expr *CondExpr, Expr *LHSExpr, | ||||
8850 | Expr *RHSExpr) { | ||||
8851 | if (!Context.isDependenceAllowed()) { | ||||
8852 | // C cannot handle TypoExpr nodes in the condition because it | ||||
8853 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
8854 | // been dealt with before checking the operands. | ||||
8855 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||
8856 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||
8857 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||
8858 | |||||
8859 | if (!CondResult.isUsable()) | ||||
8860 | return ExprError(); | ||||
8861 | |||||
8862 | if (LHSExpr) { | ||||
8863 | if (!LHSResult.isUsable()) | ||||
8864 | return ExprError(); | ||||
8865 | } | ||||
8866 | |||||
8867 | if (!RHSResult.isUsable()) | ||||
8868 | return ExprError(); | ||||
8869 | |||||
8870 | CondExpr = CondResult.get(); | ||||
8871 | LHSExpr = LHSResult.get(); | ||||
8872 | RHSExpr = RHSResult.get(); | ||||
8873 | } | ||||
8874 | |||||
8875 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||
8876 | // was the condition. | ||||
8877 | OpaqueValueExpr *opaqueValue = nullptr; | ||||
8878 | Expr *commonExpr = nullptr; | ||||
8879 | if (!LHSExpr) { | ||||
8880 | commonExpr = CondExpr; | ||||
8881 | // Lower out placeholder types first. This is important so that we don't | ||||
8882 | // try to capture a placeholder. This happens in few cases in C++; such | ||||
8883 | // as Objective-C++'s dictionary subscripting syntax. | ||||
8884 | if (commonExpr->hasPlaceholderType()) { | ||||
8885 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||
8886 | if (!result.isUsable()) return ExprError(); | ||||
8887 | commonExpr = result.get(); | ||||
8888 | } | ||||
8889 | // We usually want to apply unary conversions *before* saving, except | ||||
8890 | // in the special case of a C++ l-value conditional. | ||||
8891 | if (!(getLangOpts().CPlusPlus | ||||
8892 | && !commonExpr->isTypeDependent() | ||||
8893 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||
8894 | && commonExpr->isGLValue() | ||||
8895 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||
8896 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||
8897 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||
8898 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||
8899 | if (commonRes.isInvalid()) | ||||
8900 | return ExprError(); | ||||
8901 | commonExpr = commonRes.get(); | ||||
8902 | } | ||||
8903 | |||||
8904 | // If the common expression is a class or array prvalue, materialize it | ||||
8905 | // so that we can safely refer to it multiple times. | ||||
8906 | if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || | ||||
8907 | commonExpr->getType()->isArrayType())) { | ||||
8908 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||
8909 | if (MatExpr.isInvalid()) | ||||
8910 | return ExprError(); | ||||
8911 | commonExpr = MatExpr.get(); | ||||
8912 | } | ||||
8913 | |||||
8914 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||
8915 | commonExpr->getType(), | ||||
8916 | commonExpr->getValueKind(), | ||||
8917 | commonExpr->getObjectKind(), | ||||
8918 | commonExpr); | ||||
8919 | LHSExpr = CondExpr = opaqueValue; | ||||
8920 | } | ||||
8921 | |||||
8922 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||
8923 | ExprValueKind VK = VK_PRValue; | ||||
8924 | ExprObjectKind OK = OK_Ordinary; | ||||
8925 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||
8926 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||
8927 | VK, OK, QuestionLoc); | ||||
8928 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||
8929 | RHS.isInvalid()) | ||||
8930 | return ExprError(); | ||||
8931 | |||||
8932 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||
8933 | RHS.get()); | ||||
8934 | |||||
8935 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||
8936 | |||||
8937 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||
8938 | Context); | ||||
8939 | |||||
8940 | if (!commonExpr) | ||||
8941 | return new (Context) | ||||
8942 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||
8943 | RHS.get(), result, VK, OK); | ||||
8944 | |||||
8945 | return new (Context) BinaryConditionalOperator( | ||||
8946 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||
8947 | ColonLoc, result, VK, OK); | ||||
8948 | } | ||||
8949 | |||||
8950 | // Check if we have a conversion between incompatible cmse function pointer | ||||
8951 | // types, that is, a conversion between a function pointer with the | ||||
8952 | // cmse_nonsecure_call attribute and one without. | ||||
8953 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||
8954 | QualType ToType) { | ||||
8955 | if (const auto *ToFn = | ||||
8956 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||
8957 | if (const auto *FromFn = | ||||
8958 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||
8959 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||
8960 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||
8961 | |||||
8962 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||
8963 | } | ||||
8964 | } | ||||
8965 | return false; | ||||
8966 | } | ||||
8967 | |||||
8968 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||
8969 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||
8970 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||
8971 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||
8972 | // FIXME: add a couple examples in this comment. | ||||
8973 | static Sema::AssignConvertType | ||||
8974 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | ||||
8975 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8975, __extension__ __PRETTY_FUNCTION__)); | ||||
8976 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 8976, __extension__ __PRETTY_FUNCTION__)); | ||||
8977 | |||||
8978 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
8979 | const Type *lhptee, *rhptee; | ||||
8980 | Qualifiers lhq, rhq; | ||||
8981 | std::tie(lhptee, lhq) = | ||||
8982 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||
8983 | std::tie(rhptee, rhq) = | ||||
8984 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||
8985 | |||||
8986 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
8987 | |||||
8988 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||
8989 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||
8990 | // qualifiers of the type *pointed to* by the right; | ||||
8991 | |||||
8992 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||
8993 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||
8994 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||
8995 | // Ignore lifetime for further calculation. | ||||
8996 | lhq.removeObjCLifetime(); | ||||
8997 | rhq.removeObjCLifetime(); | ||||
8998 | } | ||||
8999 | |||||
9000 | if (!lhq.compatiblyIncludes(rhq)) { | ||||
9001 | // Treat address-space mismatches as fatal. | ||||
9002 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||
9003 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9004 | |||||
9005 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||
9006 | // and from void*. | ||||
9007 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||
9008 | .compatiblyIncludes( | ||||
9009 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||
9010 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||
9011 | ; // keep old | ||||
9012 | |||||
9013 | // Treat lifetime mismatches as fatal. | ||||
9014 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||
9015 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||
9016 | |||||
9017 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||
9018 | // as still compatible in C. | ||||
9019 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9020 | } | ||||
9021 | |||||
9022 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||
9023 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||
9024 | // version of void... | ||||
9025 | if (lhptee->isVoidType()) { | ||||
9026 | if (rhptee->isIncompleteOrObjectType()) | ||||
9027 | return ConvTy; | ||||
9028 | |||||
9029 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9030 | assert(rhptee->isFunctionType())(static_cast <bool> (rhptee->isFunctionType()) ? void (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9030, __extension__ __PRETTY_FUNCTION__)); | ||||
9031 | return Sema::FunctionVoidPointer; | ||||
9032 | } | ||||
9033 | |||||
9034 | if (rhptee->isVoidType()) { | ||||
9035 | if (lhptee->isIncompleteOrObjectType()) | ||||
9036 | return ConvTy; | ||||
9037 | |||||
9038 | // As an extension, we allow cast to/from void* to function pointer. | ||||
9039 | assert(lhptee->isFunctionType())(static_cast <bool> (lhptee->isFunctionType()) ? void (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9039, __extension__ __PRETTY_FUNCTION__)); | ||||
9040 | return Sema::FunctionVoidPointer; | ||||
9041 | } | ||||
9042 | |||||
9043 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||
9044 | // unqualified versions of compatible types, ... | ||||
9045 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||
9046 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||
9047 | // Check if the pointee types are compatible ignoring the sign. | ||||
9048 | // We explicitly check for char so that we catch "char" vs | ||||
9049 | // "unsigned char" on systems where "char" is unsigned. | ||||
9050 | if (lhptee->isCharType()) | ||||
9051 | ltrans = S.Context.UnsignedCharTy; | ||||
9052 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||
9053 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||
9054 | |||||
9055 | if (rhptee->isCharType()) | ||||
9056 | rtrans = S.Context.UnsignedCharTy; | ||||
9057 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||
9058 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||
9059 | |||||
9060 | if (ltrans == rtrans) { | ||||
9061 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||
9062 | // takes priority over sign incompatibility because the sign | ||||
9063 | // warning can be disabled. | ||||
9064 | if (ConvTy != Sema::Compatible) | ||||
9065 | return ConvTy; | ||||
9066 | |||||
9067 | return Sema::IncompatiblePointerSign; | ||||
9068 | } | ||||
9069 | |||||
9070 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||
9071 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||
9072 | // the eventual target type is the same and the pointers have the same | ||||
9073 | // level of indirection, this must be the issue. | ||||
9074 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||
9075 | do { | ||||
9076 | std::tie(lhptee, lhq) = | ||||
9077 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||
9078 | std::tie(rhptee, rhq) = | ||||
9079 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||
9080 | |||||
9081 | // Inconsistent address spaces at this point is invalid, even if the | ||||
9082 | // address spaces would be compatible. | ||||
9083 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||
9084 | // different nesting levels, like: | ||||
9085 | // __local int *** a; | ||||
9086 | // int ** b = a; | ||||
9087 | // It's not clear how to actually determine when such pointers are | ||||
9088 | // invalidly incompatible. | ||||
9089 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||
9090 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||
9091 | |||||
9092 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||
9093 | |||||
9094 | if (lhptee == rhptee) | ||||
9095 | return Sema::IncompatibleNestedPointerQualifiers; | ||||
9096 | } | ||||
9097 | |||||
9098 | // General pointer incompatibility takes priority over qualifiers. | ||||
9099 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||
9100 | return Sema::IncompatibleFunctionPointer; | ||||
9101 | return Sema::IncompatiblePointer; | ||||
9102 | } | ||||
9103 | if (!S.getLangOpts().CPlusPlus && | ||||
9104 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||
9105 | return Sema::IncompatibleFunctionPointer; | ||||
9106 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||
9107 | return Sema::IncompatibleFunctionPointer; | ||||
9108 | return ConvTy; | ||||
9109 | } | ||||
9110 | |||||
9111 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||
9112 | /// block pointer types are compatible or whether a block and normal pointer | ||||
9113 | /// are compatible. It is more restrict than comparing two function pointer | ||||
9114 | // types. | ||||
9115 | static Sema::AssignConvertType | ||||
9116 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9117 | QualType RHSType) { | ||||
9118 | assert(LHSType.isCanonical() && "LHS not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9118, __extension__ __PRETTY_FUNCTION__)); | ||||
9119 | assert(RHSType.isCanonical() && "RHS not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9119, __extension__ __PRETTY_FUNCTION__)); | ||||
9120 | |||||
9121 | QualType lhptee, rhptee; | ||||
9122 | |||||
9123 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
9124 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||
9125 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||
9126 | |||||
9127 | // In C++, the types have to match exactly. | ||||
9128 | if (S.getLangOpts().CPlusPlus) | ||||
9129 | return Sema::IncompatibleBlockPointer; | ||||
9130 | |||||
9131 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
9132 | |||||
9133 | // For blocks we enforce that qualifiers are identical. | ||||
9134 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||
9135 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||
9136 | if (S.getLangOpts().OpenCL) { | ||||
9137 | LQuals.removeAddressSpace(); | ||||
9138 | RQuals.removeAddressSpace(); | ||||
9139 | } | ||||
9140 | if (LQuals != RQuals) | ||||
9141 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
9142 | |||||
9143 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||
9144 | // assignment. | ||||
9145 | // The current behavior is similar to C++ lambdas. A block might be | ||||
9146 | // assigned to a variable iff its return type and parameters are compatible | ||||
9147 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||
9148 | // an assignment. Presumably it should behave in way that a function pointer | ||||
9149 | // assignment does in C, so for each parameter and return type: | ||||
9150 | // * CVR and address space of LHS should be a superset of CVR and address | ||||
9151 | // space of RHS. | ||||
9152 | // * unqualified types should be compatible. | ||||
9153 | if (S.getLangOpts().OpenCL) { | ||||
9154 | if (!S.Context.typesAreBlockPointerCompatible( | ||||
9155 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||
9156 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||
9157 | return Sema::IncompatibleBlockPointer; | ||||
9158 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||
9159 | return Sema::IncompatibleBlockPointer; | ||||
9160 | |||||
9161 | return ConvTy; | ||||
9162 | } | ||||
9163 | |||||
9164 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||
9165 | /// for assignment compatibility. | ||||
9166 | static Sema::AssignConvertType | ||||
9167 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
9168 | QualType RHSType) { | ||||
9169 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")(static_cast <bool> (LHSType.isCanonical() && "LHS was not canonicalized!" ) ? void (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9169, __extension__ __PRETTY_FUNCTION__)); | ||||
9170 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")(static_cast <bool> (RHSType.isCanonical() && "RHS was not canonicalized!" ) ? void (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9170, __extension__ __PRETTY_FUNCTION__)); | ||||
9171 | |||||
9172 | if (LHSType->isObjCBuiltinType()) { | ||||
9173 | // Class is not compatible with ObjC object pointers. | ||||
9174 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||
9175 | !RHSType->isObjCQualifiedClassType()) | ||||
9176 | return Sema::IncompatiblePointer; | ||||
9177 | return Sema::Compatible; | ||||
9178 | } | ||||
9179 | if (RHSType->isObjCBuiltinType()) { | ||||
9180 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||
9181 | !LHSType->isObjCQualifiedClassType()) | ||||
9182 | return Sema::IncompatiblePointer; | ||||
9183 | return Sema::Compatible; | ||||
9184 | } | ||||
9185 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9186 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
9187 | |||||
9188 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||
9189 | // make an exception for id<P> | ||||
9190 | !LHSType->isObjCQualifiedIdType()) | ||||
9191 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||
9192 | |||||
9193 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||
9194 | return Sema::Compatible; | ||||
9195 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||
9196 | return Sema::IncompatibleObjCQualifiedId; | ||||
9197 | return Sema::IncompatiblePointer; | ||||
9198 | } | ||||
9199 | |||||
9200 | Sema::AssignConvertType | ||||
9201 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||
9202 | QualType LHSType, QualType RHSType) { | ||||
9203 | // Fake up an opaque expression. We don't actually care about what | ||||
9204 | // cast operations are required, so if CheckAssignmentConstraints | ||||
9205 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||
9206 | // usually happen on valid code. | ||||
9207 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); | ||||
9208 | ExprResult RHSPtr = &RHSExpr; | ||||
9209 | CastKind K; | ||||
9210 | |||||
9211 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||
9212 | } | ||||
9213 | |||||
9214 | /// This helper function returns true if QT is a vector type that has element | ||||
9215 | /// type ElementType. | ||||
9216 | static bool isVector(QualType QT, QualType ElementType) { | ||||
9217 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||
9218 | return VT->getElementType().getCanonicalType() == ElementType; | ||||
9219 | return false; | ||||
9220 | } | ||||
9221 | |||||
9222 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||
9223 | /// has code to accommodate several GCC extensions when type checking | ||||
9224 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||
9225 | /// | ||||
9226 | /// int a, *pint; | ||||
9227 | /// short *pshort; | ||||
9228 | /// struct foo *pfoo; | ||||
9229 | /// | ||||
9230 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||
9231 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||
9232 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||
9233 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||
9234 | /// | ||||
9235 | /// As a result, the code for dealing with pointers is more complex than the | ||||
9236 | /// C99 spec dictates. | ||||
9237 | /// | ||||
9238 | /// Sets 'Kind' for any result kind except Incompatible. | ||||
9239 | Sema::AssignConvertType | ||||
9240 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||
9241 | CastKind &Kind, bool ConvertRHS) { | ||||
9242 | QualType RHSType = RHS.get()->getType(); | ||||
9243 | QualType OrigLHSType = LHSType; | ||||
9244 | |||||
9245 | // Get canonical types. We're not formatting these types, just comparing | ||||
9246 | // them. | ||||
9247 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||
9248 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||
9249 | |||||
9250 | // Common case: no conversion required. | ||||
9251 | if (LHSType == RHSType) { | ||||
9252 | Kind = CK_NoOp; | ||||
9253 | return Compatible; | ||||
9254 | } | ||||
9255 | |||||
9256 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||
9257 | // atomic qualification step. | ||||
9258 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | ||||
9259 | Sema::AssignConvertType result = | ||||
9260 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||
9261 | if (result != Compatible) | ||||
9262 | return result; | ||||
9263 | if (Kind != CK_NoOp && ConvertRHS) | ||||
9264 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||
9265 | Kind = CK_NonAtomicToAtomic; | ||||
9266 | return Compatible; | ||||
9267 | } | ||||
9268 | |||||
9269 | // If the left-hand side is a reference type, then we are in a | ||||
9270 | // (rare!) case where we've allowed the use of references in C, | ||||
9271 | // e.g., as a parameter type in a built-in function. In this case, | ||||
9272 | // just make sure that the type referenced is compatible with the | ||||
9273 | // right-hand side type. The caller is responsible for adjusting | ||||
9274 | // LHSType so that the resulting expression does not have reference | ||||
9275 | // type. | ||||
9276 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | ||||
9277 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||
9278 | Kind = CK_LValueBitCast; | ||||
9279 | return Compatible; | ||||
9280 | } | ||||
9281 | return Incompatible; | ||||
9282 | } | ||||
9283 | |||||
9284 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||
9285 | // to the same ExtVector type. | ||||
9286 | if (LHSType->isExtVectorType()) { | ||||
9287 | if (RHSType->isExtVectorType()) | ||||
9288 | return Incompatible; | ||||
9289 | if (RHSType->isArithmeticType()) { | ||||
9290 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||
9291 | if (ConvertRHS) | ||||
9292 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||
9293 | Kind = CK_VectorSplat; | ||||
9294 | return Compatible; | ||||
9295 | } | ||||
9296 | } | ||||
9297 | |||||
9298 | // Conversions to or from vector type. | ||||
9299 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||
9300 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||
9301 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||
9302 | // vector type and vice versa | ||||
9303 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9304 | Kind = CK_BitCast; | ||||
9305 | return Compatible; | ||||
9306 | } | ||||
9307 | |||||
9308 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||
9309 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||
9310 | // no bits are changed but the result type is different. | ||||
9311 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||
9312 | Kind = CK_BitCast; | ||||
9313 | return IncompatibleVectors; | ||||
9314 | } | ||||
9315 | } | ||||
9316 | |||||
9317 | // When the RHS comes from another lax conversion (e.g. binops between | ||||
9318 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||
9319 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||
9320 | // the case where LHS is a scalar. | ||||
9321 | if (LHSType->isScalarType()) { | ||||
9322 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||
9323 | if (VecType && VecType->getNumElements() == 1 && | ||||
9324 | isLaxVectorConversion(RHSType, LHSType)) { | ||||
9325 | ExprResult *VecExpr = &RHS; | ||||
9326 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||
9327 | Kind = CK_BitCast; | ||||
9328 | return Compatible; | ||||
9329 | } | ||||
9330 | } | ||||
9331 | |||||
9332 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||
9333 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||
9334 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | ||||
9335 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | ||||
9336 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | ||||
9337 | Kind = CK_BitCast; | ||||
9338 | return Compatible; | ||||
9339 | } | ||||
9340 | |||||
9341 | return Incompatible; | ||||
9342 | } | ||||
9343 | |||||
9344 | // Diagnose attempts to convert between __float128 and long double where | ||||
9345 | // such conversions currently can't be handled. | ||||
9346 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
9347 | return Incompatible; | ||||
9348 | |||||
9349 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||
9350 | // discards the imaginary part. | ||||
9351 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||
9352 | !LHSType->getAs<ComplexType>()) | ||||
9353 | return Incompatible; | ||||
9354 | |||||
9355 | // Arithmetic conversions. | ||||
9356 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||
9357 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||
9358 | if (ConvertRHS) | ||||
9359 | Kind = PrepareScalarCast(RHS, LHSType); | ||||
9360 | return Compatible; | ||||
9361 | } | ||||
9362 | |||||
9363 | // Conversions to normal pointers. | ||||
9364 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | ||||
9365 | // U* -> T* | ||||
9366 | if (isa<PointerType>(RHSType)) { | ||||
9367 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9368 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||
9369 | if (AddrSpaceL != AddrSpaceR) | ||||
9370 | Kind = CK_AddressSpaceConversion; | ||||
9371 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||
9372 | Kind = CK_NoOp; | ||||
9373 | else | ||||
9374 | Kind = CK_BitCast; | ||||
9375 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9376 | } | ||||
9377 | |||||
9378 | // int -> T* | ||||
9379 | if (RHSType->isIntegerType()) { | ||||
9380 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||
9381 | return IntToPointer; | ||||
9382 | } | ||||
9383 | |||||
9384 | // C pointers are not compatible with ObjC object pointers, | ||||
9385 | // with two exceptions: | ||||
9386 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9387 | // - conversions to void* | ||||
9388 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9389 | Kind = CK_BitCast; | ||||
9390 | return Compatible; | ||||
9391 | } | ||||
9392 | |||||
9393 | // - conversions from 'Class' to the redefinition type | ||||
9394 | if (RHSType->isObjCClassType() && | ||||
9395 | Context.hasSameType(LHSType, | ||||
9396 | Context.getObjCClassRedefinitionType())) { | ||||
9397 | Kind = CK_BitCast; | ||||
9398 | return Compatible; | ||||
9399 | } | ||||
9400 | |||||
9401 | Kind = CK_BitCast; | ||||
9402 | return IncompatiblePointer; | ||||
9403 | } | ||||
9404 | |||||
9405 | // U^ -> void* | ||||
9406 | if (RHSType->getAs<BlockPointerType>()) { | ||||
9407 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9408 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9409 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9410 | ->getPointeeType() | ||||
9411 | .getAddressSpace(); | ||||
9412 | Kind = | ||||
9413 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9414 | return Compatible; | ||||
9415 | } | ||||
9416 | } | ||||
9417 | |||||
9418 | return Incompatible; | ||||
9419 | } | ||||
9420 | |||||
9421 | // Conversions to block pointers. | ||||
9422 | if (isa<BlockPointerType>(LHSType)) { | ||||
9423 | // U^ -> T^ | ||||
9424 | if (RHSType->isBlockPointerType()) { | ||||
9425 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||
9426 | ->getPointeeType() | ||||
9427 | .getAddressSpace(); | ||||
9428 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9429 | ->getPointeeType() | ||||
9430 | .getAddressSpace(); | ||||
9431 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9432 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9433 | } | ||||
9434 | |||||
9435 | // int or null -> T^ | ||||
9436 | if (RHSType->isIntegerType()) { | ||||
9437 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9438 | return IntToBlockPointer; | ||||
9439 | } | ||||
9440 | |||||
9441 | // id -> T^ | ||||
9442 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||
9443 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9444 | return Compatible; | ||||
9445 | } | ||||
9446 | |||||
9447 | // void* -> T^ | ||||
9448 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||
9449 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||
9450 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9451 | return Compatible; | ||||
9452 | } | ||||
9453 | |||||
9454 | return Incompatible; | ||||
9455 | } | ||||
9456 | |||||
9457 | // Conversions to Objective-C pointers. | ||||
9458 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||
9459 | // A* -> B* | ||||
9460 | if (RHSType->isObjCObjectPointerType()) { | ||||
9461 | Kind = CK_BitCast; | ||||
9462 | Sema::AssignConvertType result = | ||||
9463 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9464 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9465 | result == Compatible && | ||||
9466 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||
9467 | result = IncompatibleObjCWeakRef; | ||||
9468 | return result; | ||||
9469 | } | ||||
9470 | |||||
9471 | // int or null -> A* | ||||
9472 | if (RHSType->isIntegerType()) { | ||||
9473 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9474 | return IntToPointer; | ||||
9475 | } | ||||
9476 | |||||
9477 | // In general, C pointers are not compatible with ObjC object pointers, | ||||
9478 | // with two exceptions: | ||||
9479 | if (isa<PointerType>(RHSType)) { | ||||
9480 | Kind = CK_CPointerToObjCPointerCast; | ||||
9481 | |||||
9482 | // - conversions from 'void*' | ||||
9483 | if (RHSType->isVoidPointerType()) { | ||||
9484 | return Compatible; | ||||
9485 | } | ||||
9486 | |||||
9487 | // - conversions to 'Class' from its redefinition type | ||||
9488 | if (LHSType->isObjCClassType() && | ||||
9489 | Context.hasSameType(RHSType, | ||||
9490 | Context.getObjCClassRedefinitionType())) { | ||||
9491 | return Compatible; | ||||
9492 | } | ||||
9493 | |||||
9494 | return IncompatiblePointer; | ||||
9495 | } | ||||
9496 | |||||
9497 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||
9498 | if (RHSType->isBlockPointerType() && | ||||
9499 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
9500 | if (ConvertRHS) | ||||
9501 | maybeExtendBlockObject(RHS); | ||||
9502 | Kind = CK_BlockPointerToObjCPointerCast; | ||||
9503 | return Compatible; | ||||
9504 | } | ||||
9505 | |||||
9506 | return Incompatible; | ||||
9507 | } | ||||
9508 | |||||
9509 | // Conversions from pointers that are not covered by the above. | ||||
9510 | if (isa<PointerType>(RHSType)) { | ||||
9511 | // T* -> _Bool | ||||
9512 | if (LHSType == Context.BoolTy) { | ||||
9513 | Kind = CK_PointerToBoolean; | ||||
9514 | return Compatible; | ||||
9515 | } | ||||
9516 | |||||
9517 | // T* -> int | ||||
9518 | if (LHSType->isIntegerType()) { | ||||
9519 | Kind = CK_PointerToIntegral; | ||||
9520 | return PointerToInt; | ||||
9521 | } | ||||
9522 | |||||
9523 | return Incompatible; | ||||
9524 | } | ||||
9525 | |||||
9526 | // Conversions from Objective-C pointers that are not covered by the above. | ||||
9527 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9528 | // T* -> _Bool | ||||
9529 | if (LHSType == Context.BoolTy) { | ||||
9530 | Kind = CK_PointerToBoolean; | ||||
9531 | return Compatible; | ||||
9532 | } | ||||
9533 | |||||
9534 | // T* -> int | ||||
9535 | if (LHSType->isIntegerType()) { | ||||
9536 | Kind = CK_PointerToIntegral; | ||||
9537 | return PointerToInt; | ||||
9538 | } | ||||
9539 | |||||
9540 | return Incompatible; | ||||
9541 | } | ||||
9542 | |||||
9543 | // struct A -> struct B | ||||
9544 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||
9545 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||
9546 | Kind = CK_NoOp; | ||||
9547 | return Compatible; | ||||
9548 | } | ||||
9549 | } | ||||
9550 | |||||
9551 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||
9552 | Kind = CK_IntToOCLSampler; | ||||
9553 | return Compatible; | ||||
9554 | } | ||||
9555 | |||||
9556 | return Incompatible; | ||||
9557 | } | ||||
9558 | |||||
9559 | /// Constructs a transparent union from an expression that is | ||||
9560 | /// used to initialize the transparent union. | ||||
9561 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||
9562 | ExprResult &EResult, QualType UnionType, | ||||
9563 | FieldDecl *Field) { | ||||
9564 | // Build an initializer list that designates the appropriate member | ||||
9565 | // of the transparent union. | ||||
9566 | Expr *E = EResult.get(); | ||||
9567 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||
9568 | E, SourceLocation()); | ||||
9569 | Initializer->setType(UnionType); | ||||
9570 | Initializer->setInitializedFieldInUnion(Field); | ||||
9571 | |||||
9572 | // Build a compound literal constructing a value of the transparent | ||||
9573 | // union type from this initializer list. | ||||
9574 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||
9575 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||
9576 | VK_PRValue, Initializer, false); | ||||
9577 | } | ||||
9578 | |||||
9579 | Sema::AssignConvertType | ||||
9580 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||
9581 | ExprResult &RHS) { | ||||
9582 | QualType RHSType = RHS.get()->getType(); | ||||
9583 | |||||
9584 | // If the ArgType is a Union type, we want to handle a potential | ||||
9585 | // transparent_union GCC extension. | ||||
9586 | const RecordType *UT = ArgType->getAsUnionType(); | ||||
9587 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||
9588 | return Incompatible; | ||||
9589 | |||||
9590 | // The field to initialize within the transparent union. | ||||
9591 | RecordDecl *UD = UT->getDecl(); | ||||
9592 | FieldDecl *InitField = nullptr; | ||||
9593 | // It's compatible if the expression matches any of the fields. | ||||
9594 | for (auto *it : UD->fields()) { | ||||
9595 | if (it->getType()->isPointerType()) { | ||||
9596 | // If the transparent union contains a pointer type, we allow: | ||||
9597 | // 1) void pointer | ||||
9598 | // 2) null pointer constant | ||||
9599 | if (RHSType->isPointerType()) | ||||
9600 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||
9601 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||
9602 | InitField = it; | ||||
9603 | break; | ||||
9604 | } | ||||
9605 | |||||
9606 | if (RHS.get()->isNullPointerConstant(Context, | ||||
9607 | Expr::NPC_ValueDependentIsNull)) { | ||||
9608 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||
9609 | CK_NullToPointer); | ||||
9610 | InitField = it; | ||||
9611 | break; | ||||
9612 | } | ||||
9613 | } | ||||
9614 | |||||
9615 | CastKind Kind; | ||||
9616 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||
9617 | == Compatible) { | ||||
9618 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||
9619 | InitField = it; | ||||
9620 | break; | ||||
9621 | } | ||||
9622 | } | ||||
9623 | |||||
9624 | if (!InitField) | ||||
9625 | return Incompatible; | ||||
9626 | |||||
9627 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||
9628 | return Compatible; | ||||
9629 | } | ||||
9630 | |||||
9631 | Sema::AssignConvertType | ||||
9632 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||
9633 | bool Diagnose, | ||||
9634 | bool DiagnoseCFAudited, | ||||
9635 | bool ConvertRHS) { | ||||
9636 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||
9637 | // they ask us to issue diagnostics. | ||||
9638 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(static_cast <bool> ((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed") ? void (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9638, __extension__ __PRETTY_FUNCTION__)); | ||||
9639 | |||||
9640 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||
9641 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||
9642 | // to put the updated value. | ||||
9643 | ExprResult LocalRHS = CallerRHS; | ||||
9644 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||
9645 | |||||
9646 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||
9647 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||
9648 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
9649 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
9650 | Diag(RHS.get()->getExprLoc(), | ||||
9651 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
9652 | << RHS.get()->getSourceRange(); | ||||
9653 | } | ||||
9654 | } | ||||
9655 | } | ||||
9656 | |||||
9657 | if (getLangOpts().CPlusPlus) { | ||||
9658 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||
9659 | // C++ 5.17p3: If the left operand is not of class type, the | ||||
9660 | // expression is implicitly converted (C++ 4) to the | ||||
9661 | // cv-unqualified type of the left operand. | ||||
9662 | QualType RHSType = RHS.get()->getType(); | ||||
9663 | if (Diagnose) { | ||||
9664 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9665 | AA_Assigning); | ||||
9666 | } else { | ||||
9667 | ImplicitConversionSequence ICS = | ||||
9668 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9669 | /*SuppressUserConversions=*/false, | ||||
9670 | AllowedExplicit::None, | ||||
9671 | /*InOverloadResolution=*/false, | ||||
9672 | /*CStyle=*/false, | ||||
9673 | /*AllowObjCWritebackConversion=*/false); | ||||
9674 | if (ICS.isFailure()) | ||||
9675 | return Incompatible; | ||||
9676 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9677 | ICS, AA_Assigning); | ||||
9678 | } | ||||
9679 | if (RHS.isInvalid()) | ||||
9680 | return Incompatible; | ||||
9681 | Sema::AssignConvertType result = Compatible; | ||||
9682 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9683 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||
9684 | result = IncompatibleObjCWeakRef; | ||||
9685 | return result; | ||||
9686 | } | ||||
9687 | |||||
9688 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||
9689 | // structures. | ||||
9690 | // FIXME: We also fall through for atomics; not sure what should | ||||
9691 | // happen there, though. | ||||
9692 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||
9693 | // As a set of extensions to C, we support overloading on functions. These | ||||
9694 | // functions need to be resolved here. | ||||
9695 | DeclAccessPair DAP; | ||||
9696 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||
9697 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||
9698 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||
9699 | else | ||||
9700 | return Incompatible; | ||||
9701 | } | ||||
9702 | |||||
9703 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||
9704 | // a null pointer constant. | ||||
9705 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||
9706 | LHSType->isBlockPointerType()) && | ||||
9707 | RHS.get()->isNullPointerConstant(Context, | ||||
9708 | Expr::NPC_ValueDependentIsNull)) { | ||||
9709 | if (Diagnose || ConvertRHS) { | ||||
9710 | CastKind Kind; | ||||
9711 | CXXCastPath Path; | ||||
9712 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||
9713 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||
9714 | if (ConvertRHS) | ||||
9715 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); | ||||
9716 | } | ||||
9717 | return Compatible; | ||||
9718 | } | ||||
9719 | |||||
9720 | // OpenCL queue_t type assignment. | ||||
9721 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||
9722 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||
9723 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
9724 | return Compatible; | ||||
9725 | } | ||||
9726 | |||||
9727 | // This check seems unnatural, however it is necessary to ensure the proper | ||||
9728 | // conversion of functions/arrays. If the conversion were done for all | ||||
9729 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||
9730 | // expressions that suppress this implicit conversion (&, sizeof). | ||||
9731 | // | ||||
9732 | // Suppress this for references: C++ 8.5.3p5. | ||||
9733 | if (!LHSType->isReferenceType()) { | ||||
9734 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||
9735 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||
9736 | if (RHS.isInvalid()) | ||||
9737 | return Incompatible; | ||||
9738 | } | ||||
9739 | CastKind Kind; | ||||
9740 | Sema::AssignConvertType result = | ||||
9741 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||
9742 | |||||
9743 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||
9744 | // type of the assignment expression. | ||||
9745 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||
9746 | // so that we can use references in built-in functions even in C. | ||||
9747 | // The getNonReferenceType() call makes sure that the resulting expression | ||||
9748 | // does not have reference type. | ||||
9749 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||
9750 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||
9751 | Expr *E = RHS.get(); | ||||
9752 | |||||
9753 | // Check for various Objective-C errors. If we are not reporting | ||||
9754 | // diagnostics and just checking for errors, e.g., during overload | ||||
9755 | // resolution, return Incompatible to indicate the failure. | ||||
9756 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9757 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||
9758 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||
9759 | if (!Diagnose) | ||||
9760 | return Incompatible; | ||||
9761 | } | ||||
9762 | if (getLangOpts().ObjC && | ||||
9763 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||
9764 | E->getType(), E, Diagnose) || | ||||
9765 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||
9766 | if (!Diagnose) | ||||
9767 | return Incompatible; | ||||
9768 | // Replace the expression with a corrected version and continue so we | ||||
9769 | // can find further errors. | ||||
9770 | RHS = E; | ||||
9771 | return Compatible; | ||||
9772 | } | ||||
9773 | |||||
9774 | if (ConvertRHS) | ||||
9775 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||
9776 | } | ||||
9777 | |||||
9778 | return result; | ||||
9779 | } | ||||
9780 | |||||
9781 | namespace { | ||||
9782 | /// The original operand to an operator, prior to the application of the usual | ||||
9783 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||
9784 | /// candidate. | ||||
9785 | struct OriginalOperand { | ||||
9786 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||
9787 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||
9788 | Op = MTE->getSubExpr(); | ||||
9789 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||
9790 | Op = BTE->getSubExpr(); | ||||
9791 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||
9792 | Orig = ICE->getSubExprAsWritten(); | ||||
9793 | Conversion = ICE->getConversionFunction(); | ||||
9794 | } | ||||
9795 | } | ||||
9796 | |||||
9797 | QualType getType() const { return Orig->getType(); } | ||||
9798 | |||||
9799 | Expr *Orig; | ||||
9800 | NamedDecl *Conversion; | ||||
9801 | }; | ||||
9802 | } | ||||
9803 | |||||
9804 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9805 | ExprResult &RHS) { | ||||
9806 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||
9807 | |||||
9808 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
9809 | << OrigLHS.getType() << OrigRHS.getType() | ||||
9810 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9811 | |||||
9812 | // If a user-defined conversion was applied to either of the operands prior | ||||
9813 | // to applying the built-in operator rules, tell the user about it. | ||||
9814 | if (OrigLHS.Conversion) { | ||||
9815 | Diag(OrigLHS.Conversion->getLocation(), | ||||
9816 | diag::note_typecheck_invalid_operands_converted) | ||||
9817 | << 0 << LHS.get()->getType(); | ||||
9818 | } | ||||
9819 | if (OrigRHS.Conversion) { | ||||
9820 | Diag(OrigRHS.Conversion->getLocation(), | ||||
9821 | diag::note_typecheck_invalid_operands_converted) | ||||
9822 | << 1 << RHS.get()->getType(); | ||||
9823 | } | ||||
9824 | |||||
9825 | return QualType(); | ||||
9826 | } | ||||
9827 | |||||
9828 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||
9829 | // diagnose the underlying types. Otherwise, diagnose the error | ||||
9830 | // as invalid vector logical operands for non-C++ cases. | ||||
9831 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9832 | ExprResult &RHS) { | ||||
9833 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||
9834 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||
9835 | |||||
9836 | bool LHSNatVec = LHSType->isVectorType(); | ||||
9837 | bool RHSNatVec = RHSType->isVectorType(); | ||||
9838 | |||||
9839 | if (!(LHSNatVec && RHSNatVec)) { | ||||
9840 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||
9841 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||
9842 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9843 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||
9844 | << Vector->getSourceRange(); | ||||
9845 | return QualType(); | ||||
9846 | } | ||||
9847 | |||||
9848 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9849 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
9850 | << RHS.get()->getSourceRange(); | ||||
9851 | |||||
9852 | return QualType(); | ||||
9853 | } | ||||
9854 | |||||
9855 | /// Try to convert a value of non-vector type to a vector type by converting | ||||
9856 | /// the type to the element type of the vector and then performing a splat. | ||||
9857 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||
9858 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||
9859 | /// for float->int. | ||||
9860 | /// | ||||
9861 | /// OpenCL V2.0 6.2.6.p2: | ||||
9862 | /// An error shall occur if any scalar operand type has greater rank | ||||
9863 | /// than the type of the vector element. | ||||
9864 | /// | ||||
9865 | /// \param scalar - if non-null, actually perform the conversions | ||||
9866 | /// \return true if the operation fails (but without diagnosing the failure) | ||||
9867 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||
9868 | QualType scalarTy, | ||||
9869 | QualType vectorEltTy, | ||||
9870 | QualType vectorTy, | ||||
9871 | unsigned &DiagID) { | ||||
9872 | // The conversion to apply to the scalar before splatting it, | ||||
9873 | // if necessary. | ||||
9874 | CastKind scalarCast = CK_NoOp; | ||||
9875 | |||||
9876 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||
9877 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||
9878 | (scalarTy->isIntegerType() && | ||||
9879 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||
9880 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9881 | return true; | ||||
9882 | } | ||||
9883 | if (!scalarTy->isIntegralType(S.Context)) | ||||
9884 | return true; | ||||
9885 | scalarCast = CK_IntegralCast; | ||||
9886 | } else if (vectorEltTy->isRealFloatingType()) { | ||||
9887 | if (scalarTy->isRealFloatingType()) { | ||||
9888 | if (S.getLangOpts().OpenCL && | ||||
9889 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||
9890 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9891 | return true; | ||||
9892 | } | ||||
9893 | scalarCast = CK_FloatingCast; | ||||
9894 | } | ||||
9895 | else if (scalarTy->isIntegralType(S.Context)) | ||||
9896 | scalarCast = CK_IntegralToFloating; | ||||
9897 | else | ||||
9898 | return true; | ||||
9899 | } else { | ||||
9900 | return true; | ||||
9901 | } | ||||
9902 | |||||
9903 | // Adjust scalar if desired. | ||||
9904 | if (scalar) { | ||||
9905 | if (scalarCast != CK_NoOp) | ||||
9906 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||
9907 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||
9908 | } | ||||
9909 | return false; | ||||
9910 | } | ||||
9911 | |||||
9912 | /// Convert vector E to a vector with the same number of elements but different | ||||
9913 | /// element type. | ||||
9914 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||
9915 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||
9916 | assert(VecTy && "Expression E must be a vector")(static_cast <bool> (VecTy && "Expression E must be a vector" ) ? void (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 9916, __extension__ __PRETTY_FUNCTION__)); | ||||
9917 | QualType NewVecTy = S.Context.getVectorType(ElementType, | ||||
9918 | VecTy->getNumElements(), | ||||
9919 | VecTy->getVectorKind()); | ||||
9920 | |||||
9921 | // Look through the implicit cast. Return the subexpression if its type is | ||||
9922 | // NewVecTy. | ||||
9923 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
9924 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||
9925 | return ICE->getSubExpr(); | ||||
9926 | |||||
9927 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||
9928 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||
9929 | } | ||||
9930 | |||||
9931 | /// Test if a (constant) integer Int can be casted to another integer type | ||||
9932 | /// IntTy without losing precision. | ||||
9933 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||
9934 | QualType OtherIntTy) { | ||||
9935 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9936 | |||||
9937 | // Reject cases where the value of the Int is unknown as that would | ||||
9938 | // possibly cause truncation, but accept cases where the scalar can be | ||||
9939 | // demoted without loss of precision. | ||||
9940 | Expr::EvalResult EVResult; | ||||
9941 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9942 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||
9943 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||
9944 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||
9945 | |||||
9946 | if (CstInt) { | ||||
9947 | // If the scalar is constant and is of a higher order and has more active | ||||
9948 | // bits that the vector element type, reject it. | ||||
9949 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9950 | unsigned NumBits = IntSigned | ||||
9951 | ? (Result.isNegative() ? Result.getMinSignedBits() | ||||
9952 | : Result.getActiveBits()) | ||||
9953 | : Result.getActiveBits(); | ||||
9954 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||
9955 | return true; | ||||
9956 | |||||
9957 | // If the signedness of the scalar type and the vector element type | ||||
9958 | // differs and the number of bits is greater than that of the vector | ||||
9959 | // element reject it. | ||||
9960 | return (IntSigned != OtherIntSigned && | ||||
9961 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||
9962 | } | ||||
9963 | |||||
9964 | // Reject cases where the value of the scalar is not constant and it's | ||||
9965 | // order is greater than that of the vector element type. | ||||
9966 | return (Order < 0); | ||||
9967 | } | ||||
9968 | |||||
9969 | /// Test if a (constant) integer Int can be casted to floating point type | ||||
9970 | /// FloatTy without losing precision. | ||||
9971 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||
9972 | QualType FloatTy) { | ||||
9973 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9974 | |||||
9975 | // Determine if the integer constant can be expressed as a floating point | ||||
9976 | // number of the appropriate type. | ||||
9977 | Expr::EvalResult EVResult; | ||||
9978 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9979 | |||||
9980 | uint64_t Bits = 0; | ||||
9981 | if (CstInt) { | ||||
9982 | // Reject constants that would be truncated if they were converted to | ||||
9983 | // the floating point type. Test by simple to/from conversion. | ||||
9984 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||
9985 | // could be avoided if there was a convertFromAPInt method | ||||
9986 | // which could signal back if implicit truncation occurred. | ||||
9987 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9988 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||
9989 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||
9990 | llvm::APFloat::rmTowardZero); | ||||
9991 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||
9992 | !IntTy->hasSignedIntegerRepresentation()); | ||||
9993 | bool Ignored = false; | ||||
9994 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||
9995 | &Ignored); | ||||
9996 | if (Result != ConvertBack) | ||||
9997 | return true; | ||||
9998 | } else { | ||||
9999 | // Reject types that cannot be fully encoded into the mantissa of | ||||
10000 | // the float. | ||||
10001 | Bits = S.Context.getTypeSize(IntTy); | ||||
10002 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||
10003 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||
10004 | if (Bits > FloatPrec) | ||||
10005 | return true; | ||||
10006 | } | ||||
10007 | |||||
10008 | return false; | ||||
10009 | } | ||||
10010 | |||||
10011 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||
10012 | /// Vector following GCC conversion rules. The rule is that implicit | ||||
10013 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||
10014 | /// type without causing truncation of Scalar. | ||||
10015 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||
10016 | ExprResult *Vector) { | ||||
10017 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||
10018 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||
10019 | const VectorType *VT = VectorTy->getAs<VectorType>(); | ||||
10020 | |||||
10021 | assert(!isa<ExtVectorType>(VT) &&(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10022, __extension__ __PRETTY_FUNCTION__)) | ||||
10022 | "ExtVectorTypes should not be handled here!")(static_cast <bool> (!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!") ? void (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10022, __extension__ __PRETTY_FUNCTION__)); | ||||
10023 | |||||
10024 | QualType VectorEltTy = VT->getElementType(); | ||||
10025 | |||||
10026 | // Reject cases where the vector element type or the scalar element type are | ||||
10027 | // not integral or floating point types. | ||||
10028 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||
10029 | return true; | ||||
10030 | |||||
10031 | // The conversion to apply to the scalar before splatting it, | ||||
10032 | // if necessary. | ||||
10033 | CastKind ScalarCast = CK_NoOp; | ||||
10034 | |||||
10035 | // Accept cases where the vector elements are integers and the scalar is | ||||
10036 | // an integer. | ||||
10037 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||
10038 | // integral representation, we could cast it to an appropriate integer | ||||
10039 | // type and then perform the rest of the checks here. GCC will perform | ||||
10040 | // this conversion in some cases as determined by the input language. | ||||
10041 | // We should accept it on a language independent basis. | ||||
10042 | if (VectorEltTy->isIntegralType(S.Context) && | ||||
10043 | ScalarTy->isIntegralType(S.Context) && | ||||
10044 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||
10045 | |||||
10046 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||
10047 | return true; | ||||
10048 | |||||
10049 | ScalarCast = CK_IntegralCast; | ||||
10050 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||
10051 | ScalarTy->isRealFloatingType()) { | ||||
10052 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||
10053 | ScalarCast = CK_FloatingToIntegral; | ||||
10054 | else | ||||
10055 | return true; | ||||
10056 | } else if (VectorEltTy->isRealFloatingType()) { | ||||
10057 | if (ScalarTy->isRealFloatingType()) { | ||||
10058 | |||||
10059 | // Reject cases where the scalar type is not a constant and has a higher | ||||
10060 | // Order than the vector element type. | ||||
10061 | llvm::APFloat Result(0.0); | ||||
10062 | |||||
10063 | // Determine whether this is a constant scalar. In the event that the | ||||
10064 | // value is dependent (and thus cannot be evaluated by the constant | ||||
10065 | // evaluator), skip the evaluation. This will then diagnose once the | ||||
10066 | // expression is instantiated. | ||||
10067 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||
10068 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||
10069 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||
10070 | if (!CstScalar && Order < 0) | ||||
10071 | return true; | ||||
10072 | |||||
10073 | // If the scalar cannot be safely casted to the vector element type, | ||||
10074 | // reject it. | ||||
10075 | if (CstScalar) { | ||||
10076 | bool Truncated = false; | ||||
10077 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||
10078 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||
10079 | if (Truncated) | ||||
10080 | return true; | ||||
10081 | } | ||||
10082 | |||||
10083 | ScalarCast = CK_FloatingCast; | ||||
10084 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||
10085 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||
10086 | return true; | ||||
10087 | |||||
10088 | ScalarCast = CK_IntegralToFloating; | ||||
10089 | } else | ||||
10090 | return true; | ||||
10091 | } else if (ScalarTy->isEnumeralType()) | ||||
10092 | return true; | ||||
10093 | |||||
10094 | // Adjust scalar if desired. | ||||
10095 | if (Scalar) { | ||||
10096 | if (ScalarCast != CK_NoOp) | ||||
10097 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||
10098 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||
10099 | } | ||||
10100 | return false; | ||||
10101 | } | ||||
10102 | |||||
10103 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10104 | SourceLocation Loc, bool IsCompAssign, | ||||
10105 | bool AllowBothBool, | ||||
10106 | bool AllowBoolConversions) { | ||||
10107 | if (!IsCompAssign) { | ||||
10108 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
10109 | if (LHS.isInvalid()) | ||||
10110 | return QualType(); | ||||
10111 | } | ||||
10112 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
10113 | if (RHS.isInvalid()) | ||||
10114 | return QualType(); | ||||
10115 | |||||
10116 | // For conversion purposes, we ignore any qualifiers. | ||||
10117 | // For example, "const float" and "float" are equivalent. | ||||
10118 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
10119 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
10120 | |||||
10121 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||
10122 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||
10123 | assert(LHSVecType || RHSVecType)(static_cast <bool> (LHSVecType || RHSVecType) ? void ( 0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10123, __extension__ __PRETTY_FUNCTION__)); | ||||
10124 | |||||
10125 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||
10126 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||
10127 | return InvalidOperands(Loc, LHS, RHS); | ||||
10128 | |||||
10129 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||
10130 | // for some operators but not others. | ||||
10131 | if (!AllowBothBool && | ||||
10132 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10133 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10134 | return InvalidOperands(Loc, LHS, RHS); | ||||
10135 | |||||
10136 | // If the vector types are identical, return. | ||||
10137 | if (Context.hasSameType(LHSType, RHSType)) | ||||
10138 | return LHSType; | ||||
10139 | |||||
10140 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||
10141 | if (LHSVecType && RHSVecType && | ||||
10142 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
10143 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10144 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10145 | return LHSType; | ||||
10146 | } | ||||
10147 | |||||
10148 | if (!IsCompAssign) | ||||
10149 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10150 | return RHSType; | ||||
10151 | } | ||||
10152 | |||||
10153 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||
10154 | // can be mixed, with the result being the non-bool type. The non-bool | ||||
10155 | // operand must have integer element type. | ||||
10156 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||
10157 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||
10158 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||
10159 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||
10160 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10161 | LHSVecType->getElementType()->isIntegerType() && | ||||
10162 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||
10163 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
10164 | return LHSType; | ||||
10165 | } | ||||
10166 | if (!IsCompAssign && | ||||
10167 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
10168 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
10169 | RHSVecType->getElementType()->isIntegerType()) { | ||||
10170 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
10171 | return RHSType; | ||||
10172 | } | ||||
10173 | } | ||||
10174 | |||||
10175 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||
10176 | // since the ambiguity can affect the ABI. | ||||
10177 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||
10178 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||
10179 | return FirstType->isSizelessBuiltinType() && VecType && | ||||
10180 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||
10181 | VecType->getVectorKind() == | ||||
10182 | VectorType::SveFixedLengthPredicateVector); | ||||
10183 | }; | ||||
10184 | |||||
10185 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||
10186 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||
10187 | return QualType(); | ||||
10188 | } | ||||
10189 | |||||
10190 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||
10191 | // since the ambiguity can affect the ABI. | ||||
10192 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||
10193 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||
10194 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||
10195 | |||||
10196 | if (FirstVecType && SecondVecType) | ||||
10197 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||
10198 | (SecondVecType->getVectorKind() == | ||||
10199 | VectorType::SveFixedLengthDataVector || | ||||
10200 | SecondVecType->getVectorKind() == | ||||
10201 | VectorType::SveFixedLengthPredicateVector); | ||||
10202 | |||||
10203 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||
10204 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||
10205 | }; | ||||
10206 | |||||
10207 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||
10208 | IsSveGnuConversion(RHSType, LHSType)) { | ||||
10209 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||
10210 | return QualType(); | ||||
10211 | } | ||||
10212 | |||||
10213 | // If there's a vector type and a scalar, try to convert the scalar to | ||||
10214 | // the vector element type and splat. | ||||
10215 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||
10216 | if (!RHSVecType) { | ||||
10217 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
10218 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||
10219 | LHSVecType->getElementType(), LHSType, | ||||
10220 | DiagID)) | ||||
10221 | return LHSType; | ||||
10222 | } else { | ||||
10223 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
10224 | return LHSType; | ||||
10225 | } | ||||
10226 | } | ||||
10227 | if (!LHSVecType) { | ||||
10228 | if (isa<ExtVectorType>(RHSVecType)) { | ||||
10229 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||
10230 | LHSType, RHSVecType->getElementType(), | ||||
10231 | RHSType, DiagID)) | ||||
10232 | return RHSType; | ||||
10233 | } else { | ||||
10234 | if (LHS.get()->isLValue() || | ||||
10235 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10236 | return RHSType; | ||||
10237 | } | ||||
10238 | } | ||||
10239 | |||||
10240 | // FIXME: The code below also handles conversion between vectors and | ||||
10241 | // non-scalars, we should break this down into fine grained specific checks | ||||
10242 | // and emit proper diagnostics. | ||||
10243 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||
10244 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||
10245 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||
10246 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||
10247 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||
10248 | // If we're allowing lax vector conversions, only the total (data) size | ||||
10249 | // needs to be the same. For non compound assignment, if one of the types is | ||||
10250 | // scalar, the result is always the vector type. | ||||
10251 | if (!IsCompAssign) { | ||||
10252 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||
10253 | return VecType; | ||||
10254 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||
10255 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||
10256 | // type. Note that this is already done by non-compound assignments in | ||||
10257 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||
10258 | // <1 x T> -> T. The result is also a vector type. | ||||
10259 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||
10260 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||
10261 | ExprResult *RHSExpr = &RHS; | ||||
10262 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||
10263 | return VecType; | ||||
10264 | } | ||||
10265 | } | ||||
10266 | |||||
10267 | // Okay, the expression is invalid. | ||||
10268 | |||||
10269 | // If there's a non-vector, non-real operand, diagnose that. | ||||
10270 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||
10271 | (!LHSVecType && !LHSType->isRealType())) { | ||||
10272 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10273 | << LHSType << RHSType | ||||
10274 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10275 | return QualType(); | ||||
10276 | } | ||||
10277 | |||||
10278 | // OpenCL V1.1 6.2.6.p1: | ||||
10279 | // If the operands are of more than one vector type, then an error shall | ||||
10280 | // occur. Implicit conversions between vector types are not permitted, per | ||||
10281 | // section 6.2.1. | ||||
10282 | if (getLangOpts().OpenCL && | ||||
10283 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||
10284 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||
10285 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||
10286 | << RHSType; | ||||
10287 | return QualType(); | ||||
10288 | } | ||||
10289 | |||||
10290 | |||||
10291 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||
10292 | // this point if scalar could not be converted to the vector's element type | ||||
10293 | // without truncation. | ||||
10294 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||
10295 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||
10296 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||
10297 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||
10298 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||
10299 | Diag(Loc, | ||||
10300 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10301 | << ScalarOrVector << Scalar << Vector; | ||||
10302 | |||||
10303 | return QualType(); | ||||
10304 | } | ||||
10305 | |||||
10306 | // Otherwise, use the generic diagnostic. | ||||
10307 | Diag(Loc, DiagID) | ||||
10308 | << LHSType << RHSType | ||||
10309 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10310 | return QualType(); | ||||
10311 | } | ||||
10312 | |||||
10313 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||
10314 | // expression. These are mainly cases where the null pointer is used as an | ||||
10315 | // integer instead of a pointer. | ||||
10316 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10317 | SourceLocation Loc, bool IsCompare) { | ||||
10318 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||
10319 | // but we use a bit of a hack here for speed; this is a relatively | ||||
10320 | // hot path, and isNullPointerConstant is slow. | ||||
10321 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||
10322 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||
10323 | |||||
10324 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||
10325 | |||||
10326 | // Avoid analyzing cases where the result will either be invalid (and | ||||
10327 | // diagnosed as such) or entirely valid and not something to warn about. | ||||
10328 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||
10329 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||
10330 | return; | ||||
10331 | |||||
10332 | // Comparison operations would not make sense with a null pointer no matter | ||||
10333 | // what the other expression is. | ||||
10334 | if (!IsCompare) { | ||||
10335 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||
10336 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||
10337 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||
10338 | return; | ||||
10339 | } | ||||
10340 | |||||
10341 | // The rest of the operations only make sense with a null pointer | ||||
10342 | // if the other expression is a pointer. | ||||
10343 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||
10344 | NonNullType->canDecayToPointerType()) | ||||
10345 | return; | ||||
10346 | |||||
10347 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||
10348 | << LHSNull /* LHS is NULL */ << NonNullType | ||||
10349 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10350 | } | ||||
10351 | |||||
10352 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||
10353 | SourceLocation Loc) { | ||||
10354 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||
10355 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||
10356 | if (!LUE || !RUE) | ||||
10357 | return; | ||||
10358 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||
10359 | RUE->getKind() != UETT_SizeOf) | ||||
10360 | return; | ||||
10361 | |||||
10362 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||
10363 | QualType LHSTy = LHSArg->getType(); | ||||
10364 | QualType RHSTy; | ||||
10365 | |||||
10366 | if (RUE->isArgumentType()) | ||||
10367 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||
10368 | else | ||||
10369 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||
10370 | |||||
10371 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||
10372 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||
10373 | return; | ||||
10374 | |||||
10375 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||
10376 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10377 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10378 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||
10379 | << LHSArgDecl; | ||||
10380 | } | ||||
10381 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||
10382 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||
10383 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||
10384 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||
10385 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||
10386 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||
10387 | return; | ||||
10388 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||
10389 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||
10390 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10391 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10392 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||
10393 | << LHSArgDecl; | ||||
10394 | } | ||||
10395 | |||||
10396 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||
10397 | } | ||||
10398 | } | ||||
10399 | |||||
10400 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||
10401 | ExprResult &RHS, | ||||
10402 | SourceLocation Loc, bool IsDiv) { | ||||
10403 | // Check for division/remainder by zero. | ||||
10404 | Expr::EvalResult RHSValue; | ||||
10405 | if (!RHS.get()->isValueDependent() && | ||||
10406 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||
10407 | RHSValue.Val.getInt() == 0) | ||||
10408 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10409 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||
10410 | << IsDiv << RHS.get()->getSourceRange()); | ||||
10411 | } | ||||
10412 | |||||
10413 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10414 | SourceLocation Loc, | ||||
10415 | bool IsCompAssign, bool IsDiv) { | ||||
10416 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10417 | |||||
10418 | QualType LHSTy = LHS.get()->getType(); | ||||
10419 | QualType RHSTy = RHS.get()->getType(); | ||||
10420 | if (LHSTy->isVectorType() || RHSTy->isVectorType()) | ||||
10421 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10422 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10423 | /*AllowBoolConversions*/false); | ||||
10424 | if (!IsDiv && | ||||
10425 | (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) | ||||
10426 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10427 | // For division, only matrix-by-scalar is supported. Other combinations with | ||||
10428 | // matrix types are invalid. | ||||
10429 | if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) | ||||
10430 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10431 | |||||
10432 | QualType compType = UsualArithmeticConversions( | ||||
10433 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10434 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10435 | return QualType(); | ||||
10436 | |||||
10437 | |||||
10438 | if (compType.isNull() || !compType->isArithmeticType()) | ||||
10439 | return InvalidOperands(Loc, LHS, RHS); | ||||
10440 | if (IsDiv) { | ||||
10441 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||
10442 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||
10443 | } | ||||
10444 | return compType; | ||||
10445 | } | ||||
10446 | |||||
10447 | QualType Sema::CheckRemainderOperands( | ||||
10448 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||
10449 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10450 | |||||
10451 | if (LHS.get()->getType()->isVectorType() || | ||||
10452 | RHS.get()->getType()->isVectorType()) { | ||||
10453 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
10454 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
10455 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10456 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10457 | /*AllowBoolConversions*/false); | ||||
10458 | return InvalidOperands(Loc, LHS, RHS); | ||||
10459 | } | ||||
10460 | |||||
10461 | QualType compType = UsualArithmeticConversions( | ||||
10462 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10463 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10464 | return QualType(); | ||||
10465 | |||||
10466 | if (compType.isNull() || !compType->isIntegerType()) | ||||
10467 | return InvalidOperands(Loc, LHS, RHS); | ||||
10468 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||
10469 | return compType; | ||||
10470 | } | ||||
10471 | |||||
10472 | /// Diagnose invalid arithmetic on two void pointers. | ||||
10473 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||
10474 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10475 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10476 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10477 | : diag::ext_gnu_void_ptr) | ||||
10478 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||
10479 | << RHSExpr->getSourceRange(); | ||||
10480 | } | ||||
10481 | |||||
10482 | /// Diagnose invalid arithmetic on a void pointer. | ||||
10483 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||
10484 | Expr *Pointer) { | ||||
10485 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10486 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10487 | : diag::ext_gnu_void_ptr) | ||||
10488 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||
10489 | } | ||||
10490 | |||||
10491 | /// Diagnose invalid arithmetic on a null pointer. | ||||
10492 | /// | ||||
10493 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||
10494 | /// idiom, which we recognize as a GNU extension. | ||||
10495 | /// | ||||
10496 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10497 | Expr *Pointer, bool IsGNUIdiom) { | ||||
10498 | if (IsGNUIdiom) | ||||
10499 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||
10500 | << Pointer->getSourceRange(); | ||||
10501 | else | ||||
10502 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||
10503 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
10504 | } | ||||
10505 | |||||
10506 | /// Diagnose invalid subraction on a null pointer. | ||||
10507 | /// | ||||
10508 | static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10509 | Expr *Pointer, bool BothNull) { | ||||
10510 | // Null - null is valid in C++ [expr.add]p7 | ||||
10511 | if (BothNull && S.getLangOpts().CPlusPlus) | ||||
10512 | return; | ||||
10513 | |||||
10514 | // Is this s a macro from a system header? | ||||
10515 | if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) | ||||
10516 | return; | ||||
10517 | |||||
10518 | S.Diag(Loc, diag::warn_pointer_sub_null_ptr) | ||||
10519 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
10520 | } | ||||
10521 | |||||
10522 | /// Diagnose invalid arithmetic on two function pointers. | ||||
10523 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||
10524 | Expr *LHS, Expr *RHS) { | ||||
10525 | assert(LHS->getType()->isAnyPointerType())(static_cast <bool> (LHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10525, __extension__ __PRETTY_FUNCTION__)); | ||||
10526 | assert(RHS->getType()->isAnyPointerType())(static_cast <bool> (RHS->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10526, __extension__ __PRETTY_FUNCTION__)); | ||||
10527 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10528 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10529 | : diag::ext_gnu_ptr_func_arith) | ||||
10530 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||
10531 | // We only show the second type if it differs from the first. | ||||
10532 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||
10533 | RHS->getType()) | ||||
10534 | << RHS->getType()->getPointeeType() | ||||
10535 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||
10536 | } | ||||
10537 | |||||
10538 | /// Diagnose invalid arithmetic on a function pointer. | ||||
10539 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||
10540 | Expr *Pointer) { | ||||
10541 | assert(Pointer->getType()->isAnyPointerType())(static_cast <bool> (Pointer->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10541, __extension__ __PRETTY_FUNCTION__)); | ||||
10542 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10543 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10544 | : diag::ext_gnu_ptr_func_arith) | ||||
10545 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||
10546 | << 0 /* one pointer, so only one type */ | ||||
10547 | << Pointer->getSourceRange(); | ||||
10548 | } | ||||
10549 | |||||
10550 | /// Emit error if Operand is incomplete pointer type | ||||
10551 | /// | ||||
10552 | /// \returns True if pointer has incomplete type | ||||
10553 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||
10554 | Expr *Operand) { | ||||
10555 | QualType ResType = Operand->getType(); | ||||
10556 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10557 | ResType = ResAtomicType->getValueType(); | ||||
10558 | |||||
10559 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())(static_cast <bool> (ResType->isAnyPointerType() && !ResType->isDependentType()) ? void (0) : __assert_fail ( "ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10559, __extension__ __PRETTY_FUNCTION__)); | ||||
10560 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10561 | return S.RequireCompleteSizedType( | ||||
10562 | Loc, PointeeTy, | ||||
10563 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||
10564 | Operand->getSourceRange()); | ||||
10565 | } | ||||
10566 | |||||
10567 | /// Check the validity of an arithmetic pointer operand. | ||||
10568 | /// | ||||
10569 | /// If the operand has pointer type, this code will check for pointer types | ||||
10570 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||
10571 | /// appropriately, including whether or not the use is supported as an | ||||
10572 | /// extension. | ||||
10573 | /// | ||||
10574 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10575 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||
10576 | Expr *Operand) { | ||||
10577 | QualType ResType = Operand->getType(); | ||||
10578 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10579 | ResType = ResAtomicType->getValueType(); | ||||
10580 | |||||
10581 | if (!ResType->isAnyPointerType()) return true; | ||||
10582 | |||||
10583 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10584 | if (PointeeTy->isVoidType()) { | ||||
10585 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||
10586 | return !S.getLangOpts().CPlusPlus; | ||||
10587 | } | ||||
10588 | if (PointeeTy->isFunctionType()) { | ||||
10589 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||
10590 | return !S.getLangOpts().CPlusPlus; | ||||
10591 | } | ||||
10592 | |||||
10593 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||
10594 | |||||
10595 | return true; | ||||
10596 | } | ||||
10597 | |||||
10598 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||
10599 | /// operands. | ||||
10600 | /// | ||||
10601 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||
10602 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||
10603 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||
10604 | /// are (potentially problematic) pointers. | ||||
10605 | /// | ||||
10606 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10607 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||
10608 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10609 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||
10610 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||
10611 | if (!isLHSPointer && !isRHSPointer) return true; | ||||
10612 | |||||
10613 | QualType LHSPointeeTy, RHSPointeeTy; | ||||
10614 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||
10615 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||
10616 | |||||
10617 | // if both are pointers check if operation is valid wrt address spaces | ||||
10618 | if (isLHSPointer && isRHSPointer) { | ||||
10619 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||
10620 | S.Diag(Loc, | ||||
10621 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
10622 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||
10623 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||
10624 | return false; | ||||
10625 | } | ||||
10626 | } | ||||
10627 | |||||
10628 | // Check for arithmetic on pointers to incomplete types. | ||||
10629 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||
10630 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||
10631 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||
10632 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||
10633 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||
10634 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10635 | |||||
10636 | return !S.getLangOpts().CPlusPlus; | ||||
10637 | } | ||||
10638 | |||||
10639 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||
10640 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||
10641 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||
10642 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||
10643 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||
10644 | RHSExpr); | ||||
10645 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10646 | |||||
10647 | return !S.getLangOpts().CPlusPlus; | ||||
10648 | } | ||||
10649 | |||||
10650 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||
10651 | return false; | ||||
10652 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||
10653 | return false; | ||||
10654 | |||||
10655 | return true; | ||||
10656 | } | ||||
10657 | |||||
10658 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||
10659 | /// literal. | ||||
10660 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||
10661 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10662 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10663 | Expr* IndexExpr = RHSExpr; | ||||
10664 | if (!StrExpr) { | ||||
10665 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10666 | IndexExpr = LHSExpr; | ||||
10667 | } | ||||
10668 | |||||
10669 | bool IsStringPlusInt = StrExpr && | ||||
10670 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||
10671 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||
10672 | return; | ||||
10673 | |||||
10674 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10675 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||
10676 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||
10677 | |||||
10678 | // Only print a fixit for "str" + int, not for int + "str". | ||||
10679 | if (IndexExpr == RHSExpr) { | ||||
10680 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10681 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10682 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10683 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10684 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10685 | } else | ||||
10686 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10687 | } | ||||
10688 | |||||
10689 | /// Emit a warning when adding a char literal to a string. | ||||
10690 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||
10691 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10692 | const Expr *StringRefExpr = LHSExpr; | ||||
10693 | const CharacterLiteral *CharExpr = | ||||
10694 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10695 | |||||
10696 | if (!CharExpr) { | ||||
10697 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10698 | StringRefExpr = RHSExpr; | ||||
10699 | } | ||||
10700 | |||||
10701 | if (!CharExpr || !StringRefExpr) | ||||
10702 | return; | ||||
10703 | |||||
10704 | const QualType StringType = StringRefExpr->getType(); | ||||
10705 | |||||
10706 | // Return if not a PointerType. | ||||
10707 | if (!StringType->isAnyPointerType()) | ||||
10708 | return; | ||||
10709 | |||||
10710 | // Return if not a CharacterType. | ||||
10711 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||
10712 | return; | ||||
10713 | |||||
10714 | ASTContext &Ctx = Self.getASTContext(); | ||||
10715 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10716 | |||||
10717 | const QualType CharType = CharExpr->getType(); | ||||
10718 | if (!CharType->isAnyCharacterType() && | ||||
10719 | CharType->isIntegerType() && | ||||
10720 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||
10721 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10722 | << DiagRange << Ctx.CharTy; | ||||
10723 | } else { | ||||
10724 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10725 | << DiagRange << CharExpr->getType(); | ||||
10726 | } | ||||
10727 | |||||
10728 | // Only print a fixit for str + char, not for char + str. | ||||
10729 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||
10730 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10731 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10732 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10733 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10734 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10735 | } else { | ||||
10736 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10737 | } | ||||
10738 | } | ||||
10739 | |||||
10740 | /// Emit error when two pointers are incompatible. | ||||
10741 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||
10742 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10743 | assert(LHSExpr->getType()->isAnyPointerType())(static_cast <bool> (LHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10743, __extension__ __PRETTY_FUNCTION__)); | ||||
10744 | assert(RHSExpr->getType()->isAnyPointerType())(static_cast <bool> (RHSExpr->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10744, __extension__ __PRETTY_FUNCTION__)); | ||||
10745 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||
10746 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||
10747 | << RHSExpr->getSourceRange(); | ||||
10748 | } | ||||
10749 | |||||
10750 | // C99 6.5.6 | ||||
10751 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10752 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10753 | QualType* CompLHSTy) { | ||||
10754 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10755 | |||||
10756 | if (LHS.get()->getType()->isVectorType() || | ||||
10757 | RHS.get()->getType()->isVectorType()) { | ||||
10758 | QualType compType = CheckVectorOperands( | ||||
10759 | LHS, RHS, Loc, CompLHSTy, | ||||
10760 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10761 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10762 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10763 | return compType; | ||||
10764 | } | ||||
10765 | |||||
10766 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10767 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10768 | QualType compType = | ||||
10769 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10770 | if (CompLHSTy) | ||||
10771 | *CompLHSTy = compType; | ||||
10772 | return compType; | ||||
10773 | } | ||||
10774 | |||||
10775 | QualType compType = UsualArithmeticConversions( | ||||
10776 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10777 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10778 | return QualType(); | ||||
10779 | |||||
10780 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||
10781 | if (Opc == BO_Add) { | ||||
10782 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||
10783 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||
10784 | } | ||||
10785 | |||||
10786 | // handle the common case first (both operands are arithmetic). | ||||
10787 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10788 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10789 | return compType; | ||||
10790 | } | ||||
10791 | |||||
10792 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||
10793 | // note that we bias towards the LHS being the pointer. | ||||
10794 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||
10795 | |||||
10796 | bool isObjCPointer; | ||||
10797 | if (PExp->getType()->isPointerType()) { | ||||
10798 | isObjCPointer = false; | ||||
10799 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10800 | isObjCPointer = true; | ||||
10801 | } else { | ||||
10802 | std::swap(PExp, IExp); | ||||
10803 | if (PExp->getType()->isPointerType()) { | ||||
10804 | isObjCPointer = false; | ||||
10805 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10806 | isObjCPointer = true; | ||||
10807 | } else { | ||||
10808 | return InvalidOperands(Loc, LHS, RHS); | ||||
10809 | } | ||||
10810 | } | ||||
10811 | assert(PExp->getType()->isAnyPointerType())(static_cast <bool> (PExp->getType()->isAnyPointerType ()) ? void (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 10811, __extension__ __PRETTY_FUNCTION__)); | ||||
10812 | |||||
10813 | if (!IExp->getType()->isIntegerType()) | ||||
10814 | return InvalidOperands(Loc, LHS, RHS); | ||||
10815 | |||||
10816 | // Adding to a null pointer results in undefined behavior. | ||||
10817 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||
10818 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
10819 | // In C++ adding zero to a null pointer is defined. | ||||
10820 | Expr::EvalResult KnownVal; | ||||
10821 | if (!getLangOpts().CPlusPlus || | ||||
10822 | (!IExp->isValueDependent() && | ||||
10823 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||
10824 | KnownVal.Val.getInt() != 0))) { | ||||
10825 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||
10826 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||
10827 | Context, BO_Add, PExp, IExp); | ||||
10828 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||
10829 | } | ||||
10830 | } | ||||
10831 | |||||
10832 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||
10833 | return QualType(); | ||||
10834 | |||||
10835 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||
10836 | return QualType(); | ||||
10837 | |||||
10838 | // Check array bounds for pointer arithemtic | ||||
10839 | CheckArrayAccess(PExp, IExp); | ||||
10840 | |||||
10841 | if (CompLHSTy) { | ||||
10842 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||
10843 | if (LHSTy.isNull()) { | ||||
10844 | LHSTy = LHS.get()->getType(); | ||||
10845 | if (LHSTy->isPromotableIntegerType()) | ||||
10846 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||
10847 | } | ||||
10848 | *CompLHSTy = LHSTy; | ||||
10849 | } | ||||
10850 | |||||
10851 | return PExp->getType(); | ||||
10852 | } | ||||
10853 | |||||
10854 | // C99 6.5.6 | ||||
10855 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10856 | SourceLocation Loc, | ||||
10857 | QualType* CompLHSTy) { | ||||
10858 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10859 | |||||
10860 | if (LHS.get()->getType()->isVectorType() || | ||||
10861 | RHS.get()->getType()->isVectorType()) { | ||||
10862 | QualType compType = CheckVectorOperands( | ||||
10863 | LHS, RHS, Loc, CompLHSTy, | ||||
10864 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10865 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10866 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10867 | return compType; | ||||
10868 | } | ||||
10869 | |||||
10870 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10871 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10872 | QualType compType = | ||||
10873 | CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10874 | if (CompLHSTy) | ||||
10875 | *CompLHSTy = compType; | ||||
10876 | return compType; | ||||
10877 | } | ||||
10878 | |||||
10879 | QualType compType = UsualArithmeticConversions( | ||||
10880 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10881 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10882 | return QualType(); | ||||
10883 | |||||
10884 | // Enforce type constraints: C99 6.5.6p3. | ||||
10885 | |||||
10886 | // Handle the common case first (both operands are arithmetic). | ||||
10887 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10888 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10889 | return compType; | ||||
10890 | } | ||||
10891 | |||||
10892 | // Either ptr - int or ptr - ptr. | ||||
10893 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||
10894 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||
10895 | |||||
10896 | // Diagnose bad cases where we step over interface counts. | ||||
10897 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||
10898 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||
10899 | return QualType(); | ||||
10900 | |||||
10901 | // The result type of a pointer-int computation is the pointer type. | ||||
10902 | if (RHS.get()->getType()->isIntegerType()) { | ||||
10903 | // Subtracting from a null pointer should produce a warning. | ||||
10904 | // The last argument to the diagnose call says this doesn't match the | ||||
10905 | // GNU int-to-pointer idiom. | ||||
10906 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||
10907 | Expr::NPC_ValueDependentIsNotNull)) { | ||||
10908 | // In C++ adding zero to a null pointer is defined. | ||||
10909 | Expr::EvalResult KnownVal; | ||||
10910 | if (!getLangOpts().CPlusPlus || | ||||
10911 | (!RHS.get()->isValueDependent() && | ||||
10912 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||
10913 | KnownVal.Val.getInt() != 0))) { | ||||
10914 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||
10915 | } | ||||
10916 | } | ||||
10917 | |||||
10918 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||
10919 | return QualType(); | ||||
10920 | |||||
10921 | // Check array bounds for pointer arithemtic | ||||
10922 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||
10923 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||
10924 | |||||
10925 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10926 | return LHS.get()->getType(); | ||||
10927 | } | ||||
10928 | |||||
10929 | // Handle pointer-pointer subtractions. | ||||
10930 | if (const PointerType *RHSPTy | ||||
10931 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||
10932 | QualType rpointee = RHSPTy->getPointeeType(); | ||||
10933 | |||||
10934 | if (getLangOpts().CPlusPlus) { | ||||
10935 | // Pointee types must be the same: C++ [expr.add] | ||||
10936 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||
10937 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10938 | } | ||||
10939 | } else { | ||||
10940 | // Pointee types must be compatible C99 6.5.6p3 | ||||
10941 | if (!Context.typesAreCompatible( | ||||
10942 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||
10943 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||
10944 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10945 | return QualType(); | ||||
10946 | } | ||||
10947 | } | ||||
10948 | |||||
10949 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||
10950 | LHS.get(), RHS.get())) | ||||
10951 | return QualType(); | ||||
10952 | |||||
10953 | bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
10954 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
10955 | bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( | ||||
10956 | Context, Expr::NPC_ValueDependentIsNotNull); | ||||
10957 | |||||
10958 | // Subtracting nullptr or from nullptr is suspect | ||||
10959 | if (LHSIsNullPtr) | ||||
10960 | diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); | ||||
10961 | if (RHSIsNullPtr) | ||||
10962 | diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); | ||||
10963 | |||||
10964 | // The pointee type may have zero size. As an extension, a structure or | ||||
10965 | // union may have zero size or an array may have zero length. In this | ||||
10966 | // case subtraction does not make sense. | ||||
10967 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||
10968 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||
10969 | if (ElementSize.isZero()) { | ||||
10970 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||
10971 | << rpointee.getUnqualifiedType() | ||||
10972 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10973 | } | ||||
10974 | } | ||||
10975 | |||||
10976 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10977 | return Context.getPointerDiffType(); | ||||
10978 | } | ||||
10979 | } | ||||
10980 | |||||
10981 | return InvalidOperands(Loc, LHS, RHS); | ||||
10982 | } | ||||
10983 | |||||
10984 | static bool isScopedEnumerationType(QualType T) { | ||||
10985 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||
10986 | return ET->getDecl()->isScoped(); | ||||
10987 | return false; | ||||
10988 | } | ||||
10989 | |||||
10990 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||
10991 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10992 | QualType LHSType) { | ||||
10993 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||
10994 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||
10995 | if (S.getLangOpts().OpenCL) | ||||
10996 | return; | ||||
10997 | |||||
10998 | // Check right/shifter operand | ||||
10999 | Expr::EvalResult RHSResult; | ||||
11000 | if (RHS.get()->isValueDependent() || | ||||
11001 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||
11002 | return; | ||||
11003 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||
11004 | |||||
11005 | if (Right.isNegative()) { | ||||
11006 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11007 | S.PDiag(diag::warn_shift_negative) | ||||
11008 | << RHS.get()->getSourceRange()); | ||||
11009 | return; | ||||
11010 | } | ||||
11011 | |||||
11012 | QualType LHSExprType = LHS.get()->getType(); | ||||
11013 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||
11014 | if (LHSExprType->isExtIntType()) | ||||
11015 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||
11016 | else if (LHSExprType->isFixedPointType()) { | ||||
11017 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||
11018 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||
11019 | } | ||||
11020 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||
11021 | if (Right.uge(LeftBits)) { | ||||
11022 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
11023 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||
11024 | << RHS.get()->getSourceRange()); | ||||
11025 | return; | ||||
11026 | } | ||||
11027 | |||||
11028 | // FIXME: We probably need to handle fixed point types specially here. | ||||
11029 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||
11030 | return; | ||||
11031 | |||||
11032 | // When left shifting an ICE which is signed, we can check for overflow which | ||||
11033 | // according to C++ standards prior to C++2a has undefined behavior | ||||
11034 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||
11035 | // more than the maximum value representable in the result type, so never | ||||
11036 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||
11037 | // expression is still probably a bug.) | ||||
11038 | Expr::EvalResult LHSResult; | ||||
11039 | if (LHS.get()->isValueDependent() || | ||||
11040 | LHSType->hasUnsignedIntegerRepresentation() || | ||||
11041 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||
11042 | return; | ||||
11043 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||
11044 | |||||
11045 | // If LHS does not have a signed type and non-negative value | ||||
11046 | // then, the behavior is undefined before C++2a. Warn about it. | ||||
11047 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | ||||
11048 | !S.getLangOpts().CPlusPlus20) { | ||||
11049 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||
11050 | S.PDiag(diag::warn_shift_lhs_negative) | ||||
11051 | << LHS.get()->getSourceRange()); | ||||
11052 | return; | ||||
11053 | } | ||||
11054 | |||||
11055 | llvm::APInt ResultBits = | ||||
11056 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | ||||
11057 | if (LeftBits.uge(ResultBits)) | ||||
11058 | return; | ||||
11059 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||
11060 | Result = Result.shl(Right); | ||||
11061 | |||||
11062 | // Print the bit representation of the signed integer as an unsigned | ||||
11063 | // hexadecimal number. | ||||
11064 | SmallString<40> HexResult; | ||||
11065 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||
11066 | |||||
11067 | // If we are only missing a sign bit, this is less likely to result in actual | ||||
11068 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||
11069 | // expected value. Thus we place this behind a different warning that can be | ||||
11070 | // turned off separately if needed. | ||||
11071 | if (LeftBits == ResultBits - 1) { | ||||
11072 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||
11073 | << HexResult << LHSType | ||||
11074 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11075 | return; | ||||
11076 | } | ||||
11077 | |||||
11078 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||
11079 | << HexResult.str() << Result.getMinSignedBits() << LHSType | ||||
11080 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||
11081 | << RHS.get()->getSourceRange(); | ||||
11082 | } | ||||
11083 | |||||
11084 | /// Return the resulting type when a vector is shifted | ||||
11085 | /// by a scalar or vector shift amount. | ||||
11086 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
11087 | SourceLocation Loc, bool IsCompAssign) { | ||||
11088 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||
11089 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||
11090 | !LHS.get()->getType()->isVectorType()) { | ||||
11091 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||
11092 | << RHS.get()->getType() << LHS.get()->getType() | ||||
11093 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11094 | return QualType(); | ||||
11095 | } | ||||
11096 | |||||
11097 | if (!IsCompAssign) { | ||||
11098 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
11099 | if (LHS.isInvalid()) return QualType(); | ||||
11100 | } | ||||
11101 | |||||
11102 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
11103 | if (RHS.isInvalid()) return QualType(); | ||||
11104 | |||||
11105 | QualType LHSType = LHS.get()->getType(); | ||||
11106 | // Note that LHS might be a scalar because the routine calls not only in | ||||
11107 | // OpenCL case. | ||||
11108 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||
11109 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||
11110 | |||||
11111 | // Note that RHS might not be a vector. | ||||
11112 | QualType RHSType = RHS.get()->getType(); | ||||
11113 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||
11114 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||
11115 | |||||
11116 | // The operands need to be integers. | ||||
11117 | if (!LHSEleType->isIntegerType()) { | ||||
11118 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11119 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
11120 | return QualType(); | ||||
11121 | } | ||||
11122 | |||||
11123 | if (!RHSEleType->isIntegerType()) { | ||||
11124 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
11125 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
11126 | return QualType(); | ||||
11127 | } | ||||
11128 | |||||
11129 | if (!LHSVecTy) { | ||||
11130 | assert(RHSVecTy)(static_cast <bool> (RHSVecTy) ? void (0) : __assert_fail ("RHSVecTy", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11130, __extension__ __PRETTY_FUNCTION__)); | ||||
11131 | if (IsCompAssign) | ||||
11132 | return RHSType; | ||||
11133 | if (LHSEleType != RHSEleType) { | ||||
11134 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||
11135 | LHSEleType = RHSEleType; | ||||
11136 | } | ||||
11137 | QualType VecTy = | ||||
11138 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||
11139 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||
11140 | LHSType = VecTy; | ||||
11141 | } else if (RHSVecTy) { | ||||
11142 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||
11143 | // are applied component-wise. So if RHS is a vector, then ensure | ||||
11144 | // that the number of elements is the same as LHS... | ||||
11145 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||
11146 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
11147 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11148 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11149 | return QualType(); | ||||
11150 | } | ||||
11151 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||
11152 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||
11153 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||
11154 | if (LHSBT != RHSBT && | ||||
11155 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||
11156 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||
11157 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11158 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11159 | } | ||||
11160 | } | ||||
11161 | } else { | ||||
11162 | // ...else expand RHS to match the number of elements in LHS. | ||||
11163 | QualType VecTy = | ||||
11164 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||
11165 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
11166 | } | ||||
11167 | |||||
11168 | return LHSType; | ||||
11169 | } | ||||
11170 | |||||
11171 | // C99 6.5.7 | ||||
11172 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11173 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
11174 | bool IsCompAssign) { | ||||
11175 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
11176 | |||||
11177 | // Vector shifts promote their scalar inputs to vector type. | ||||
11178 | if (LHS.get()->getType()->isVectorType() || | ||||
11179 | RHS.get()->getType()->isVectorType()) { | ||||
11180 | if (LangOpts.ZVector) { | ||||
11181 | // The shift operators for the z vector extensions work basically | ||||
11182 | // like general shifts, except that neither the LHS nor the RHS is | ||||
11183 | // allowed to be a "vector bool". | ||||
11184 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||
11185 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11186 | return InvalidOperands(Loc, LHS, RHS); | ||||
11187 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||
11188 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
11189 | return InvalidOperands(Loc, LHS, RHS); | ||||
11190 | } | ||||
11191 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
11192 | } | ||||
11193 | |||||
11194 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||
11195 | // promotions on each operand. C99 6.5.7p3 | ||||
11196 | |||||
11197 | // For the LHS, do usual unary conversions, but then reset them away | ||||
11198 | // if this is a compound assignment. | ||||
11199 | ExprResult OldLHS = LHS; | ||||
11200 | LHS = UsualUnaryConversions(LHS.get()); | ||||
11201 | if (LHS.isInvalid()) | ||||
11202 | return QualType(); | ||||
11203 | QualType LHSType = LHS.get()->getType(); | ||||
11204 | if (IsCompAssign) LHS = OldLHS; | ||||
11205 | |||||
11206 | // The RHS is simpler. | ||||
11207 | RHS = UsualUnaryConversions(RHS.get()); | ||||
11208 | if (RHS.isInvalid()) | ||||
11209 | return QualType(); | ||||
11210 | QualType RHSType = RHS.get()->getType(); | ||||
11211 | |||||
11212 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||
11213 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||
11214 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||
11215 | !LHSType->hasIntegerRepresentation()) || | ||||
11216 | !RHSType->hasIntegerRepresentation()) | ||||
11217 | return InvalidOperands(Loc, LHS, RHS); | ||||
11218 | |||||
11219 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||
11220 | // hasIntegerRepresentation() above instead of this. | ||||
11221 | if (isScopedEnumerationType(LHSType) || | ||||
11222 | isScopedEnumerationType(RHSType)) { | ||||
11223 | return InvalidOperands(Loc, LHS, RHS); | ||||
11224 | } | ||||
11225 | // Sanity-check shift operands | ||||
11226 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||
11227 | |||||
11228 | // "The type of the result is that of the promoted left operand." | ||||
11229 | return LHSType; | ||||
11230 | } | ||||
11231 | |||||
11232 | /// Diagnose bad pointer comparisons. | ||||
11233 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||
11234 | ExprResult &LHS, ExprResult &RHS, | ||||
11235 | bool IsError) { | ||||
11236 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||
11237 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||
11238 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11239 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11240 | } | ||||
11241 | |||||
11242 | /// Returns false if the pointers are converted to a composite type, | ||||
11243 | /// true otherwise. | ||||
11244 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||
11245 | ExprResult &LHS, ExprResult &RHS) { | ||||
11246 | // C++ [expr.rel]p2: | ||||
11247 | // [...] Pointer conversions (4.10) and qualification | ||||
11248 | // conversions (4.4) are performed on pointer operands (or on | ||||
11249 | // a pointer operand and a null pointer constant) to bring | ||||
11250 | // them to their composite pointer type. [...] | ||||
11251 | // | ||||
11252 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||
11253 | // comparisons of pointers. | ||||
11254 | |||||
11255 | QualType LHSType = LHS.get()->getType(); | ||||
11256 | QualType RHSType = RHS.get()->getType(); | ||||
11257 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11258, __extension__ __PRETTY_FUNCTION__)) | ||||
11258 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())(static_cast <bool> (LHSType->isPointerType() || RHSType ->isPointerType() || LHSType->isMemberPointerType() || RHSType ->isMemberPointerType()) ? void (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11258, __extension__ __PRETTY_FUNCTION__)); | ||||
11259 | |||||
11260 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||
11261 | if (T.isNull()) { | ||||
11262 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||
11263 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||
11264 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||
11265 | else | ||||
11266 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11267 | return true; | ||||
11268 | } | ||||
11269 | |||||
11270 | return false; | ||||
11271 | } | ||||
11272 | |||||
11273 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||
11274 | ExprResult &LHS, | ||||
11275 | ExprResult &RHS, | ||||
11276 | bool IsError) { | ||||
11277 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||
11278 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||
11279 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11280 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11281 | } | ||||
11282 | |||||
11283 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||
11284 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||
11285 | case Stmt::ObjCArrayLiteralClass: | ||||
11286 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11287 | case Stmt::ObjCStringLiteralClass: | ||||
11288 | case Stmt::ObjCBoxedExprClass: | ||||
11289 | return true; | ||||
11290 | default: | ||||
11291 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||
11292 | return false; | ||||
11293 | } | ||||
11294 | } | ||||
11295 | |||||
11296 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||
11297 | const ObjCObjectPointerType *Type = | ||||
11298 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||
11299 | |||||
11300 | // If this is not actually an Objective-C object, bail out. | ||||
11301 | if (!Type) | ||||
11302 | return false; | ||||
11303 | |||||
11304 | // Get the LHS object's interface type. | ||||
11305 | QualType InterfaceType = Type->getPointeeType(); | ||||
11306 | |||||
11307 | // If the RHS isn't an Objective-C object, bail out. | ||||
11308 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||
11309 | return false; | ||||
11310 | |||||
11311 | // Try to find the -isEqual: method. | ||||
11312 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||
11313 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||
11314 | InterfaceType, | ||||
11315 | /*IsInstance=*/true); | ||||
11316 | if (!Method) { | ||||
11317 | if (Type->isObjCIdType()) { | ||||
11318 | // For 'id', just check the global pool. | ||||
11319 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||
11320 | /*receiverId=*/true); | ||||
11321 | } else { | ||||
11322 | // Check protocols. | ||||
11323 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||
11324 | /*IsInstance=*/true); | ||||
11325 | } | ||||
11326 | } | ||||
11327 | |||||
11328 | if (!Method) | ||||
11329 | return false; | ||||
11330 | |||||
11331 | QualType T = Method->parameters()[0]->getType(); | ||||
11332 | if (!T->isObjCObjectPointerType()) | ||||
11333 | return false; | ||||
11334 | |||||
11335 | QualType R = Method->getReturnType(); | ||||
11336 | if (!R->isScalarType()) | ||||
11337 | return false; | ||||
11338 | |||||
11339 | return true; | ||||
11340 | } | ||||
11341 | |||||
11342 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||
11343 | FromE = FromE->IgnoreParenImpCasts(); | ||||
11344 | switch (FromE->getStmtClass()) { | ||||
11345 | default: | ||||
11346 | break; | ||||
11347 | case Stmt::ObjCStringLiteralClass: | ||||
11348 | // "string literal" | ||||
11349 | return LK_String; | ||||
11350 | case Stmt::ObjCArrayLiteralClass: | ||||
11351 | // "array literal" | ||||
11352 | return LK_Array; | ||||
11353 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11354 | // "dictionary literal" | ||||
11355 | return LK_Dictionary; | ||||
11356 | case Stmt::BlockExprClass: | ||||
11357 | return LK_Block; | ||||
11358 | case Stmt::ObjCBoxedExprClass: { | ||||
11359 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||
11360 | switch (Inner->getStmtClass()) { | ||||
11361 | case Stmt::IntegerLiteralClass: | ||||
11362 | case Stmt::FloatingLiteralClass: | ||||
11363 | case Stmt::CharacterLiteralClass: | ||||
11364 | case Stmt::ObjCBoolLiteralExprClass: | ||||
11365 | case Stmt::CXXBoolLiteralExprClass: | ||||
11366 | // "numeric literal" | ||||
11367 | return LK_Numeric; | ||||
11368 | case Stmt::ImplicitCastExprClass: { | ||||
11369 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||
11370 | // Boolean literals can be represented by implicit casts. | ||||
11371 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||
11372 | return LK_Numeric; | ||||
11373 | break; | ||||
11374 | } | ||||
11375 | default: | ||||
11376 | break; | ||||
11377 | } | ||||
11378 | return LK_Boxed; | ||||
11379 | } | ||||
11380 | } | ||||
11381 | return LK_None; | ||||
11382 | } | ||||
11383 | |||||
11384 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||
11385 | ExprResult &LHS, ExprResult &RHS, | ||||
11386 | BinaryOperator::Opcode Opc){ | ||||
11387 | Expr *Literal; | ||||
11388 | Expr *Other; | ||||
11389 | if (isObjCObjectLiteral(LHS)) { | ||||
11390 | Literal = LHS.get(); | ||||
11391 | Other = RHS.get(); | ||||
11392 | } else { | ||||
11393 | Literal = RHS.get(); | ||||
11394 | Other = LHS.get(); | ||||
11395 | } | ||||
11396 | |||||
11397 | // Don't warn on comparisons against nil. | ||||
11398 | Other = Other->IgnoreParenCasts(); | ||||
11399 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||
11400 | Expr::NPC_ValueDependentIsNotNull)) | ||||
11401 | return; | ||||
11402 | |||||
11403 | // This should be kept in sync with warn_objc_literal_comparison. | ||||
11404 | // LK_String should always be after the other literals, since it has its own | ||||
11405 | // warning flag. | ||||
11406 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||
11407 | assert(LiteralKind != Sema::LK_Block)(static_cast <bool> (LiteralKind != Sema::LK_Block) ? void (0) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11407, __extension__ __PRETTY_FUNCTION__)); | ||||
11408 | if (LiteralKind == Sema::LK_None) { | ||||
11409 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11409); | ||||
11410 | } | ||||
11411 | |||||
11412 | if (LiteralKind == Sema::LK_String) | ||||
11413 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||
11414 | << Literal->getSourceRange(); | ||||
11415 | else | ||||
11416 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||
11417 | << LiteralKind << Literal->getSourceRange(); | ||||
11418 | |||||
11419 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
11420 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||
11421 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||
11422 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
11423 | CharSourceRange OpRange = | ||||
11424 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
11425 | |||||
11426 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||
11427 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||
11428 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||
11429 | << FixItHint::CreateInsertion(End, "]"); | ||||
11430 | } | ||||
11431 | } | ||||
11432 | |||||
11433 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||
11434 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||
11435 | ExprResult &RHS, SourceLocation Loc, | ||||
11436 | BinaryOperatorKind Opc) { | ||||
11437 | // Check that left hand side is !something. | ||||
11438 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||
11439 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||
11440 | |||||
11441 | // Only check if the right hand side is non-bool arithmetic type. | ||||
11442 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||
11443 | |||||
11444 | // Make sure that the something in !something is not bool. | ||||
11445 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||
11446 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||
11447 | |||||
11448 | // Emit warning. | ||||
11449 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||
11450 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||
11451 | << Loc << IsBitwiseOp; | ||||
11452 | |||||
11453 | // First note suggest !(x < y) | ||||
11454 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||
11455 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||
11456 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||
11457 | if (FirstClose.isInvalid()) | ||||
11458 | FirstOpen = SourceLocation(); | ||||
11459 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||
11460 | << IsBitwiseOp | ||||
11461 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||
11462 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||
11463 | |||||
11464 | // Second note suggests (!x) < y | ||||
11465 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||
11466 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||
11467 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||
11468 | if (SecondClose.isInvalid()) | ||||
11469 | SecondOpen = SourceLocation(); | ||||
11470 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||
11471 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||
11472 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||
11473 | } | ||||
11474 | |||||
11475 | // Returns true if E refers to a non-weak array. | ||||
11476 | static bool checkForArray(const Expr *E) { | ||||
11477 | const ValueDecl *D = nullptr; | ||||
11478 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||
11479 | D = DR->getDecl(); | ||||
11480 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||
11481 | if (Mem->isImplicitAccess()) | ||||
11482 | D = Mem->getMemberDecl(); | ||||
11483 | } | ||||
11484 | if (!D) | ||||
11485 | return false; | ||||
11486 | return D->getType()->isArrayType() && !D->isWeak(); | ||||
11487 | } | ||||
11488 | |||||
11489 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||
11490 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||
11491 | Expr *LHS, Expr *RHS, | ||||
11492 | BinaryOperatorKind Opc) { | ||||
11493 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||
11494 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||
11495 | |||||
11496 | QualType LHSType = LHS->getType(); | ||||
11497 | QualType RHSType = RHS->getType(); | ||||
11498 | if (LHSType->hasFloatingRepresentation() || | ||||
11499 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||
11500 | S.inTemplateInstantiation()) | ||||
11501 | return; | ||||
11502 | |||||
11503 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||
11504 | // we shouldn't emit any additional warnings about it. | ||||
11505 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||
11506 | return; | ||||
11507 | |||||
11508 | // For non-floating point types, check for self-comparisons of the form | ||||
11509 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
11510 | // often indicate logic errors in the program. | ||||
11511 | // | ||||
11512 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||
11513 | // expansion. Also don't warn about comparisons which are only self | ||||
11514 | // comparisons within a template instantiation. The warnings should catch | ||||
11515 | // obvious cases in the definition of the template anyways. The idea is to | ||||
11516 | // warn when the typed comparison operator will always evaluate to the same | ||||
11517 | // result. | ||||
11518 | |||||
11519 | // Used for indexing into %select in warn_comparison_always | ||||
11520 | enum { | ||||
11521 | AlwaysConstant, | ||||
11522 | AlwaysTrue, | ||||
11523 | AlwaysFalse, | ||||
11524 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||
11525 | }; | ||||
11526 | |||||
11527 | // C++2a [depr.array.comp]: | ||||
11528 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||
11529 | // operands of array type are deprecated. | ||||
11530 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||
11531 | RHSStripped->getType()->isArrayType()) { | ||||
11532 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||
11533 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
11534 | << LHSStripped->getType() << RHSStripped->getType(); | ||||
11535 | // Carry on to produce the tautological comparison warning, if this | ||||
11536 | // expression is potentially-evaluated, we can resolve the array to a | ||||
11537 | // non-weak declaration, and so on. | ||||
11538 | } | ||||
11539 | |||||
11540 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||
11541 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||
11542 | unsigned Result; | ||||
11543 | switch (Opc) { | ||||
11544 | case BO_EQ: | ||||
11545 | case BO_LE: | ||||
11546 | case BO_GE: | ||||
11547 | Result = AlwaysTrue; | ||||
11548 | break; | ||||
11549 | case BO_NE: | ||||
11550 | case BO_LT: | ||||
11551 | case BO_GT: | ||||
11552 | Result = AlwaysFalse; | ||||
11553 | break; | ||||
11554 | case BO_Cmp: | ||||
11555 | Result = AlwaysEqual; | ||||
11556 | break; | ||||
11557 | default: | ||||
11558 | Result = AlwaysConstant; | ||||
11559 | break; | ||||
11560 | } | ||||
11561 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11562 | S.PDiag(diag::warn_comparison_always) | ||||
11563 | << 0 /*self-comparison*/ | ||||
11564 | << Result); | ||||
11565 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||
11566 | // What is it always going to evaluate to? | ||||
11567 | unsigned Result; | ||||
11568 | switch (Opc) { | ||||
11569 | case BO_EQ: // e.g. array1 == array2 | ||||
11570 | Result = AlwaysFalse; | ||||
11571 | break; | ||||
11572 | case BO_NE: // e.g. array1 != array2 | ||||
11573 | Result = AlwaysTrue; | ||||
11574 | break; | ||||
11575 | default: // e.g. array1 <= array2 | ||||
11576 | // The best we can say is 'a constant' | ||||
11577 | Result = AlwaysConstant; | ||||
11578 | break; | ||||
11579 | } | ||||
11580 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11581 | S.PDiag(diag::warn_comparison_always) | ||||
11582 | << 1 /*array comparison*/ | ||||
11583 | << Result); | ||||
11584 | } | ||||
11585 | } | ||||
11586 | |||||
11587 | if (isa<CastExpr>(LHSStripped)) | ||||
11588 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||
11589 | if (isa<CastExpr>(RHSStripped)) | ||||
11590 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||
11591 | |||||
11592 | // Warn about comparisons against a string constant (unless the other | ||||
11593 | // operand is null); the user probably wants string comparison function. | ||||
11594 | Expr *LiteralString = nullptr; | ||||
11595 | Expr *LiteralStringStripped = nullptr; | ||||
11596 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||
11597 | !RHSStripped->isNullPointerConstant(S.Context, | ||||
11598 | Expr::NPC_ValueDependentIsNull)) { | ||||
11599 | LiteralString = LHS; | ||||
11600 | LiteralStringStripped = LHSStripped; | ||||
11601 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||
11602 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||
11603 | !LHSStripped->isNullPointerConstant(S.Context, | ||||
11604 | Expr::NPC_ValueDependentIsNull)) { | ||||
11605 | LiteralString = RHS; | ||||
11606 | LiteralStringStripped = RHSStripped; | ||||
11607 | } | ||||
11608 | |||||
11609 | if (LiteralString) { | ||||
11610 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11611 | S.PDiag(diag::warn_stringcompare) | ||||
11612 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||
11613 | << LiteralString->getSourceRange()); | ||||
11614 | } | ||||
11615 | } | ||||
11616 | |||||
11617 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||
11618 | switch (CK) { | ||||
11619 | default: { | ||||
11620 | #ifndef NDEBUG | ||||
11621 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||
11622 | << "\n"; | ||||
11623 | #endif | ||||
11624 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11624); | ||||
11625 | } | ||||
11626 | case CK_UserDefinedConversion: | ||||
11627 | return ICK_Identity; | ||||
11628 | case CK_LValueToRValue: | ||||
11629 | return ICK_Lvalue_To_Rvalue; | ||||
11630 | case CK_ArrayToPointerDecay: | ||||
11631 | return ICK_Array_To_Pointer; | ||||
11632 | case CK_FunctionToPointerDecay: | ||||
11633 | return ICK_Function_To_Pointer; | ||||
11634 | case CK_IntegralCast: | ||||
11635 | return ICK_Integral_Conversion; | ||||
11636 | case CK_FloatingCast: | ||||
11637 | return ICK_Floating_Conversion; | ||||
11638 | case CK_IntegralToFloating: | ||||
11639 | case CK_FloatingToIntegral: | ||||
11640 | return ICK_Floating_Integral; | ||||
11641 | case CK_IntegralComplexCast: | ||||
11642 | case CK_FloatingComplexCast: | ||||
11643 | case CK_FloatingComplexToIntegralComplex: | ||||
11644 | case CK_IntegralComplexToFloatingComplex: | ||||
11645 | return ICK_Complex_Conversion; | ||||
11646 | case CK_FloatingComplexToReal: | ||||
11647 | case CK_FloatingRealToComplex: | ||||
11648 | case CK_IntegralComplexToReal: | ||||
11649 | case CK_IntegralRealToComplex: | ||||
11650 | return ICK_Complex_Real; | ||||
11651 | } | ||||
11652 | } | ||||
11653 | |||||
11654 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||
11655 | QualType FromType, | ||||
11656 | SourceLocation Loc) { | ||||
11657 | // Check for a narrowing implicit conversion. | ||||
11658 | StandardConversionSequence SCS; | ||||
11659 | SCS.setAsIdentityConversion(); | ||||
11660 | SCS.setToType(0, FromType); | ||||
11661 | SCS.setToType(1, ToType); | ||||
11662 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
11663 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||
11664 | |||||
11665 | APValue PreNarrowingValue; | ||||
11666 | QualType PreNarrowingType; | ||||
11667 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||
11668 | PreNarrowingType, | ||||
11669 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||
11670 | case NK_Dependent_Narrowing: | ||||
11671 | // Implicit conversion to a narrower type, but the expression is | ||||
11672 | // value-dependent so we can't tell whether it's actually narrowing. | ||||
11673 | case NK_Not_Narrowing: | ||||
11674 | return false; | ||||
11675 | |||||
11676 | case NK_Constant_Narrowing: | ||||
11677 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11678 | // expression. | ||||
11679 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11680 | << /*Constant*/ 1 | ||||
11681 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||
11682 | return true; | ||||
11683 | |||||
11684 | case NK_Variable_Narrowing: | ||||
11685 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11686 | // expression. | ||||
11687 | case NK_Type_Narrowing: | ||||
11688 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11689 | << /*Constant*/ 0 << FromType << ToType; | ||||
11690 | // TODO: It's not a constant expression, but what if the user intended it | ||||
11691 | // to be? Can we produce notes to help them figure out why it isn't? | ||||
11692 | return true; | ||||
11693 | } | ||||
11694 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11694); | ||||
11695 | } | ||||
11696 | |||||
11697 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||
11698 | ExprResult &LHS, | ||||
11699 | ExprResult &RHS, | ||||
11700 | SourceLocation Loc) { | ||||
11701 | QualType LHSType = LHS.get()->getType(); | ||||
11702 | QualType RHSType = RHS.get()->getType(); | ||||
11703 | // Dig out the original argument type and expression before implicit casts | ||||
11704 | // were applied. These are the types/expressions we need to check the | ||||
11705 | // [expr.spaceship] requirements against. | ||||
11706 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||
11707 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||
11708 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||
11709 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||
11710 | |||||
11711 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||
11712 | // other is not, the program is ill-formed. | ||||
11713 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||
11714 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11715 | return QualType(); | ||||
11716 | } | ||||
11717 | |||||
11718 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||
11719 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||
11720 | RHSStrippedType->isEnumeralType(); | ||||
11721 | if (NumEnumArgs == 1) { | ||||
11722 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||
11723 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||
11724 | if (OtherTy->hasFloatingRepresentation()) { | ||||
11725 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11726 | return QualType(); | ||||
11727 | } | ||||
11728 | } | ||||
11729 | if (NumEnumArgs == 2) { | ||||
11730 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||
11731 | // type E, the operator yields the result of converting the operands | ||||
11732 | // to the underlying type of E and applying <=> to the converted operands. | ||||
11733 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||
11734 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11735 | return QualType(); | ||||
11736 | } | ||||
11737 | QualType IntType = | ||||
11738 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||
11739 | assert(IntType->isArithmeticType())(static_cast <bool> (IntType->isArithmeticType()) ? void (0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11739, __extension__ __PRETTY_FUNCTION__)); | ||||
11740 | |||||
11741 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||
11742 | // promote the boolean type, and all other promotable integer types, to | ||||
11743 | // avoid this. | ||||
11744 | if (IntType->isPromotableIntegerType()) | ||||
11745 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||
11746 | |||||
11747 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||
11748 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||
11749 | LHSType = RHSType = IntType; | ||||
11750 | } | ||||
11751 | |||||
11752 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||
11753 | // usual arithmetic conversions are applied to the operands. | ||||
11754 | QualType Type = | ||||
11755 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11756 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11757 | return QualType(); | ||||
11758 | if (Type.isNull()) | ||||
11759 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11760 | |||||
11761 | Optional<ComparisonCategoryType> CCT = | ||||
11762 | getComparisonCategoryForBuiltinCmp(Type); | ||||
11763 | if (!CCT) | ||||
11764 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11765 | |||||
11766 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||
11767 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||
11768 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||
11769 | RHS.get()->getBeginLoc()); | ||||
11770 | if (HasNarrowing) | ||||
11771 | return QualType(); | ||||
11772 | |||||
11773 | assert(!Type.isNull() && "composite type for <=> has not been set")(static_cast <bool> (!Type.isNull() && "composite type for <=> has not been set" ) ? void (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11773, __extension__ __PRETTY_FUNCTION__)); | ||||
11774 | |||||
11775 | return S.CheckComparisonCategoryType( | ||||
11776 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||
11777 | } | ||||
11778 | |||||
11779 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||
11780 | ExprResult &RHS, | ||||
11781 | SourceLocation Loc, | ||||
11782 | BinaryOperatorKind Opc) { | ||||
11783 | if (Opc == BO_Cmp) | ||||
11784 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||
11785 | |||||
11786 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||
11787 | QualType Type = | ||||
11788 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11789 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11790 | return QualType(); | ||||
11791 | if (Type.isNull()) | ||||
11792 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11793 | assert(Type->isArithmeticType() || Type->isEnumeralType())(static_cast <bool> (Type->isArithmeticType() || Type ->isEnumeralType()) ? void (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11793, __extension__ __PRETTY_FUNCTION__)); | ||||
11794 | |||||
11795 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||
11796 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11797 | |||||
11798 | // Check for comparisons of floating point operands using != and ==. | ||||
11799 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | ||||
11800 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
11801 | |||||
11802 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||
11803 | return S.Context.getLogicalOperationType(); | ||||
11804 | } | ||||
11805 | |||||
11806 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||
11807 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||
11808 | return; | ||||
11809 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||
11810 | if (!E.get()->getType()->isAnyPointerType() && | ||||
11811 | E.get()->isNullPointerConstant(Context, | ||||
11812 | Expr::NPC_ValueDependentIsNotNull) == | ||||
11813 | Expr::NPCK_ZeroExpression) { | ||||
11814 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||
11815 | if (CL->getValue() == 0) | ||||
11816 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11817 | << NullValue | ||||
11818 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11819 | NullValue ? "NULL" : "(void *)0"); | ||||
11820 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||
11821 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||
11822 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||
11823 | if (T == Context.CharTy) | ||||
11824 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11825 | << NullValue | ||||
11826 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11827 | NullValue ? "NULL" : "(void *)0"); | ||||
11828 | } | ||||
11829 | } | ||||
11830 | } | ||||
11831 | |||||
11832 | // C99 6.5.8, C++ [expr.rel] | ||||
11833 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11834 | SourceLocation Loc, | ||||
11835 | BinaryOperatorKind Opc) { | ||||
11836 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||
11837 | bool IsThreeWay = Opc == BO_Cmp; | ||||
11838 | bool IsOrdered = IsRelational || IsThreeWay; | ||||
11839 | auto IsAnyPointerType = [](ExprResult E) { | ||||
11840 | QualType Ty = E.get()->getType(); | ||||
11841 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||
11842 | }; | ||||
11843 | |||||
11844 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||
11845 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||
11846 | // bring them to their composite type. | ||||
11847 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||
11848 | // any type-related checks. | ||||
11849 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||
11850 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
11851 | if (LHS.isInvalid()) | ||||
11852 | return QualType(); | ||||
11853 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
11854 | if (RHS.isInvalid()) | ||||
11855 | return QualType(); | ||||
11856 | } else { | ||||
11857 | LHS = DefaultLvalueConversion(LHS.get()); | ||||
11858 | if (LHS.isInvalid()) | ||||
11859 | return QualType(); | ||||
11860 | RHS = DefaultLvalueConversion(RHS.get()); | ||||
11861 | if (RHS.isInvalid()) | ||||
11862 | return QualType(); | ||||
11863 | } | ||||
11864 | |||||
11865 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||
11866 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||
11867 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||
11868 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||
11869 | } | ||||
11870 | |||||
11871 | // Handle vector comparisons separately. | ||||
11872 | if (LHS.get()->getType()->isVectorType() || | ||||
11873 | RHS.get()->getType()->isVectorType()) | ||||
11874 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
11875 | |||||
11876 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
11877 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
11878 | |||||
11879 | QualType LHSType = LHS.get()->getType(); | ||||
11880 | QualType RHSType = RHS.get()->getType(); | ||||
11881 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||
11882 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||
11883 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||
11884 | |||||
11885 | const Expr::NullPointerConstantKind LHSNullKind = | ||||
11886 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11887 | const Expr::NullPointerConstantKind RHSNullKind = | ||||
11888 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11889 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||
11890 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||
11891 | |||||
11892 | auto computeResultTy = [&]() { | ||||
11893 | if (Opc != BO_Cmp) | ||||
11894 | return Context.getLogicalOperationType(); | ||||
11895 | assert(getLangOpts().CPlusPlus)(static_cast <bool> (getLangOpts().CPlusPlus) ? void (0 ) : __assert_fail ("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11895, __extension__ __PRETTY_FUNCTION__)); | ||||
11896 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))(static_cast <bool> (Context.hasSameType(LHS.get()-> getType(), RHS.get()->getType())) ? void (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11896, __extension__ __PRETTY_FUNCTION__)); | ||||
11897 | |||||
11898 | QualType CompositeTy = LHS.get()->getType(); | ||||
11899 | assert(!CompositeTy->isReferenceType())(static_cast <bool> (!CompositeTy->isReferenceType() ) ? void (0) : __assert_fail ("!CompositeTy->isReferenceType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 11899, __extension__ __PRETTY_FUNCTION__)); | ||||
11900 | |||||
11901 | Optional<ComparisonCategoryType> CCT = | ||||
11902 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||
11903 | if (!CCT) | ||||
11904 | return InvalidOperands(Loc, LHS, RHS); | ||||
11905 | |||||
11906 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||
11907 | // P0946R0: Comparisons between a null pointer constant and an object | ||||
11908 | // pointer result in std::strong_equality, which is ill-formed under | ||||
11909 | // P1959R0. | ||||
11910 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||
11911 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||
11912 | : RHS.get()->getSourceRange()); | ||||
11913 | return QualType(); | ||||
11914 | } | ||||
11915 | |||||
11916 | return CheckComparisonCategoryType( | ||||
11917 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||
11918 | }; | ||||
11919 | |||||
11920 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||
11921 | bool IsEquality = Opc == BO_EQ; | ||||
11922 | if (RHSIsNull) | ||||
11923 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||
11924 | RHS.get()->getSourceRange()); | ||||
11925 | else | ||||
11926 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||
11927 | LHS.get()->getSourceRange()); | ||||
11928 | } | ||||
11929 | |||||
11930 | if (IsOrdered && LHSType->isFunctionPointerType() && | ||||
11931 | RHSType->isFunctionPointerType()) { | ||||
11932 | // Valid unless a relational comparison of function pointers | ||||
11933 | bool IsError = Opc == BO_Cmp; | ||||
11934 | auto DiagID = | ||||
11935 | IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers | ||||
11936 | : getLangOpts().CPlusPlus | ||||
11937 | ? diag::warn_typecheck_ordered_comparison_of_function_pointers | ||||
11938 | : diag::ext_typecheck_ordered_comparison_of_function_pointers; | ||||
11939 | Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11940 | << RHS.get()->getSourceRange(); | ||||
11941 | if (IsError) | ||||
11942 | return QualType(); | ||||
11943 | } | ||||
11944 | |||||
11945 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||
11946 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||
11947 | // Skip normal pointer conversion checks in this case; we have better | ||||
11948 | // diagnostics for this below. | ||||
11949 | } else if (getLangOpts().CPlusPlus) { | ||||
11950 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||
11951 | // but we allow it as an extension. | ||||
11952 | // FIXME: If we really want to allow this, should it be part of composite | ||||
11953 | // pointer type computation so it works in conditionals too? | ||||
11954 | if (!IsOrdered && | ||||
11955 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||
11956 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||
11957 | // This is a gcc extension compatibility comparison. | ||||
11958 | // In a SFINAE context, we treat this as a hard error to maintain | ||||
11959 | // conformance with the C++ standard. | ||||
11960 | diagnoseFunctionPointerToVoidComparison( | ||||
11961 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||
11962 | |||||
11963 | if (isSFINAEContext()) | ||||
11964 | return QualType(); | ||||
11965 | |||||
11966 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11967 | return computeResultTy(); | ||||
11968 | } | ||||
11969 | |||||
11970 | // C++ [expr.eq]p2: | ||||
11971 | // If at least one operand is a pointer [...] bring them to their | ||||
11972 | // composite pointer type. | ||||
11973 | // C++ [expr.spaceship]p6 | ||||
11974 | // If at least one of the operands is of pointer type, [...] bring them | ||||
11975 | // to their composite pointer type. | ||||
11976 | // C++ [expr.rel]p2: | ||||
11977 | // If both operands are pointers, [...] bring them to their composite | ||||
11978 | // pointer type. | ||||
11979 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||
11980 | // we already decayed those, so this is really the same as the relational | ||||
11981 | // comparison rule. | ||||
11982 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||
11983 | (IsOrdered ? 2 : 1) && | ||||
11984 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||
11985 | RHSType->isObjCObjectPointerType()))) { | ||||
11986 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
11987 | return QualType(); | ||||
11988 | return computeResultTy(); | ||||
11989 | } | ||||
11990 | } else if (LHSType->isPointerType() && | ||||
11991 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||
11992 | // All of the following pointer-related warnings are GCC extensions, except | ||||
11993 | // when handling null pointer constants. | ||||
11994 | QualType LCanPointeeTy = | ||||
11995 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11996 | QualType RCanPointeeTy = | ||||
11997 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11998 | |||||
11999 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||
12000 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||
12001 | RCanPointeeTy.getUnqualifiedType())) { | ||||
12002 | if (IsRelational) { | ||||
12003 | // Pointers both need to point to complete or incomplete types | ||||
12004 | if ((LCanPointeeTy->isIncompleteType() != | ||||
12005 | RCanPointeeTy->isIncompleteType()) && | ||||
12006 | !getLangOpts().C11) { | ||||
12007 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||
12008 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||
12009 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||
12010 | << RCanPointeeTy->isIncompleteType(); | ||||
12011 | } | ||||
12012 | } | ||||
12013 | } else if (!IsRelational && | ||||
12014 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||
12015 | // Valid unless comparison between non-null pointer and function pointer | ||||
12016 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||
12017 | && !LHSIsNull && !RHSIsNull) | ||||
12018 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||
12019 | /*isError*/false); | ||||
12020 | } else { | ||||
12021 | // Invalid | ||||
12022 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||
12023 | } | ||||
12024 | if (LCanPointeeTy != RCanPointeeTy) { | ||||
12025 | // Treat NULL constant as a special case in OpenCL. | ||||
12026 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||
12027 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||
12028 | Diag(Loc, | ||||
12029 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
12030 | << LHSType << RHSType << 0 /* comparison */ | ||||
12031 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
12032 | } | ||||
12033 | } | ||||
12034 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||
12035 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||
12036 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||
12037 | : CK_BitCast; | ||||
12038 | if (LHSIsNull && !RHSIsNull) | ||||
12039 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||
12040 | else | ||||
12041 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||
12042 | } | ||||
12043 | return computeResultTy(); | ||||
12044 | } | ||||
12045 | |||||
12046 | if (getLangOpts().CPlusPlus) { | ||||
12047 | // C++ [expr.eq]p4: | ||||
12048 | // Two operands of type std::nullptr_t or one operand of type | ||||
12049 | // std::nullptr_t and the other a null pointer constant compare equal. | ||||
12050 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||
12051 | if (LHSType->isNullPtrType()) { | ||||
12052 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12053 | return computeResultTy(); | ||||
12054 | } | ||||
12055 | if (RHSType->isNullPtrType()) { | ||||
12056 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12057 | return computeResultTy(); | ||||
12058 | } | ||||
12059 | } | ||||
12060 | |||||
12061 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||
12062 | // These aren't covered by the composite pointer type rules. | ||||
12063 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||
12064 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||
12065 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12066 | return computeResultTy(); | ||||
12067 | } | ||||
12068 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||
12069 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||
12070 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12071 | return computeResultTy(); | ||||
12072 | } | ||||
12073 | |||||
12074 | if (IsRelational && | ||||
12075 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||
12076 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||
12077 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||
12078 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||
12079 | // since otherwise common uses of it break. | ||||
12080 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||
12081 | // friends to have std::nullptr_t overload candidates. | ||||
12082 | DeclContext *DC = CurContext; | ||||
12083 | if (isa<FunctionDecl>(DC)) | ||||
12084 | DC = DC->getParent(); | ||||
12085 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||
12086 | if (CTSD->isInStdNamespace() && | ||||
12087 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||
12088 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||
12089 | .Default(false)) { | ||||
12090 | if (RHSType->isNullPtrType()) | ||||
12091 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12092 | else | ||||
12093 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12094 | return computeResultTy(); | ||||
12095 | } | ||||
12096 | } | ||||
12097 | } | ||||
12098 | |||||
12099 | // C++ [expr.eq]p2: | ||||
12100 | // If at least one operand is a pointer to member, [...] bring them to | ||||
12101 | // their composite pointer type. | ||||
12102 | if (!IsOrdered && | ||||
12103 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||
12104 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
12105 | return QualType(); | ||||
12106 | else | ||||
12107 | return computeResultTy(); | ||||
12108 | } | ||||
12109 | } | ||||
12110 | |||||
12111 | // Handle block pointer types. | ||||
12112 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
12113 | RHSType->isBlockPointerType()) { | ||||
12114 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12115 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
12116 | |||||
12117 | if (!LHSIsNull && !RHSIsNull && | ||||
12118 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||
12119 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12120 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12121 | << RHS.get()->getSourceRange(); | ||||
12122 | } | ||||
12123 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12124 | return computeResultTy(); | ||||
12125 | } | ||||
12126 | |||||
12127 | // Allow block pointers to be compared with null pointer constants. | ||||
12128 | if (!IsOrdered | ||||
12129 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||
12130 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||
12131 | if (!LHSIsNull && !RHSIsNull) { | ||||
12132 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||
12133 | ->getPointeeType()->isVoidType()) | ||||
12134 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||
12135 | ->getPointeeType()->isVoidType()))) | ||||
12136 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
12137 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12138 | << RHS.get()->getSourceRange(); | ||||
12139 | } | ||||
12140 | if (LHSIsNull && !RHSIsNull) | ||||
12141 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12142 | RHSType->isPointerType() ? CK_BitCast | ||||
12143 | : CK_AnyPointerToBlockPointerCast); | ||||
12144 | else | ||||
12145 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12146 | LHSType->isPointerType() ? CK_BitCast | ||||
12147 | : CK_AnyPointerToBlockPointerCast); | ||||
12148 | return computeResultTy(); | ||||
12149 | } | ||||
12150 | |||||
12151 | if (LHSType->isObjCObjectPointerType() || | ||||
12152 | RHSType->isObjCObjectPointerType()) { | ||||
12153 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||
12154 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||
12155 | if (LPT || RPT) { | ||||
12156 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||
12157 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||
12158 | |||||
12159 | if (!LPtrToVoid && !RPtrToVoid && | ||||
12160 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||
12161 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
12162 | /*isError*/false); | ||||
12163 | } | ||||
12164 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||
12165 | // the RHS, but we have test coverage for this behavior. | ||||
12166 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||
12167 | if (LHSIsNull && !RHSIsNull) { | ||||
12168 | Expr *E = LHS.get(); | ||||
12169 | if (getLangOpts().ObjCAutoRefCount) | ||||
12170 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||
12171 | CCK_ImplicitConversion); | ||||
12172 | LHS = ImpCastExprToType(E, RHSType, | ||||
12173 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
12174 | } | ||||
12175 | else { | ||||
12176 | Expr *E = RHS.get(); | ||||
12177 | if (getLangOpts().ObjCAutoRefCount) | ||||
12178 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||
12179 | /*Diagnose=*/true, | ||||
12180 | /*DiagnoseCFAudited=*/false, Opc); | ||||
12181 | RHS = ImpCastExprToType(E, LHSType, | ||||
12182 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
12183 | } | ||||
12184 | return computeResultTy(); | ||||
12185 | } | ||||
12186 | if (LHSType->isObjCObjectPointerType() && | ||||
12187 | RHSType->isObjCObjectPointerType()) { | ||||
12188 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||
12189 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
12190 | /*isError*/false); | ||||
12191 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||
12192 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||
12193 | |||||
12194 | if (LHSIsNull && !RHSIsNull) | ||||
12195 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
12196 | else | ||||
12197 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
12198 | return computeResultTy(); | ||||
12199 | } | ||||
12200 | |||||
12201 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
12202 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
12203 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12204 | CK_BlockPointerToObjCPointerCast); | ||||
12205 | return computeResultTy(); | ||||
12206 | } else if (!IsOrdered && | ||||
12207 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||
12208 | RHSType->isBlockPointerType()) { | ||||
12209 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12210 | CK_BlockPointerToObjCPointerCast); | ||||
12211 | return computeResultTy(); | ||||
12212 | } | ||||
12213 | } | ||||
12214 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||
12215 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||
12216 | unsigned DiagID = 0; | ||||
12217 | bool isError = false; | ||||
12218 | if (LangOpts.DebuggerSupport) { | ||||
12219 | // Under a debugger, allow the comparison of pointers to integers, | ||||
12220 | // since users tend to want to compare addresses. | ||||
12221 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||
12222 | (RHSIsNull && RHSType->isIntegerType())) { | ||||
12223 | if (IsOrdered) { | ||||
12224 | isError = getLangOpts().CPlusPlus; | ||||
12225 | DiagID = | ||||
12226 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||
12227 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||
12228 | } | ||||
12229 | } else if (getLangOpts().CPlusPlus) { | ||||
12230 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||
12231 | isError = true; | ||||
12232 | } else if (IsOrdered) | ||||
12233 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||
12234 | else | ||||
12235 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||
12236 | |||||
12237 | if (DiagID) { | ||||
12238 | Diag(Loc, DiagID) | ||||
12239 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
12240 | << RHS.get()->getSourceRange(); | ||||
12241 | if (isError) | ||||
12242 | return QualType(); | ||||
12243 | } | ||||
12244 | |||||
12245 | if (LHSType->isIntegerType()) | ||||
12246 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
12247 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12248 | else | ||||
12249 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
12250 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
12251 | return computeResultTy(); | ||||
12252 | } | ||||
12253 | |||||
12254 | // Handle block pointers. | ||||
12255 | if (!IsOrdered && RHSIsNull | ||||
12256 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||
12257 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12258 | return computeResultTy(); | ||||
12259 | } | ||||
12260 | if (!IsOrdered && LHSIsNull | ||||
12261 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||
12262 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12263 | return computeResultTy(); | ||||
12264 | } | ||||
12265 | |||||
12266 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||
12267 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||
12268 | return computeResultTy(); | ||||
12269 | } | ||||
12270 | |||||
12271 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||
12272 | return computeResultTy(); | ||||
12273 | } | ||||
12274 | |||||
12275 | if (LHSIsNull && RHSType->isQueueT()) { | ||||
12276 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12277 | return computeResultTy(); | ||||
12278 | } | ||||
12279 | |||||
12280 | if (LHSType->isQueueT() && RHSIsNull) { | ||||
12281 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12282 | return computeResultTy(); | ||||
12283 | } | ||||
12284 | } | ||||
12285 | |||||
12286 | return InvalidOperands(Loc, LHS, RHS); | ||||
12287 | } | ||||
12288 | |||||
12289 | // Return a signed ext_vector_type that is of identical size and number of | ||||
12290 | // elements. For floating point vectors, return an integer type of identical | ||||
12291 | // size and number of elements. In the non ext_vector_type case, search from | ||||
12292 | // the largest type to the smallest type to avoid cases where long long == long, | ||||
12293 | // where long gets picked over long long. | ||||
12294 | QualType Sema::GetSignedVectorType(QualType V) { | ||||
12295 | const VectorType *VTy = V->castAs<VectorType>(); | ||||
12296 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||
12297 | |||||
12298 | if (isa<ExtVectorType>(VTy)) { | ||||
12299 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||
12300 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||
12301 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12302 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||
12303 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12304 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||
12305 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12306 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||
12307 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12308, __extension__ __PRETTY_FUNCTION__)) | ||||
12308 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .LongLongTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12308, __extension__ __PRETTY_FUNCTION__)); | ||||
12309 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||
12310 | } | ||||
12311 | |||||
12312 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||
12313 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||
12314 | VectorType::GenericVector); | ||||
12315 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12316 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||
12317 | VectorType::GenericVector); | ||||
12318 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12319 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||
12320 | VectorType::GenericVector); | ||||
12321 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12322 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||
12323 | VectorType::GenericVector); | ||||
12324 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12325, __extension__ __PRETTY_FUNCTION__)) | ||||
12325 | "Unhandled vector element size in vector compare")(static_cast <bool> (TypeSize == Context.getTypeSize(Context .CharTy) && "Unhandled vector element size in vector compare" ) ? void (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12325, __extension__ __PRETTY_FUNCTION__)); | ||||
12326 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||
12327 | VectorType::GenericVector); | ||||
12328 | } | ||||
12329 | |||||
12330 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||
12331 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||
12332 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||
12333 | /// types. | ||||
12334 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12335 | SourceLocation Loc, | ||||
12336 | BinaryOperatorKind Opc) { | ||||
12337 | if (Opc == BO_Cmp) { | ||||
12338 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
12339 | return QualType(); | ||||
12340 | } | ||||
12341 | |||||
12342 | // Check to make sure we're operating on vectors of the same type and width, | ||||
12343 | // Allowing one side to be a scalar of element type. | ||||
12344 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | ||||
12345 | /*AllowBothBool*/true, | ||||
12346 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12347 | if (vType.isNull()) | ||||
12348 | return vType; | ||||
12349 | |||||
12350 | QualType LHSType = LHS.get()->getType(); | ||||
12351 | |||||
12352 | // Determine the return type of a vector compare. By default clang will return | ||||
12353 | // a scalar for all vector compares except vector bool and vector pixel. | ||||
12354 | // With the gcc compiler we will always return a vector type and with the xl | ||||
12355 | // compiler we will always return a scalar type. This switch allows choosing | ||||
12356 | // which behavior is prefered. | ||||
12357 | if (getLangOpts().AltiVec) { | ||||
12358 | switch (getLangOpts().getAltivecSrcCompat()) { | ||||
12359 | case LangOptions::AltivecSrcCompatKind::Mixed: | ||||
12360 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||
12361 | // bool for C++, int for C | ||||
12362 | if (vType->castAs<VectorType>()->getVectorKind() == | ||||
12363 | VectorType::AltiVecVector) | ||||
12364 | return Context.getLogicalOperationType(); | ||||
12365 | else | ||||
12366 | Diag(Loc, diag::warn_deprecated_altivec_src_compat); | ||||
12367 | break; | ||||
12368 | case LangOptions::AltivecSrcCompatKind::GCC: | ||||
12369 | // For GCC we always return the vector type. | ||||
12370 | break; | ||||
12371 | case LangOptions::AltivecSrcCompatKind::XL: | ||||
12372 | return Context.getLogicalOperationType(); | ||||
12373 | break; | ||||
12374 | } | ||||
12375 | } | ||||
12376 | |||||
12377 | // For non-floating point types, check for self-comparisons of the form | ||||
12378 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12379 | // often indicate logic errors in the program. | ||||
12380 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12381 | |||||
12382 | // Check for comparisons of floating point operands using != and ==. | ||||
12383 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
12384 | LHSType->hasFloatingRepresentation()) { | ||||
12385 | assert(RHS.get()->getType()->hasFloatingRepresentation())(static_cast <bool> (RHS.get()->getType()->hasFloatingRepresentation ()) ? void (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12385, __extension__ __PRETTY_FUNCTION__)); | ||||
12386 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
12387 | } | ||||
12388 | |||||
12389 | // Return a signed type for the vector. | ||||
12390 | return GetSignedVectorType(vType); | ||||
12391 | } | ||||
12392 | |||||
12393 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||
12394 | const ExprResult &XorRHS, | ||||
12395 | const SourceLocation Loc) { | ||||
12396 | // Do not diagnose macros. | ||||
12397 | if (Loc.isMacroID()) | ||||
12398 | return; | ||||
12399 | |||||
12400 | // Do not diagnose if both LHS and RHS are macros. | ||||
12401 | if (XorLHS.get()->getExprLoc().isMacroID() && | ||||
12402 | XorRHS.get()->getExprLoc().isMacroID()) | ||||
12403 | return; | ||||
12404 | |||||
12405 | bool Negative = false; | ||||
12406 | bool ExplicitPlus = false; | ||||
12407 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||
12408 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||
12409 | |||||
12410 | if (!LHSInt) | ||||
12411 | return; | ||||
12412 | if (!RHSInt) { | ||||
12413 | // Check negative literals. | ||||
12414 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||
12415 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||
12416 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||
12417 | return; | ||||
12418 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||
12419 | if (!RHSInt) | ||||
12420 | return; | ||||
12421 | Negative = (Opc == UO_Minus); | ||||
12422 | ExplicitPlus = !Negative; | ||||
12423 | } else { | ||||
12424 | return; | ||||
12425 | } | ||||
12426 | } | ||||
12427 | |||||
12428 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||
12429 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||
12430 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||
12431 | return; | ||||
12432 | |||||
12433 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||
12434 | return; | ||||
12435 | |||||
12436 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||
12437 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||
12438 | llvm::StringRef ExprStr = | ||||
12439 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||
12440 | |||||
12441 | CharSourceRange XorRange = | ||||
12442 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
12443 | llvm::StringRef XorStr = | ||||
12444 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||
12445 | // Do not diagnose if xor keyword/macro is used. | ||||
12446 | if (XorStr == "xor") | ||||
12447 | return; | ||||
12448 | |||||
12449 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||
12450 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||
12451 | S.getSourceManager(), S.getLangOpts())); | ||||
12452 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||
12453 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||
12454 | S.getSourceManager(), S.getLangOpts())); | ||||
12455 | |||||
12456 | if (Negative) { | ||||
12457 | RightSideValue = -RightSideValue; | ||||
12458 | RHSStr = "-" + RHSStr; | ||||
12459 | } else if (ExplicitPlus) { | ||||
12460 | RHSStr = "+" + RHSStr; | ||||
12461 | } | ||||
12462 | |||||
12463 | StringRef LHSStrRef = LHSStr; | ||||
12464 | StringRef RHSStrRef = RHSStr; | ||||
12465 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||
12466 | // literals. | ||||
12467 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||
12468 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||
12469 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||
12470 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||
12471 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||
12472 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||
12473 | LHSStrRef.find('\'') != StringRef::npos || | ||||
12474 | RHSStrRef.find('\'') != StringRef::npos) | ||||
12475 | return; | ||||
12476 | |||||
12477 | bool SuggestXor = | ||||
12478 | S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||
12479 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||
12480 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||
12481 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||
12482 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||
12483 | bool Overflow = false; | ||||
12484 | llvm::APInt One = (LeftSideValue - 1); | ||||
12485 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||
12486 | if (Overflow) { | ||||
12487 | if (RightSideIntValue < 64) | ||||
12488 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12489 | << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) | ||||
12490 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||
12491 | else if (RightSideIntValue == 64) | ||||
12492 | S.Diag(Loc, diag::warn_xor_used_as_pow) | ||||
12493 | << ExprStr << toString(XorValue, 10, true); | ||||
12494 | else | ||||
12495 | return; | ||||
12496 | } else { | ||||
12497 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||
12498 | << ExprStr << toString(XorValue, 10, true) << SuggestedExpr | ||||
12499 | << toString(PowValue, 10, true) | ||||
12500 | << FixItHint::CreateReplacement( | ||||
12501 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||
12502 | } | ||||
12503 | |||||
12504 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
12505 | << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||
12506 | } else if (LeftSideValue == 10) { | ||||
12507 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||
12508 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12509 | << ExprStr << toString(XorValue, 10, true) << SuggestedValue | ||||
12510 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||
12511 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) | ||||
12512 | << ("0xA ^ " + RHSStr) << SuggestXor; | ||||
12513 | } | ||||
12514 | } | ||||
12515 | |||||
12516 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12517 | SourceLocation Loc) { | ||||
12518 | // Ensure that either both operands are of the same vector type, or | ||||
12519 | // one operand is of a vector type and the other is of its element type. | ||||
12520 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||
12521 | /*AllowBothBool*/true, | ||||
12522 | /*AllowBoolConversions*/false); | ||||
12523 | if (vType.isNull()) | ||||
12524 | return InvalidOperands(Loc, LHS, RHS); | ||||
12525 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | ||||
12526 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) | ||||
12527 | return InvalidOperands(Loc, LHS, RHS); | ||||
12528 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||
12529 | // usage of the logical operators && and || with vectors in C. This | ||||
12530 | // check could be notionally dropped. | ||||
12531 | if (!getLangOpts().CPlusPlus && | ||||
12532 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||
12533 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||
12534 | |||||
12535 | return GetSignedVectorType(LHS.get()->getType()); | ||||
12536 | } | ||||
12537 | |||||
12538 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12539 | SourceLocation Loc, | ||||
12540 | bool IsCompAssign) { | ||||
12541 | if (!IsCompAssign) { | ||||
12542 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12543 | if (LHS.isInvalid()) | ||||
12544 | return QualType(); | ||||
12545 | } | ||||
12546 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12547 | if (RHS.isInvalid()) | ||||
12548 | return QualType(); | ||||
12549 | |||||
12550 | // For conversion purposes, we ignore any qualifiers. | ||||
12551 | // For example, "const float" and "float" are equivalent. | ||||
12552 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
12553 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
12554 | |||||
12555 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||
12556 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||
12557 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12557, __extension__ __PRETTY_FUNCTION__)); | ||||
12558 | |||||
12559 | if (Context.hasSameType(LHSType, RHSType)) | ||||
12560 | return LHSType; | ||||
12561 | |||||
12562 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||
12563 | // case we have to return InvalidOperands. | ||||
12564 | ExprResult OriginalLHS = LHS; | ||||
12565 | ExprResult OriginalRHS = RHS; | ||||
12566 | if (LHSMatType && !RHSMatType) { | ||||
12567 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||
12568 | if (!RHS.isInvalid()) | ||||
12569 | return LHSType; | ||||
12570 | |||||
12571 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12572 | } | ||||
12573 | |||||
12574 | if (!LHSMatType && RHSMatType) { | ||||
12575 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||
12576 | if (!LHS.isInvalid()) | ||||
12577 | return RHSType; | ||||
12578 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12579 | } | ||||
12580 | |||||
12581 | return InvalidOperands(Loc, LHS, RHS); | ||||
12582 | } | ||||
12583 | |||||
12584 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12585 | SourceLocation Loc, | ||||
12586 | bool IsCompAssign) { | ||||
12587 | if (!IsCompAssign) { | ||||
12588 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12589 | if (LHS.isInvalid()) | ||||
12590 | return QualType(); | ||||
12591 | } | ||||
12592 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12593 | if (RHS.isInvalid()) | ||||
12594 | return QualType(); | ||||
12595 | |||||
12596 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12597 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12598 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(static_cast <bool> ((LHSMatType || RHSMatType) && "At least one operand must be a matrix") ? void (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12598, __extension__ __PRETTY_FUNCTION__)); | ||||
12599 | |||||
12600 | if (LHSMatType && RHSMatType) { | ||||
12601 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||
12602 | return InvalidOperands(Loc, LHS, RHS); | ||||
12603 | |||||
12604 | if (!Context.hasSameType(LHSMatType->getElementType(), | ||||
12605 | RHSMatType->getElementType())) | ||||
12606 | return InvalidOperands(Loc, LHS, RHS); | ||||
12607 | |||||
12608 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | ||||
12609 | LHSMatType->getNumRows(), | ||||
12610 | RHSMatType->getNumColumns()); | ||||
12611 | } | ||||
12612 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
12613 | } | ||||
12614 | |||||
12615 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12616 | SourceLocation Loc, | ||||
12617 | BinaryOperatorKind Opc) { | ||||
12618 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
12619 | |||||
12620 | bool IsCompAssign = | ||||
12621 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||
12622 | |||||
12623 | if (LHS.get()->getType()->isVectorType() || | ||||
12624 | RHS.get()->getType()->isVectorType()) { | ||||
12625 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
12626 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
12627 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
12628 | /*AllowBothBool*/true, | ||||
12629 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12630 | return InvalidOperands(Loc, LHS, RHS); | ||||
12631 | } | ||||
12632 | |||||
12633 | if (Opc == BO_And) | ||||
12634 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
12635 | |||||
12636 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||
12637 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||
12638 | return InvalidOperands(Loc, LHS, RHS); | ||||
12639 | |||||
12640 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||
12641 | QualType compType = UsualArithmeticConversions( | ||||
12642 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||
12643 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||
12644 | return QualType(); | ||||
12645 | LHS = LHSResult.get(); | ||||
12646 | RHS = RHSResult.get(); | ||||
12647 | |||||
12648 | if (Opc == BO_Xor) | ||||
12649 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||
12650 | |||||
12651 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||
12652 | return compType; | ||||
12653 | return InvalidOperands(Loc, LHS, RHS); | ||||
12654 | } | ||||
12655 | |||||
12656 | // C99 6.5.[13,14] | ||||
12657 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12658 | SourceLocation Loc, | ||||
12659 | BinaryOperatorKind Opc) { | ||||
12660 | // Check vector operands differently. | ||||
12661 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | ||||
12662 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||
12663 | |||||
12664 | bool EnumConstantInBoolContext = false; | ||||
12665 | for (const ExprResult &HS : {LHS, RHS}) { | ||||
12666 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||
12667 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||
12668 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||
12669 | EnumConstantInBoolContext = true; | ||||
12670 | } | ||||
12671 | } | ||||
12672 | |||||
12673 | if (EnumConstantInBoolContext) | ||||
12674 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||
12675 | |||||
12676 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||
12677 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||
12678 | // is a constant. | ||||
12679 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||
12680 | !LHS.get()->getType()->isBooleanType() && | ||||
12681 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||
12682 | // Don't warn in macros or template instantiations. | ||||
12683 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||
12684 | // If the RHS can be constant folded, and if it constant folds to something | ||||
12685 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||
12686 | // happened to fold to true/false) then warn. | ||||
12687 | // Parens on the RHS are ignored. | ||||
12688 | Expr::EvalResult EVResult; | ||||
12689 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||
12690 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
12691 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||
12692 | !RHS.get()->getExprLoc().isMacroID()) || | ||||
12693 | (Result != 0 && Result != 1)) { | ||||
12694 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||
12695 | << RHS.get()->getSourceRange() | ||||
12696 | << (Opc == BO_LAnd ? "&&" : "||"); | ||||
12697 | // Suggest replacing the logical operator with the bitwise version | ||||
12698 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||
12699 | << (Opc == BO_LAnd ? "&" : "|") | ||||
12700 | << FixItHint::CreateReplacement(SourceRange( | ||||
12701 | Loc, getLocForEndOfToken(Loc)), | ||||
12702 | Opc == BO_LAnd ? "&" : "|"); | ||||
12703 | if (Opc == BO_LAnd) | ||||
12704 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||
12705 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||
12706 | << FixItHint::CreateRemoval( | ||||
12707 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||
12708 | RHS.get()->getEndLoc())); | ||||
12709 | } | ||||
12710 | } | ||||
12711 | } | ||||
12712 | |||||
12713 | if (!Context.getLangOpts().CPlusPlus) { | ||||
12714 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||
12715 | // not operate on the built-in scalar and vector float types. | ||||
12716 | if (Context.getLangOpts().OpenCL && | ||||
12717 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
12718 | if (LHS.get()->getType()->isFloatingType() || | ||||
12719 | RHS.get()->getType()->isFloatingType()) | ||||
12720 | return InvalidOperands(Loc, LHS, RHS); | ||||
12721 | } | ||||
12722 | |||||
12723 | LHS = UsualUnaryConversions(LHS.get()); | ||||
12724 | if (LHS.isInvalid()) | ||||
12725 | return QualType(); | ||||
12726 | |||||
12727 | RHS = UsualUnaryConversions(RHS.get()); | ||||
12728 | if (RHS.isInvalid()) | ||||
12729 | return QualType(); | ||||
12730 | |||||
12731 | if (!LHS.get()->getType()->isScalarType() || | ||||
12732 | !RHS.get()->getType()->isScalarType()) | ||||
12733 | return InvalidOperands(Loc, LHS, RHS); | ||||
12734 | |||||
12735 | return Context.IntTy; | ||||
12736 | } | ||||
12737 | |||||
12738 | // The following is safe because we only use this method for | ||||
12739 | // non-overloadable operands. | ||||
12740 | |||||
12741 | // C++ [expr.log.and]p1 | ||||
12742 | // C++ [expr.log.or]p1 | ||||
12743 | // The operands are both contextually converted to type bool. | ||||
12744 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||
12745 | if (LHSRes.isInvalid()) | ||||
12746 | return InvalidOperands(Loc, LHS, RHS); | ||||
12747 | LHS = LHSRes; | ||||
12748 | |||||
12749 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||
12750 | if (RHSRes.isInvalid()) | ||||
12751 | return InvalidOperands(Loc, LHS, RHS); | ||||
12752 | RHS = RHSRes; | ||||
12753 | |||||
12754 | // C++ [expr.log.and]p2 | ||||
12755 | // C++ [expr.log.or]p2 | ||||
12756 | // The result is a bool. | ||||
12757 | return Context.BoolTy; | ||||
12758 | } | ||||
12759 | |||||
12760 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||
12761 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
12762 | if (!ME) return false; | ||||
12763 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||
12764 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||
12765 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||
12766 | if (!Base) return false; | ||||
12767 | return Base->getMethodDecl() != nullptr; | ||||
12768 | } | ||||
12769 | |||||
12770 | /// Is the given expression (which must be 'const') a reference to a | ||||
12771 | /// variable which was originally non-const, but which has become | ||||
12772 | /// 'const' due to being captured within a block? | ||||
12773 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||
12774 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||
12775 | assert(E->isLValue() && E->getType().isConstQualified())(static_cast <bool> (E->isLValue() && E-> getType().isConstQualified()) ? void (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12775, __extension__ __PRETTY_FUNCTION__)); | ||||
12776 | E = E->IgnoreParens(); | ||||
12777 | |||||
12778 | // Must be a reference to a declaration from an enclosing scope. | ||||
12779 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
12780 | if (!DRE) return NCCK_None; | ||||
12781 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||
12782 | |||||
12783 | // The declaration must be a variable which is not declared 'const'. | ||||
12784 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
12785 | if (!var) return NCCK_None; | ||||
12786 | if (var->getType().isConstQualified()) return NCCK_None; | ||||
12787 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")(static_cast <bool> (var->hasLocalStorage() && "capture added 'const' to non-local?") ? void (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12787, __extension__ __PRETTY_FUNCTION__)); | ||||
12788 | |||||
12789 | // Decide whether the first capture was for a block or a lambda. | ||||
12790 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||
12791 | // Decide whether the first capture was for a block or a lambda. | ||||
12792 | while (DC) { | ||||
12793 | // For init-capture, it is possible that the variable belongs to the | ||||
12794 | // template pattern of the current context. | ||||
12795 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||
12796 | if (var->isInitCapture() && | ||||
12797 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||
12798 | break; | ||||
12799 | if (DC == var->getDeclContext()) | ||||
12800 | break; | ||||
12801 | Prev = DC; | ||||
12802 | DC = DC->getParent(); | ||||
12803 | } | ||||
12804 | // Unless we have an init-capture, we've gone one step too far. | ||||
12805 | if (!var->isInitCapture()) | ||||
12806 | DC = Prev; | ||||
12807 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||
12808 | } | ||||
12809 | |||||
12810 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||
12811 | Ty = Ty.getNonReferenceType(); | ||||
12812 | if (IsDereference && Ty->isPointerType()) | ||||
12813 | Ty = Ty->getPointeeType(); | ||||
12814 | return !Ty.isConstQualified(); | ||||
12815 | } | ||||
12816 | |||||
12817 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||
12818 | // when this enum is changed. | ||||
12819 | enum { | ||||
12820 | ConstFunction, | ||||
12821 | ConstVariable, | ||||
12822 | ConstMember, | ||||
12823 | ConstMethod, | ||||
12824 | NestedConstMember, | ||||
12825 | ConstUnknown, // Keep as last element | ||||
12826 | }; | ||||
12827 | |||||
12828 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||
12829 | /// more information about why the variable is not assignable, such as pointing | ||||
12830 | /// to the declaration of a const variable, showing that a method is const, or | ||||
12831 | /// that the function is returning a const reference. | ||||
12832 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||
12833 | SourceLocation Loc) { | ||||
12834 | SourceRange ExprRange = E->getSourceRange(); | ||||
12835 | |||||
12836 | // Only emit one error on the first const found. All other consts will emit | ||||
12837 | // a note to the error. | ||||
12838 | bool DiagnosticEmitted = false; | ||||
12839 | |||||
12840 | // Track if the current expression is the result of a dereference, and if the | ||||
12841 | // next checked expression is the result of a dereference. | ||||
12842 | bool IsDereference = false; | ||||
12843 | bool NextIsDereference = false; | ||||
12844 | |||||
12845 | // Loop to process MemberExpr chains. | ||||
12846 | while (true) { | ||||
12847 | IsDereference = NextIsDereference; | ||||
12848 | |||||
12849 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||
12850 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
12851 | NextIsDereference = ME->isArrow(); | ||||
12852 | const ValueDecl *VD = ME->getMemberDecl(); | ||||
12853 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||
12854 | // Mutable fields can be modified even if the class is const. | ||||
12855 | if (Field->isMutable()) { | ||||
12856 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")(static_cast <bool> (DiagnosticEmitted && "Expected diagnostic not emitted." ) ? void (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 12856, __extension__ __PRETTY_FUNCTION__)); | ||||
12857 | break; | ||||
12858 | } | ||||
12859 | |||||
12860 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||
12861 | if (!DiagnosticEmitted) { | ||||
12862 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12863 | << ExprRange << ConstMember << false /*static*/ << Field | ||||
12864 | << Field->getType(); | ||||
12865 | DiagnosticEmitted = true; | ||||
12866 | } | ||||
12867 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12868 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||
12869 | << Field->getSourceRange(); | ||||
12870 | } | ||||
12871 | E = ME->getBase(); | ||||
12872 | continue; | ||||
12873 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||
12874 | if (VDecl->getType().isConstQualified()) { | ||||
12875 | if (!DiagnosticEmitted) { | ||||
12876 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12877 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||
12878 | << VDecl->getType(); | ||||
12879 | DiagnosticEmitted = true; | ||||
12880 | } | ||||
12881 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12882 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||
12883 | << VDecl->getSourceRange(); | ||||
12884 | } | ||||
12885 | // Static fields do not inherit constness from parents. | ||||
12886 | break; | ||||
12887 | } | ||||
12888 | break; // End MemberExpr | ||||
12889 | } else if (const ArraySubscriptExpr *ASE = | ||||
12890 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||
12891 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||
12892 | continue; | ||||
12893 | } else if (const ExtVectorElementExpr *EVE = | ||||
12894 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||
12895 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||
12896 | continue; | ||||
12897 | } | ||||
12898 | break; | ||||
12899 | } | ||||
12900 | |||||
12901 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
12902 | // Function calls | ||||
12903 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||
12904 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||
12905 | if (!DiagnosticEmitted) { | ||||
12906 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12907 | << ConstFunction << FD; | ||||
12908 | DiagnosticEmitted = true; | ||||
12909 | } | ||||
12910 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||
12911 | diag::note_typecheck_assign_const) | ||||
12912 | << ConstFunction << FD << FD->getReturnType() | ||||
12913 | << FD->getReturnTypeSourceRange(); | ||||
12914 | } | ||||
12915 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
12916 | // Point to variable declaration. | ||||
12917 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||
12918 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||
12919 | if (!DiagnosticEmitted) { | ||||
12920 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12921 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||
12922 | DiagnosticEmitted = true; | ||||
12923 | } | ||||
12924 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12925 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||
12926 | } | ||||
12927 | } | ||||
12928 | } else if (isa<CXXThisExpr>(E)) { | ||||
12929 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||
12930 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||
12931 | if (MD->isConst()) { | ||||
12932 | if (!DiagnosticEmitted) { | ||||
12933 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12934 | << ConstMethod << MD; | ||||
12935 | DiagnosticEmitted = true; | ||||
12936 | } | ||||
12937 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||
12938 | << ConstMethod << MD << MD->getSourceRange(); | ||||
12939 | } | ||||
12940 | } | ||||
12941 | } | ||||
12942 | } | ||||
12943 | |||||
12944 | if (DiagnosticEmitted) | ||||
12945 | return; | ||||
12946 | |||||
12947 | // Can't determine a more specific message, so display the generic error. | ||||
12948 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||
12949 | } | ||||
12950 | |||||
12951 | enum OriginalExprKind { | ||||
12952 | OEK_Variable, | ||||
12953 | OEK_Member, | ||||
12954 | OEK_LValue | ||||
12955 | }; | ||||
12956 | |||||
12957 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||
12958 | const RecordType *Ty, | ||||
12959 | SourceLocation Loc, SourceRange Range, | ||||
12960 | OriginalExprKind OEK, | ||||
12961 | bool &DiagnosticEmitted) { | ||||
12962 | std::vector<const RecordType *> RecordTypeList; | ||||
12963 | RecordTypeList.push_back(Ty); | ||||
12964 | unsigned NextToCheckIndex = 0; | ||||
12965 | // We walk the record hierarchy breadth-first to ensure that we print | ||||
12966 | // diagnostics in field nesting order. | ||||
12967 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||
12968 | bool IsNested = NextToCheckIndex > 0; | ||||
12969 | for (const FieldDecl *Field : | ||||
12970 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||
12971 | // First, check every field for constness. | ||||
12972 | QualType FieldTy = Field->getType(); | ||||
12973 | if (FieldTy.isConstQualified()) { | ||||
12974 | if (!DiagnosticEmitted) { | ||||
12975 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12976 | << Range << NestedConstMember << OEK << VD | ||||
12977 | << IsNested << Field; | ||||
12978 | DiagnosticEmitted = true; | ||||
12979 | } | ||||
12980 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||
12981 | << NestedConstMember << IsNested << Field | ||||
12982 | << FieldTy << Field->getSourceRange(); | ||||
12983 | } | ||||
12984 | |||||
12985 | // Then we append it to the list to check next in order. | ||||
12986 | FieldTy = FieldTy.getCanonicalType(); | ||||
12987 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||
12988 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) | ||||
12989 | RecordTypeList.push_back(FieldRecTy); | ||||
12990 | } | ||||
12991 | } | ||||
12992 | ++NextToCheckIndex; | ||||
12993 | } | ||||
12994 | } | ||||
12995 | |||||
12996 | /// Emit an error for the case where a record we are trying to assign to has a | ||||
12997 | /// const-qualified field somewhere in its hierarchy. | ||||
12998 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||
12999 | SourceLocation Loc) { | ||||
13000 | QualType Ty = E->getType(); | ||||
13001 | assert(Ty->isRecordType() && "lvalue was not record?")(static_cast <bool> (Ty->isRecordType() && "lvalue was not record?" ) ? void (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13001, __extension__ __PRETTY_FUNCTION__)); | ||||
13002 | SourceRange Range = E->getSourceRange(); | ||||
13003 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||
13004 | bool DiagEmitted = false; | ||||
13005 | |||||
13006 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
13007 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||
13008 | Range, OEK_Member, DiagEmitted); | ||||
13009 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
13010 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||
13011 | Range, OEK_Variable, DiagEmitted); | ||||
13012 | else | ||||
13013 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||
13014 | Range, OEK_LValue, DiagEmitted); | ||||
13015 | if (!DiagEmitted) | ||||
13016 | DiagnoseConstAssignment(S, E, Loc); | ||||
13017 | } | ||||
13018 | |||||
13019 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||
13020 | /// emit an error and return true. If so, return false. | ||||
13021 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||
13022 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!E->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13022, __extension__ __PRETTY_FUNCTION__)); | ||||
13023 | |||||
13024 | S.CheckShadowingDeclModification(E, Loc); | ||||
13025 | |||||
13026 | SourceLocation OrigLoc = Loc; | ||||
13027 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||
13028 | &Loc); | ||||
13029 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||
13030 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||
13031 | if (IsLV == Expr::MLV_Valid) | ||||
13032 | return false; | ||||
13033 | |||||
13034 | unsigned DiagID = 0; | ||||
13035 | bool NeedType = false; | ||||
13036 | switch (IsLV) { // C99 6.5.16p2 | ||||
13037 | case Expr::MLV_ConstQualified: | ||||
13038 | // Use a specialized diagnostic when we're assigning to an object | ||||
13039 | // from an enclosing function or block. | ||||
13040 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||
13041 | if (NCCK == NCCK_Block) | ||||
13042 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||
13043 | else | ||||
13044 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||
13045 | break; | ||||
13046 | } | ||||
13047 | |||||
13048 | // In ARC, use some specialized diagnostics for occasions where we | ||||
13049 | // infer 'const'. These are always pseudo-strong variables. | ||||
13050 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||
13051 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||
13052 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||
13053 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||
13054 | |||||
13055 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||
13056 | // user actually wrote 'const'. | ||||
13057 | if (var->isARCPseudoStrong() && | ||||
13058 | (!var->getTypeSourceInfo() || | ||||
13059 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||
13060 | // There are three pseudo-strong cases: | ||||
13061 | // - self | ||||
13062 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||
13063 | if (method && var == method->getSelfDecl()) { | ||||
13064 | DiagID = method->isClassMethod() | ||||
13065 | ? diag::err_typecheck_arc_assign_self_class_method | ||||
13066 | : diag::err_typecheck_arc_assign_self; | ||||
13067 | |||||
13068 | // - Objective-C externally_retained attribute. | ||||
13069 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||
13070 | isa<ParmVarDecl>(var)) { | ||||
13071 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||
13072 | |||||
13073 | // - fast enumeration variables | ||||
13074 | } else { | ||||
13075 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||
13076 | } | ||||
13077 | |||||
13078 | SourceRange Assign; | ||||
13079 | if (Loc != OrigLoc) | ||||
13080 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
13081 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
13082 | // We need to preserve the AST regardless, so migration tool | ||||
13083 | // can do its job. | ||||
13084 | return false; | ||||
13085 | } | ||||
13086 | } | ||||
13087 | } | ||||
13088 | |||||
13089 | // If none of the special cases above are triggered, then this is a | ||||
13090 | // simple const assignment. | ||||
13091 | if (DiagID == 0) { | ||||
13092 | DiagnoseConstAssignment(S, E, Loc); | ||||
13093 | return true; | ||||
13094 | } | ||||
13095 | |||||
13096 | break; | ||||
13097 | case Expr::MLV_ConstAddrSpace: | ||||
13098 | DiagnoseConstAssignment(S, E, Loc); | ||||
13099 | return true; | ||||
13100 | case Expr::MLV_ConstQualifiedField: | ||||
13101 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||
13102 | return true; | ||||
13103 | case Expr::MLV_ArrayType: | ||||
13104 | case Expr::MLV_ArrayTemporary: | ||||
13105 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||
13106 | NeedType = true; | ||||
13107 | break; | ||||
13108 | case Expr::MLV_NotObjectType: | ||||
13109 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||
13110 | NeedType = true; | ||||
13111 | break; | ||||
13112 | case Expr::MLV_LValueCast: | ||||
13113 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||
13114 | break; | ||||
13115 | case Expr::MLV_Valid: | ||||
13116 | llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13116); | ||||
13117 | case Expr::MLV_InvalidExpression: | ||||
13118 | case Expr::MLV_MemberFunction: | ||||
13119 | case Expr::MLV_ClassTemporary: | ||||
13120 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||
13121 | break; | ||||
13122 | case Expr::MLV_IncompleteType: | ||||
13123 | case Expr::MLV_IncompleteVoidType: | ||||
13124 | return S.RequireCompleteType(Loc, E->getType(), | ||||
13125 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||
13126 | case Expr::MLV_DuplicateVectorComponents: | ||||
13127 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||
13128 | break; | ||||
13129 | case Expr::MLV_NoSetterProperty: | ||||
13130 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13130); | ||||
13131 | case Expr::MLV_InvalidMessageExpression: | ||||
13132 | DiagID = diag::err_readonly_message_assignment; | ||||
13133 | break; | ||||
13134 | case Expr::MLV_SubObjCPropertySetting: | ||||
13135 | DiagID = diag::err_no_subobject_property_setting; | ||||
13136 | break; | ||||
13137 | } | ||||
13138 | |||||
13139 | SourceRange Assign; | ||||
13140 | if (Loc != OrigLoc) | ||||
13141 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
13142 | if (NeedType) | ||||
13143 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||
13144 | else | ||||
13145 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
13146 | return true; | ||||
13147 | } | ||||
13148 | |||||
13149 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||
13150 | SourceLocation Loc, | ||||
13151 | Sema &Sema) { | ||||
13152 | if (Sema.inTemplateInstantiation()) | ||||
13153 | return; | ||||
13154 | if (Sema.isUnevaluatedContext()) | ||||
13155 | return; | ||||
13156 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||
13157 | return; | ||||
13158 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||
13159 | return; | ||||
13160 | |||||
13161 | // C / C++ fields | ||||
13162 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||
13163 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||
13164 | if (ML && MR) { | ||||
13165 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||
13166 | return; | ||||
13167 | const ValueDecl *LHSDecl = | ||||
13168 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||
13169 | const ValueDecl *RHSDecl = | ||||
13170 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||
13171 | if (LHSDecl != RHSDecl) | ||||
13172 | return; | ||||
13173 | if (LHSDecl->getType().isVolatileQualified()) | ||||
13174 | return; | ||||
13175 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
13176 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
13177 | return; | ||||
13178 | |||||
13179 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||
13180 | } | ||||
13181 | |||||
13182 | // Objective-C instance variables | ||||
13183 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||
13184 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||
13185 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||
13186 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||
13187 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||
13188 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||
13189 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||
13190 | } | ||||
13191 | } | ||||
13192 | |||||
13193 | // C99 6.5.16.1 | ||||
13194 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||
13195 | SourceLocation Loc, | ||||
13196 | QualType CompoundType) { | ||||
13197 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))(static_cast <bool> (!LHSExpr->hasPlaceholderType(BuiltinType ::PseudoObject)) ? void (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13197, __extension__ __PRETTY_FUNCTION__)); | ||||
13198 | |||||
13199 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||
13200 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||
13201 | return QualType(); | ||||
13202 | |||||
13203 | QualType LHSType = LHSExpr->getType(); | ||||
13204 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||
13205 | CompoundType; | ||||
13206 | // OpenCL v1.2 s6.1.1.1 p2: | ||||
13207 | // The half data type can only be used to declare a pointer to a buffer that | ||||
13208 | // contains half values | ||||
13209 | if (getLangOpts().OpenCL && | ||||
13210 | !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && | ||||
13211 | LHSType->isHalfType()) { | ||||
13212 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||
13213 | << LHSType.getUnqualifiedType(); | ||||
13214 | return QualType(); | ||||
13215 | } | ||||
13216 | |||||
13217 | AssignConvertType ConvTy; | ||||
13218 | if (CompoundType.isNull()) { | ||||
13219 | Expr *RHSCheck = RHS.get(); | ||||
13220 | |||||
13221 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||
13222 | |||||
13223 | QualType LHSTy(LHSType); | ||||
13224 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||
13225 | if (RHS.isInvalid()) | ||||
13226 | return QualType(); | ||||
13227 | // Special case of NSObject attributes on c-style pointer types. | ||||
13228 | if (ConvTy == IncompatiblePointer && | ||||
13229 | ((Context.isObjCNSObjectType(LHSType) && | ||||
13230 | RHSType->isObjCObjectPointerType()) || | ||||
13231 | (Context.isObjCNSObjectType(RHSType) && | ||||
13232 | LHSType->isObjCObjectPointerType()))) | ||||
13233 | ConvTy = Compatible; | ||||
13234 | |||||
13235 | if (ConvTy == Compatible && | ||||
13236 | LHSType->isObjCObjectType()) | ||||
13237 | Diag(Loc, diag::err_objc_object_assignment) | ||||
13238 | << LHSType; | ||||
13239 | |||||
13240 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||
13241 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||
13242 | // instead of "x += 4". | ||||
13243 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||
13244 | RHSCheck = ICE->getSubExpr(); | ||||
13245 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||
13246 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||
13247 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||
13248 | // Only if the two operators are exactly adjacent. | ||||
13249 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||
13250 | // And there is a space or other character before the subexpr of the | ||||
13251 | // unary +/-. We don't want to warn on "x=-1". | ||||
13252 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||
13253 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||
13254 | Diag(Loc, diag::warn_not_compound_assign) | ||||
13255 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||
13256 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||
13257 | } | ||||
13258 | } | ||||
13259 | |||||
13260 | if (ConvTy == Compatible) { | ||||
13261 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||
13262 | // Warn about retain cycles where a block captures the LHS, but | ||||
13263 | // not if the LHS is a simple variable into which the block is | ||||
13264 | // being stored...unless that variable can be captured by reference! | ||||
13265 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||
13266 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||
13267 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||
13268 | checkRetainCycles(LHSExpr, RHS.get()); | ||||
13269 | } | ||||
13270 | |||||
13271 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
13272 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||
13273 | // It is safe to assign a weak reference into a strong variable. | ||||
13274 | // Although this code can still have problems: | ||||
13275 | // id x = self.weakProp; | ||||
13276 | // id y = self.weakProp; | ||||
13277 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
13278 | // paths through the function. This should be revisited if | ||||
13279 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
13280 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||
13281 | // variable, which will be valid for the current autorelease scope. | ||||
13282 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
13283 | RHS.get()->getBeginLoc())) | ||||
13284 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||
13285 | |||||
13286 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||
13287 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||
13288 | } | ||||
13289 | } | ||||
13290 | } else { | ||||
13291 | // Compound assignment "x += y" | ||||
13292 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||
13293 | } | ||||
13294 | |||||
13295 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||
13296 | RHS.get(), AA_Assigning)) | ||||
13297 | return QualType(); | ||||
13298 | |||||
13299 | CheckForNullPointerDereference(*this, LHSExpr); | ||||
13300 | |||||
13301 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||
13302 | if (CompoundType.isNull()) { | ||||
13303 | // C++2a [expr.ass]p5: | ||||
13304 | // A simple-assignment whose left operand is of a volatile-qualified | ||||
13305 | // type is deprecated unless the assignment is either a discarded-value | ||||
13306 | // expression or an unevaluated operand | ||||
13307 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||
13308 | } else { | ||||
13309 | // C++2a [expr.ass]p6: | ||||
13310 | // [Compound-assignment] expressions are deprecated if E1 has | ||||
13311 | // volatile-qualified type | ||||
13312 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | ||||
13313 | } | ||||
13314 | } | ||||
13315 | |||||
13316 | // C99 6.5.16p3: The type of an assignment expression is the type of the | ||||
13317 | // left operand unless the left operand has qualified type, in which case | ||||
13318 | // it is the unqualified version of the type of the left operand. | ||||
13319 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | ||||
13320 | // is converted to the type of the assignment expression (above). | ||||
13321 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||
13322 | // operand. | ||||
13323 | return (getLangOpts().CPlusPlus | ||||
13324 | ? LHSType : LHSType.getUnqualifiedType()); | ||||
13325 | } | ||||
13326 | |||||
13327 | // Only ignore explicit casts to void. | ||||
13328 | static bool IgnoreCommaOperand(const Expr *E) { | ||||
13329 | E = E->IgnoreParens(); | ||||
13330 | |||||
13331 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||
13332 | if (CE->getCastKind() == CK_ToVoid) { | ||||
13333 | return true; | ||||
13334 | } | ||||
13335 | |||||
13336 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||
13337 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||
13338 | CE->getSubExpr()->getType()->isDependentType()) { | ||||
13339 | return true; | ||||
13340 | } | ||||
13341 | } | ||||
13342 | |||||
13343 | return false; | ||||
13344 | } | ||||
13345 | |||||
13346 | // Look for instances where it is likely the comma operator is confused with | ||||
13347 | // another operator. There is an explicit list of acceptable expressions for | ||||
13348 | // the left hand side of the comma operator, otherwise emit a warning. | ||||
13349 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||
13350 | // No warnings in macros | ||||
13351 | if (Loc.isMacroID()) | ||||
13352 | return; | ||||
13353 | |||||
13354 | // Don't warn in template instantiations. | ||||
13355 | if (inTemplateInstantiation()) | ||||
13356 | return; | ||||
13357 | |||||
13358 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||
13359 | // instead, skip more than needed, then call back into here with the | ||||
13360 | // CommaVisitor in SemaStmt.cpp. | ||||
13361 | // The listed locations are the initialization and increment portions | ||||
13362 | // of a for loop. The additional checks are on the condition of | ||||
13363 | // if statements, do/while loops, and for loops. | ||||
13364 | // Differences in scope flags for C89 mode requires the extra logic. | ||||
13365 | const unsigned ForIncrementFlags = | ||||
13366 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||
13367 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||
13368 | : Scope::ContinueScope | Scope::BreakScope; | ||||
13369 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||
13370 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||
13371 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||
13372 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||
13373 | return; | ||||
13374 | |||||
13375 | // If there are multiple comma operators used together, get the RHS of the | ||||
13376 | // of the comma operator as the LHS. | ||||
13377 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||
13378 | if (BO->getOpcode() != BO_Comma) | ||||
13379 | break; | ||||
13380 | LHS = BO->getRHS(); | ||||
13381 | } | ||||
13382 | |||||
13383 | // Only allow some expressions on LHS to not warn. | ||||
13384 | if (IgnoreCommaOperand(LHS)) | ||||
13385 | return; | ||||
13386 | |||||
13387 | Diag(Loc, diag::warn_comma_operator); | ||||
13388 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||
13389 | << LHS->getSourceRange() | ||||
13390 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||
13391 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||
13392 | : "(void)(") | ||||
13393 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||
13394 | ")"); | ||||
13395 | } | ||||
13396 | |||||
13397 | // C99 6.5.17 | ||||
13398 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
13399 | SourceLocation Loc) { | ||||
13400 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||
13401 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||
13402 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
13403 | return QualType(); | ||||
13404 | |||||
13405 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||
13406 | // operands, but not unary promotions. | ||||
13407 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||
13408 | |||||
13409 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||
13410 | // containing site to determine what should be done with the RHS. | ||||
13411 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||
13412 | if (LHS.isInvalid()) | ||||
13413 | return QualType(); | ||||
13414 | |||||
13415 | S.DiagnoseUnusedExprResult(LHS.get()); | ||||
13416 | |||||
13417 | if (!S.getLangOpts().CPlusPlus) { | ||||
13418 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13419 | if (RHS.isInvalid()) | ||||
13420 | return QualType(); | ||||
13421 | if (!RHS.get()->getType()->isVoidType()) | ||||
13422 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||
13423 | diag::err_incomplete_type); | ||||
13424 | } | ||||
13425 | |||||
13426 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||
13427 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||
13428 | |||||
13429 | return RHS.get()->getType(); | ||||
13430 | } | ||||
13431 | |||||
13432 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||
13433 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||
13434 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||
13435 | ExprValueKind &VK, | ||||
13436 | ExprObjectKind &OK, | ||||
13437 | SourceLocation OpLoc, | ||||
13438 | bool IsInc, bool IsPrefix) { | ||||
13439 | if (Op->isTypeDependent()) | ||||
13440 | return S.Context.DependentTy; | ||||
13441 | |||||
13442 | QualType ResType = Op->getType(); | ||||
13443 | // Atomic types can be used for increment / decrement where the non-atomic | ||||
13444 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||
13445 | // checking. | ||||
13446 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
13447 | ResType = ResAtomicType->getValueType(); | ||||
13448 | |||||
13449 | assert(!ResType.isNull() && "no type for increment/decrement expression")(static_cast <bool> (!ResType.isNull() && "no type for increment/decrement expression" ) ? void (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13449, __extension__ __PRETTY_FUNCTION__)); | ||||
13450 | |||||
13451 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||
13452 | // Decrement of bool is not allowed. | ||||
13453 | if (!IsInc) { | ||||
13454 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||
13455 | return QualType(); | ||||
13456 | } | ||||
13457 | // Increment of bool sets it to true, but is deprecated. | ||||
13458 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||
13459 | : diag::warn_increment_bool) | ||||
13460 | << Op->getSourceRange(); | ||||
13461 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||
13462 | // Error on enum increments and decrements in C++ mode | ||||
13463 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||
13464 | return QualType(); | ||||
13465 | } else if (ResType->isRealType()) { | ||||
13466 | // OK! | ||||
13467 | } else if (ResType->isPointerType()) { | ||||
13468 | // C99 6.5.2.4p2, 6.5.6p2 | ||||
13469 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||
13470 | return QualType(); | ||||
13471 | } else if (ResType->isObjCObjectPointerType()) { | ||||
13472 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||
13473 | // Otherwise, we just need a complete type. | ||||
13474 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||
13475 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||
13476 | return QualType(); | ||||
13477 | } else if (ResType->isAnyComplexType()) { | ||||
13478 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||
13479 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||
13480 | << ResType << Op->getSourceRange(); | ||||
13481 | } else if (ResType->isPlaceholderType()) { | ||||
13482 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13483 | if (PR.isInvalid()) return QualType(); | ||||
13484 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||
13485 | IsInc, IsPrefix); | ||||
13486 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||
13487 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||
13488 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||
13489 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||
13490 | VectorType::AltiVecBool)) { | ||||
13491 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||
13492 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||
13493 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||
13494 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||
13495 | } else { | ||||
13496 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||
13497 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||
13498 | return QualType(); | ||||
13499 | } | ||||
13500 | // At this point, we know we have a real, complex or pointer type. | ||||
13501 | // Now make sure the operand is a modifiable lvalue. | ||||
13502 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||
13503 | return QualType(); | ||||
13504 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||
13505 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||
13506 | // An operand with volatile-qualified type is deprecated | ||||
13507 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||
13508 | << IsInc << ResType; | ||||
13509 | } | ||||
13510 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||
13511 | // (in C or with postfix), the increment is the unqualified type of the | ||||
13512 | // operand. | ||||
13513 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||
13514 | VK = VK_LValue; | ||||
13515 | OK = Op->getObjectKind(); | ||||
13516 | return ResType; | ||||
13517 | } else { | ||||
13518 | VK = VK_PRValue; | ||||
13519 | return ResType.getUnqualifiedType(); | ||||
13520 | } | ||||
13521 | } | ||||
13522 | |||||
13523 | |||||
13524 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||
13525 | /// This routine allows us to typecheck complex/recursive expressions | ||||
13526 | /// where the declaration is needed for type checking. We only need to | ||||
13527 | /// handle cases when the expression references a function designator | ||||
13528 | /// or is an lvalue. Here are some examples: | ||||
13529 | /// - &(x) => x | ||||
13530 | /// - &*****f => f for f a function designator. | ||||
13531 | /// - &s.xx => s | ||||
13532 | /// - &s.zz[1].yy -> s, if zz is an array | ||||
13533 | /// - *(x + 1) -> x, if x is an array | ||||
13534 | /// - &"123"[2] -> 0 | ||||
13535 | /// - & __real__ x -> x | ||||
13536 | /// | ||||
13537 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||
13538 | /// members. | ||||
13539 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||
13540 | switch (E->getStmtClass()) { | ||||
13541 | case Stmt::DeclRefExprClass: | ||||
13542 | return cast<DeclRefExpr>(E)->getDecl(); | ||||
13543 | case Stmt::MemberExprClass: | ||||
13544 | // If this is an arrow operator, the address is an offset from | ||||
13545 | // the base's value, so the object the base refers to is | ||||
13546 | // irrelevant. | ||||
13547 | if (cast<MemberExpr>(E)->isArrow()) | ||||
13548 | return nullptr; | ||||
13549 | // Otherwise, the expression refers to a part of the base | ||||
13550 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||
13551 | case Stmt::ArraySubscriptExprClass: { | ||||
13552 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||
13553 | // promotion of register arrays earlier. | ||||
13554 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||
13555 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
13556 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||
13557 | return getPrimaryDecl(ICE->getSubExpr()); | ||||
13558 | } | ||||
13559 | return nullptr; | ||||
13560 | } | ||||
13561 | case Stmt::UnaryOperatorClass: { | ||||
13562 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||
13563 | |||||
13564 | switch(UO->getOpcode()) { | ||||
13565 | case UO_Real: | ||||
13566 | case UO_Imag: | ||||
13567 | case UO_Extension: | ||||
13568 | return getPrimaryDecl(UO->getSubExpr()); | ||||
13569 | default: | ||||
13570 | return nullptr; | ||||
13571 | } | ||||
13572 | } | ||||
13573 | case Stmt::ParenExprClass: | ||||
13574 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||
13575 | case Stmt::ImplicitCastExprClass: | ||||
13576 | // If the result of an implicit cast is an l-value, we care about | ||||
13577 | // the sub-expression; otherwise, the result here doesn't matter. | ||||
13578 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||
13579 | case Stmt::CXXUuidofExprClass: | ||||
13580 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||
13581 | default: | ||||
13582 | return nullptr; | ||||
13583 | } | ||||
13584 | } | ||||
13585 | |||||
13586 | namespace { | ||||
13587 | enum { | ||||
13588 | AO_Bit_Field = 0, | ||||
13589 | AO_Vector_Element = 1, | ||||
13590 | AO_Property_Expansion = 2, | ||||
13591 | AO_Register_Variable = 3, | ||||
13592 | AO_Matrix_Element = 4, | ||||
13593 | AO_No_Error = 5 | ||||
13594 | }; | ||||
13595 | } | ||||
13596 | /// Diagnose invalid operand for address of operations. | ||||
13597 | /// | ||||
13598 | /// \param Type The type of operand which cannot have its address taken. | ||||
13599 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||
13600 | Expr *E, unsigned Type) { | ||||
13601 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||
13602 | } | ||||
13603 | |||||
13604 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||
13605 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||
13606 | /// object cannot be declared with storage class register or be a bit field. | ||||
13607 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||
13608 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||
13609 | /// In C++, the operand might be an overloaded function name, in which case | ||||
13610 | /// we allow the '&' but retain the overloaded-function type. | ||||
13611 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||
13612 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||
13613 | if (PTy->getKind() == BuiltinType::Overload) { | ||||
13614 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||
13615 | if (!isa<OverloadExpr>(E)) { | ||||
13616 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode () == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13616, __extension__ __PRETTY_FUNCTION__)); | ||||
13617 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||
13618 | << OrigOp.get()->getSourceRange(); | ||||
13619 | return QualType(); | ||||
13620 | } | ||||
13621 | |||||
13622 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||
13623 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||
13624 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||
13625 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13626 | << OrigOp.get()->getSourceRange(); | ||||
13627 | return QualType(); | ||||
13628 | } | ||||
13629 | |||||
13630 | return Context.OverloadTy; | ||||
13631 | } | ||||
13632 | |||||
13633 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||
13634 | return Context.UnknownAnyTy; | ||||
13635 | |||||
13636 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||
13637 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13638 | << OrigOp.get()->getSourceRange(); | ||||
13639 | return QualType(); | ||||
13640 | } | ||||
13641 | |||||
13642 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||
13643 | if (OrigOp.isInvalid()) return QualType(); | ||||
13644 | } | ||||
13645 | |||||
13646 | if (OrigOp.get()->isTypeDependent()) | ||||
13647 | return Context.DependentTy; | ||||
13648 | |||||
13649 | assert(!OrigOp.get()->getType()->isPlaceholderType())(static_cast <bool> (!OrigOp.get()->getType()->isPlaceholderType ()) ? void (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13649, __extension__ __PRETTY_FUNCTION__)); | ||||
13650 | |||||
13651 | // Make sure to ignore parentheses in subsequent checks | ||||
13652 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||
13653 | |||||
13654 | // In OpenCL captures for blocks called as lambda functions | ||||
13655 | // are located in the private address space. Blocks used in | ||||
13656 | // enqueue_kernel can be located in a different address space | ||||
13657 | // depending on a vendor implementation. Thus preventing | ||||
13658 | // taking an address of the capture to avoid invalid AS casts. | ||||
13659 | if (LangOpts.OpenCL) { | ||||
13660 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||
13661 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||
13662 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||
13663 | return QualType(); | ||||
13664 | } | ||||
13665 | } | ||||
13666 | |||||
13667 | if (getLangOpts().C99) { | ||||
13668 | // Implement C99-only parts of addressof rules. | ||||
13669 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||
13670 | if (uOp->getOpcode() == UO_Deref) | ||||
13671 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||
13672 | // (assuming the deref expression is valid). | ||||
13673 | return uOp->getSubExpr()->getType(); | ||||
13674 | } | ||||
13675 | // Technically, there should be a check for array subscript | ||||
13676 | // expressions here, but the result of one is always an lvalue anyway. | ||||
13677 | } | ||||
13678 | ValueDecl *dcl = getPrimaryDecl(op); | ||||
13679 | |||||
13680 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||
13681 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
13682 | op->getBeginLoc())) | ||||
13683 | return QualType(); | ||||
13684 | |||||
13685 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||
13686 | unsigned AddressOfError = AO_No_Error; | ||||
13687 | |||||
13688 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||
13689 | bool sfinae = (bool)isSFINAEContext(); | ||||
13690 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||
13691 | : diag::ext_typecheck_addrof_temporary) | ||||
13692 | << op->getType() << op->getSourceRange(); | ||||
13693 | if (sfinae) | ||||
13694 | return QualType(); | ||||
13695 | // Materialize the temporary as an lvalue so that we can take its address. | ||||
13696 | OrigOp = op = | ||||
13697 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||
13698 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||
13699 | return Context.getPointerType(op->getType()); | ||||
13700 | } else if (lval == Expr::LV_MemberFunction) { | ||||
13701 | // If it's an instance method, make a member pointer. | ||||
13702 | // The expression must have exactly the form &A::foo. | ||||
13703 | |||||
13704 | // If the underlying expression isn't a decl ref, give up. | ||||
13705 | if (!isa<DeclRefExpr>(op)) { | ||||
13706 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13707 | << OrigOp.get()->getSourceRange(); | ||||
13708 | return QualType(); | ||||
13709 | } | ||||
13710 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||
13711 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||
13712 | |||||
13713 | // The id-expression was parenthesized. | ||||
13714 | if (OrigOp.get() != DRE) { | ||||
13715 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||
13716 | << OrigOp.get()->getSourceRange(); | ||||
13717 | |||||
13718 | // The method was named without a qualifier. | ||||
13719 | } else if (!DRE->getQualifier()) { | ||||
13720 | if (MD->getParent()->getName().empty()) | ||||
13721 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13722 | << op->getSourceRange(); | ||||
13723 | else { | ||||
13724 | SmallString<32> Str; | ||||
13725 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||
13726 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13727 | << op->getSourceRange() | ||||
13728 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||
13729 | } | ||||
13730 | } | ||||
13731 | |||||
13732 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||
13733 | if (isa<CXXDestructorDecl>(MD)) | ||||
13734 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||
13735 | |||||
13736 | QualType MPTy = Context.getMemberPointerType( | ||||
13737 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||
13738 | // Under the MS ABI, lock down the inheritance model now. | ||||
13739 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13740 | (void)isCompleteType(OpLoc, MPTy); | ||||
13741 | return MPTy; | ||||
13742 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||
13743 | // C99 6.5.3.2p1 | ||||
13744 | // The operand must be either an l-value or a function designator | ||||
13745 | if (!op->getType()->isFunctionType()) { | ||||
13746 | // Use a special diagnostic for loads from property references. | ||||
13747 | if (isa<PseudoObjectExpr>(op)) { | ||||
13748 | AddressOfError = AO_Property_Expansion; | ||||
13749 | } else { | ||||
13750 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||
13751 | << op->getType() << op->getSourceRange(); | ||||
13752 | return QualType(); | ||||
13753 | } | ||||
13754 | } | ||||
13755 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||
13756 | // The operand cannot be a bit-field | ||||
13757 | AddressOfError = AO_Bit_Field; | ||||
13758 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||
13759 | // The operand cannot be an element of a vector | ||||
13760 | AddressOfError = AO_Vector_Element; | ||||
13761 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||
13762 | // The operand cannot be an element of a matrix. | ||||
13763 | AddressOfError = AO_Matrix_Element; | ||||
13764 | } else if (dcl) { // C99 6.5.3.2p1 | ||||
13765 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||
13766 | // with the register storage-class specifier. | ||||
13767 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||
13768 | // in C++ it is not error to take address of a register | ||||
13769 | // variable (c++03 7.1.1P3) | ||||
13770 | if (vd->getStorageClass() == SC_Register && | ||||
13771 | !getLangOpts().CPlusPlus) { | ||||
13772 | AddressOfError = AO_Register_Variable; | ||||
13773 | } | ||||
13774 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||
13775 | AddressOfError = AO_Property_Expansion; | ||||
13776 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||
13777 | return Context.OverloadTy; | ||||
13778 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||
13779 | // Okay: we can take the address of a field. | ||||
13780 | // Could be a pointer to member, though, if there is an explicit | ||||
13781 | // scope qualifier for the class. | ||||
13782 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||
13783 | DeclContext *Ctx = dcl->getDeclContext(); | ||||
13784 | if (Ctx && Ctx->isRecord()) { | ||||
13785 | if (dcl->getType()->isReferenceType()) { | ||||
13786 | Diag(OpLoc, | ||||
13787 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||
13788 | << dcl->getDeclName() << dcl->getType(); | ||||
13789 | return QualType(); | ||||
13790 | } | ||||
13791 | |||||
13792 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||
13793 | Ctx = Ctx->getParent(); | ||||
13794 | |||||
13795 | QualType MPTy = Context.getMemberPointerType( | ||||
13796 | op->getType(), | ||||
13797 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||
13798 | // Under the MS ABI, lock down the inheritance model now. | ||||
13799 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13800 | (void)isCompleteType(OpLoc, MPTy); | ||||
13801 | return MPTy; | ||||
13802 | } | ||||
13803 | } | ||||
13804 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | ||||
13805 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | ||||
13806 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13806); | ||||
13807 | } | ||||
13808 | |||||
13809 | if (AddressOfError != AO_No_Error) { | ||||
13810 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||
13811 | return QualType(); | ||||
13812 | } | ||||
13813 | |||||
13814 | if (lval == Expr::LV_IncompleteVoidType) { | ||||
13815 | // Taking the address of a void variable is technically illegal, but we | ||||
13816 | // allow it in cases which are otherwise valid. | ||||
13817 | // Example: "extern void x; void* y = &x;". | ||||
13818 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||
13819 | } | ||||
13820 | |||||
13821 | // If the operand has type "type", the result has type "pointer to type". | ||||
13822 | if (op->getType()->isObjCObjectType()) | ||||
13823 | return Context.getObjCObjectPointerType(op->getType()); | ||||
13824 | |||||
13825 | CheckAddressOfPackedMember(op); | ||||
13826 | |||||
13827 | return Context.getPointerType(op->getType()); | ||||
13828 | } | ||||
13829 | |||||
13830 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||
13831 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||
13832 | if (!DRE) | ||||
13833 | return; | ||||
13834 | const Decl *D = DRE->getDecl(); | ||||
13835 | if (!D) | ||||
13836 | return; | ||||
13837 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||
13838 | if (!Param) | ||||
13839 | return; | ||||
13840 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||
13841 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||
13842 | return; | ||||
13843 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||
13844 | if (!FD->ModifiedNonNullParams.count(Param)) | ||||
13845 | FD->ModifiedNonNullParams.insert(Param); | ||||
13846 | } | ||||
13847 | |||||
13848 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||
13849 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||
13850 | SourceLocation OpLoc) { | ||||
13851 | if (Op->isTypeDependent()) | ||||
13852 | return S.Context.DependentTy; | ||||
13853 | |||||
13854 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||
13855 | if (ConvResult.isInvalid()) | ||||
13856 | return QualType(); | ||||
13857 | Op = ConvResult.get(); | ||||
13858 | QualType OpTy = Op->getType(); | ||||
13859 | QualType Result; | ||||
13860 | |||||
13861 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||
13862 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||
13863 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||
13864 | Op->getSourceRange()); | ||||
13865 | } | ||||
13866 | |||||
13867 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||
13868 | { | ||||
13869 | Result = PT->getPointeeType(); | ||||
13870 | } | ||||
13871 | else if (const ObjCObjectPointerType *OPT = | ||||
13872 | OpTy->getAs<ObjCObjectPointerType>()) | ||||
13873 | Result = OPT->getPointeeType(); | ||||
13874 | else { | ||||
13875 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13876 | if (PR.isInvalid()) return QualType(); | ||||
13877 | if (PR.get() != Op) | ||||
13878 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||
13879 | } | ||||
13880 | |||||
13881 | if (Result.isNull()) { | ||||
13882 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||
13883 | << OpTy << Op->getSourceRange(); | ||||
13884 | return QualType(); | ||||
13885 | } | ||||
13886 | |||||
13887 | // Note that per both C89 and C99, indirection is always legal, even if Result | ||||
13888 | // is an incomplete type or void. It would be possible to warn about | ||||
13889 | // dereferencing a void pointer, but it's completely well-defined, and such a | ||||
13890 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | ||||
13891 | // for pointers to 'void' but is fine for any other pointer type: | ||||
13892 | // | ||||
13893 | // C++ [expr.unary.op]p1: | ||||
13894 | // [...] the expression to which [the unary * operator] is applied shall | ||||
13895 | // be a pointer to an object type, or a pointer to a function type | ||||
13896 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | ||||
13897 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||
13898 | << OpTy << Op->getSourceRange(); | ||||
13899 | |||||
13900 | // Dereferences are usually l-values... | ||||
13901 | VK = VK_LValue; | ||||
13902 | |||||
13903 | // ...except that certain expressions are never l-values in C. | ||||
13904 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||
13905 | VK = VK_PRValue; | ||||
13906 | |||||
13907 | return Result; | ||||
13908 | } | ||||
13909 | |||||
13910 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||
13911 | BinaryOperatorKind Opc; | ||||
13912 | switch (Kind) { | ||||
13913 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13913); | ||||
13914 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||
13915 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||
13916 | case tok::star: Opc = BO_Mul; break; | ||||
13917 | case tok::slash: Opc = BO_Div; break; | ||||
13918 | case tok::percent: Opc = BO_Rem; break; | ||||
13919 | case tok::plus: Opc = BO_Add; break; | ||||
13920 | case tok::minus: Opc = BO_Sub; break; | ||||
13921 | case tok::lessless: Opc = BO_Shl; break; | ||||
13922 | case tok::greatergreater: Opc = BO_Shr; break; | ||||
13923 | case tok::lessequal: Opc = BO_LE; break; | ||||
13924 | case tok::less: Opc = BO_LT; break; | ||||
13925 | case tok::greaterequal: Opc = BO_GE; break; | ||||
13926 | case tok::greater: Opc = BO_GT; break; | ||||
13927 | case tok::exclaimequal: Opc = BO_NE; break; | ||||
13928 | case tok::equalequal: Opc = BO_EQ; break; | ||||
13929 | case tok::spaceship: Opc = BO_Cmp; break; | ||||
13930 | case tok::amp: Opc = BO_And; break; | ||||
13931 | case tok::caret: Opc = BO_Xor; break; | ||||
13932 | case tok::pipe: Opc = BO_Or; break; | ||||
13933 | case tok::ampamp: Opc = BO_LAnd; break; | ||||
13934 | case tok::pipepipe: Opc = BO_LOr; break; | ||||
13935 | case tok::equal: Opc = BO_Assign; break; | ||||
13936 | case tok::starequal: Opc = BO_MulAssign; break; | ||||
13937 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||
13938 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||
13939 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||
13940 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||
13941 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||
13942 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||
13943 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||
13944 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||
13945 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||
13946 | case tok::comma: Opc = BO_Comma; break; | ||||
13947 | } | ||||
13948 | return Opc; | ||||
13949 | } | ||||
13950 | |||||
13951 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||
13952 | tok::TokenKind Kind) { | ||||
13953 | UnaryOperatorKind Opc; | ||||
13954 | switch (Kind) { | ||||
13955 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 13955); | ||||
13956 | case tok::plusplus: Opc = UO_PreInc; break; | ||||
13957 | case tok::minusminus: Opc = UO_PreDec; break; | ||||
13958 | case tok::amp: Opc = UO_AddrOf; break; | ||||
13959 | case tok::star: Opc = UO_Deref; break; | ||||
13960 | case tok::plus: Opc = UO_Plus; break; | ||||
13961 | case tok::minus: Opc = UO_Minus; break; | ||||
13962 | case tok::tilde: Opc = UO_Not; break; | ||||
13963 | case tok::exclaim: Opc = UO_LNot; break; | ||||
13964 | case tok::kw___real: Opc = UO_Real; break; | ||||
13965 | case tok::kw___imag: Opc = UO_Imag; break; | ||||
13966 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||
13967 | } | ||||
13968 | return Opc; | ||||
13969 | } | ||||
13970 | |||||
13971 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||
13972 | /// This warning suppressed in the event of macro expansions. | ||||
13973 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||
13974 | SourceLocation OpLoc, bool IsBuiltin) { | ||||
13975 | if (S.inTemplateInstantiation()) | ||||
13976 | return; | ||||
13977 | if (S.isUnevaluatedContext()) | ||||
13978 | return; | ||||
13979 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||
13980 | return; | ||||
13981 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||
13982 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||
13983 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||
13984 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||
13985 | if (!LHSDeclRef || !RHSDeclRef || | ||||
13986 | LHSDeclRef->getLocation().isMacroID() || | ||||
13987 | RHSDeclRef->getLocation().isMacroID()) | ||||
13988 | return; | ||||
13989 | const ValueDecl *LHSDecl = | ||||
13990 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13991 | const ValueDecl *RHSDecl = | ||||
13992 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13993 | if (LHSDecl != RHSDecl) | ||||
13994 | return; | ||||
13995 | if (LHSDecl->getType().isVolatileQualified()) | ||||
13996 | return; | ||||
13997 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
13998 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
13999 | return; | ||||
14000 | |||||
14001 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||
14002 | : diag::warn_self_assignment_overloaded) | ||||
14003 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||
14004 | << RHSExpr->getSourceRange(); | ||||
14005 | } | ||||
14006 | |||||
14007 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||
14008 | /// is usually indicative of introspection within the Objective-C pointer. | ||||
14009 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||
14010 | SourceLocation OpLoc) { | ||||
14011 | if (!S.getLangOpts().ObjC) | ||||
14012 | return; | ||||
14013 | |||||
14014 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||
14015 | const Expr *LHS = L.get(); | ||||
14016 | const Expr *RHS = R.get(); | ||||
14017 | |||||
14018 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14019 | ObjCPointerExpr = LHS; | ||||
14020 | OtherExpr = RHS; | ||||
14021 | } | ||||
14022 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
14023 | ObjCPointerExpr = RHS; | ||||
14024 | OtherExpr = LHS; | ||||
14025 | } | ||||
14026 | |||||
14027 | // This warning is deliberately made very specific to reduce false | ||||
14028 | // positives with logic that uses '&' for hashing. This logic mainly | ||||
14029 | // looks for code trying to introspect into tagged pointers, which | ||||
14030 | // code should generally never do. | ||||
14031 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||
14032 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||
14033 | // Determine if we are introspecting the result of performSelectorXXX. | ||||
14034 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||
14035 | // Special case messages to -performSelector and friends, which | ||||
14036 | // can return non-pointer values boxed in a pointer value. | ||||
14037 | // Some clients may wish to silence warnings in this subcase. | ||||
14038 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||
14039 | Selector S = ME->getSelector(); | ||||
14040 | StringRef SelArg0 = S.getNameForSlot(0); | ||||
14041 | if (SelArg0.startswith("performSelector")) | ||||
14042 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||
14043 | } | ||||
14044 | |||||
14045 | S.Diag(OpLoc, Diag) | ||||
14046 | << ObjCPointerExpr->getSourceRange(); | ||||
14047 | } | ||||
14048 | } | ||||
14049 | |||||
14050 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||
14051 | if (!E) | ||||
14052 | return nullptr; | ||||
14053 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
14054 | return DRE->getDecl(); | ||||
14055 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||
14056 | return ME->getMemberDecl(); | ||||
14057 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||
14058 | return IRE->getDecl(); | ||||
14059 | return nullptr; | ||||
14060 | } | ||||
14061 | |||||
14062 | // This helper function promotes a binary operator's operands (which are of a | ||||
14063 | // half vector type) to a vector of floats and then truncates the result to | ||||
14064 | // a vector of either half or short. | ||||
14065 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||
14066 | BinaryOperatorKind Opc, QualType ResultTy, | ||||
14067 | ExprValueKind VK, ExprObjectKind OK, | ||||
14068 | bool IsCompAssign, SourceLocation OpLoc, | ||||
14069 | FPOptionsOverride FPFeatures) { | ||||
14070 | auto &Context = S.getASTContext(); | ||||
14071 | assert((isVector(ResultTy, Context.HalfTy) ||(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14073, __extension__ __PRETTY_FUNCTION__)) | ||||
14072 | isVector(ResultTy, Context.ShortTy)) &&(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14073, __extension__ __PRETTY_FUNCTION__)) | ||||
14073 | "Result must be a vector of half or short")(static_cast <bool> ((isVector(ResultTy, Context.HalfTy ) || isVector(ResultTy, Context.ShortTy)) && "Result must be a vector of half or short" ) ? void (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14073, __extension__ __PRETTY_FUNCTION__)); | ||||
14074 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14076, __extension__ __PRETTY_FUNCTION__)) | ||||
14075 | isVector(RHS.get()->getType(), Context.HalfTy) &&(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14076, __extension__ __PRETTY_FUNCTION__)) | ||||
14076 | "both operands expected to be a half vector")(static_cast <bool> (isVector(LHS.get()->getType(), Context .HalfTy) && isVector(RHS.get()->getType(), Context .HalfTy) && "both operands expected to be a half vector" ) ? void (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14076, __extension__ __PRETTY_FUNCTION__)); | ||||
14077 | |||||
14078 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||
14079 | QualType BinOpResTy = RHS.get()->getType(); | ||||
14080 | |||||
14081 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||
14082 | // change BinOpResTy to a vector of ints. | ||||
14083 | if (isVector(ResultTy, Context.ShortTy)) | ||||
14084 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||
14085 | |||||
14086 | if (IsCompAssign) | ||||
14087 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
14088 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||
14089 | BinOpResTy, BinOpResTy); | ||||
14090 | |||||
14091 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||
14092 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
14093 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||
14094 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||
14095 | } | ||||
14096 | |||||
14097 | static std::pair<ExprResult, ExprResult> | ||||
14098 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||
14099 | Expr *RHSExpr) { | ||||
14100 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
14101 | if (!S.Context.isDependenceAllowed()) { | ||||
14102 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
14103 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
14104 | // been dealt with before checking the operands. | ||||
14105 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||
14106 | RHS = S.CorrectDelayedTyposInExpr( | ||||
14107 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||
14108 | [Opc, LHS](Expr *E) { | ||||
14109 | if (Opc != BO_Assign) | ||||
14110 | return ExprResult(E); | ||||
14111 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||
14112 | Decl *D = getDeclFromExpr(E); | ||||
14113 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||
14114 | }); | ||||
14115 | } | ||||
14116 | return std::make_pair(LHS, RHS); | ||||
14117 | } | ||||
14118 | |||||
14119 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||
14120 | /// is needed. | ||||
14121 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||
14122 | Expr *E0, Expr *E1 = nullptr) { | ||||
14123 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||
14124 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||
14125 | return false; | ||||
14126 | |||||
14127 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||
14128 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||
14129 | |||||
14130 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||
14131 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||
14132 | // the vectors shouldn't be treated as storage-only types. See the | ||||
14133 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||
14134 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||
14135 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||
14136 | return false; | ||||
14137 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||
14138 | } | ||||
14139 | return false; | ||||
14140 | }; | ||||
14141 | |||||
14142 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||
14143 | } | ||||
14144 | |||||
14145 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||
14146 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||
14147 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||
14148 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||
14149 | BinaryOperatorKind Opc, | ||||
14150 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14151 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||
14152 | // The syntax only allows initializer lists on the RHS of assignment, | ||||
14153 | // so we don't need to worry about accepting invalid code for | ||||
14154 | // non-assignment operators. | ||||
14155 | // C++11 5.17p9: | ||||
14156 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||
14157 | // of x = {} is x = T(). | ||||
14158 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
14159 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
14160 | InitializedEntity Entity = | ||||
14161 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||
14162 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||
14163 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||
14164 | if (Init.isInvalid()) | ||||
14165 | return Init; | ||||
14166 | RHSExpr = Init.get(); | ||||
14167 | } | ||||
14168 | |||||
14169 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
14170 | QualType ResultTy; // Result type of the binary operator. | ||||
14171 | // The following two variables are used for compound assignment operators | ||||
14172 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||
14173 | QualType CompResultTy; // Type of computation result | ||||
14174 | ExprValueKind VK = VK_PRValue; | ||||
14175 | ExprObjectKind OK = OK_Ordinary; | ||||
14176 | bool ConvertHalfVec = false; | ||||
14177 | |||||
14178 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
14179 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
14180 | return ExprError(); | ||||
14181 | |||||
14182 | if (getLangOpts().OpenCL) { | ||||
14183 | QualType LHSTy = LHSExpr->getType(); | ||||
14184 | QualType RHSTy = RHSExpr->getType(); | ||||
14185 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||
14186 | // the ATOMIC_VAR_INIT macro. | ||||
14187 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||
14188 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
14189 | if (BO_Assign == Opc) | ||||
14190 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||
14191 | else | ||||
14192 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
14193 | return ExprError(); | ||||
14194 | } | ||||
14195 | |||||
14196 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
14197 | // only with a builtin functions and therefore should be disallowed here. | ||||
14198 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||
14199 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||
14200 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||
14201 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||
14202 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
14203 | return ExprError(); | ||||
14204 | } | ||||
14205 | } | ||||
14206 | |||||
14207 | switch (Opc) { | ||||
14208 | case BO_Assign: | ||||
14209 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | ||||
14210 | if (getLangOpts().CPlusPlus && | ||||
14211 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||
14212 | VK = LHS.get()->getValueKind(); | ||||
14213 | OK = LHS.get()->getObjectKind(); | ||||
14214 | } | ||||
14215 | if (!ResultTy.isNull()) { | ||||
14216 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
14217 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||
14218 | |||||
14219 | // Avoid copying a block to the heap if the block is assigned to a local | ||||
14220 | // auto variable that is declared in the same scope as the block. This | ||||
14221 | // optimization is unsafe if the local variable is declared in an outer | ||||
14222 | // scope. For example: | ||||
14223 | // | ||||
14224 | // BlockTy b; | ||||
14225 | // { | ||||
14226 | // b = ^{...}; | ||||
14227 | // } | ||||
14228 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||
14229 | // // heap. | ||||
14230 | // b(); | ||||
14231 | |||||
14232 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||
14233 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||
14234 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||
14235 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||
14236 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
14237 | |||||
14238 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
14239 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||
14240 | NTCUC_Assignment, NTCUK_Copy); | ||||
14241 | } | ||||
14242 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||
14243 | break; | ||||
14244 | case BO_PtrMemD: | ||||
14245 | case BO_PtrMemI: | ||||
14246 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||
14247 | Opc == BO_PtrMemI); | ||||
14248 | break; | ||||
14249 | case BO_Mul: | ||||
14250 | case BO_Div: | ||||
14251 | ConvertHalfVec = true; | ||||
14252 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||
14253 | Opc == BO_Div); | ||||
14254 | break; | ||||
14255 | case BO_Rem: | ||||
14256 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||
14257 | break; | ||||
14258 | case BO_Add: | ||||
14259 | ConvertHalfVec = true; | ||||
14260 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||
14261 | break; | ||||
14262 | case BO_Sub: | ||||
14263 | ConvertHalfVec = true; | ||||
14264 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||
14265 | break; | ||||
14266 | case BO_Shl: | ||||
14267 | case BO_Shr: | ||||
14268 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||
14269 | break; | ||||
14270 | case BO_LE: | ||||
14271 | case BO_LT: | ||||
14272 | case BO_GE: | ||||
14273 | case BO_GT: | ||||
14274 | ConvertHalfVec = true; | ||||
14275 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14276 | break; | ||||
14277 | case BO_EQ: | ||||
14278 | case BO_NE: | ||||
14279 | ConvertHalfVec = true; | ||||
14280 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14281 | break; | ||||
14282 | case BO_Cmp: | ||||
14283 | ConvertHalfVec = true; | ||||
14284 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
14285 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())(static_cast <bool> (ResultTy.isNull() || ResultTy-> getAsCXXRecordDecl()) ? void (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14285, __extension__ __PRETTY_FUNCTION__)); | ||||
14286 | break; | ||||
14287 | case BO_And: | ||||
14288 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||
14289 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14290 | case BO_Xor: | ||||
14291 | case BO_Or: | ||||
14292 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14293 | break; | ||||
14294 | case BO_LAnd: | ||||
14295 | case BO_LOr: | ||||
14296 | ConvertHalfVec = true; | ||||
14297 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||
14298 | break; | ||||
14299 | case BO_MulAssign: | ||||
14300 | case BO_DivAssign: | ||||
14301 | ConvertHalfVec = true; | ||||
14302 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||
14303 | Opc == BO_DivAssign); | ||||
14304 | CompLHSTy = CompResultTy; | ||||
14305 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14306 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14307 | break; | ||||
14308 | case BO_RemAssign: | ||||
14309 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||
14310 | CompLHSTy = CompResultTy; | ||||
14311 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14312 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14313 | break; | ||||
14314 | case BO_AddAssign: | ||||
14315 | ConvertHalfVec = true; | ||||
14316 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||
14317 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14318 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14319 | break; | ||||
14320 | case BO_SubAssign: | ||||
14321 | ConvertHalfVec = true; | ||||
14322 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||
14323 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14324 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14325 | break; | ||||
14326 | case BO_ShlAssign: | ||||
14327 | case BO_ShrAssign: | ||||
14328 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||
14329 | CompLHSTy = CompResultTy; | ||||
14330 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14331 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14332 | break; | ||||
14333 | case BO_AndAssign: | ||||
14334 | case BO_OrAssign: // fallthrough | ||||
14335 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
14336 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14337 | case BO_XorAssign: | ||||
14338 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14339 | CompLHSTy = CompResultTy; | ||||
14340 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14341 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14342 | break; | ||||
14343 | case BO_Comma: | ||||
14344 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||
14345 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||
14346 | VK = RHS.get()->getValueKind(); | ||||
14347 | OK = RHS.get()->getObjectKind(); | ||||
14348 | } | ||||
14349 | break; | ||||
14350 | } | ||||
14351 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||
14352 | return ExprError(); | ||||
14353 | |||||
14354 | // Some of the binary operations require promoting operands of half vector to | ||||
14355 | // float vectors and truncating the result back to half vector. For now, we do | ||||
14356 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||
14357 | // arm64). | ||||
14358 | assert((static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14361, __extension__ __PRETTY_FUNCTION__)) | ||||
14359 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14361, __extension__ __PRETTY_FUNCTION__)) | ||||
14360 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14361, __extension__ __PRETTY_FUNCTION__)) | ||||
14361 | "both sides are half vectors or neither sides are")(static_cast <bool> ((Opc == BO_Comma || isVector(RHS.get ()->getType(), Context.HalfTy) == isVector(LHS.get()->getType (), Context.HalfTy)) && "both sides are half vectors or neither sides are" ) ? void (0) : __assert_fail ("(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy)) && \"both sides are half vectors or neither sides are\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14361, __extension__ __PRETTY_FUNCTION__)); | ||||
14362 | ConvertHalfVec = | ||||
14363 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||
14364 | |||||
14365 | // Check for array bounds violations for both sides of the BinaryOperator | ||||
14366 | CheckArrayAccess(LHS.get()); | ||||
14367 | CheckArrayAccess(RHS.get()); | ||||
14368 | |||||
14369 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||
14370 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||
14371 | &Context.Idents.get("object_setClass"), | ||||
14372 | SourceLocation(), LookupOrdinaryName); | ||||
14373 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||
14374 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
14375 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||
14376 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||
14377 | "object_setClass(") | ||||
14378 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||
14379 | ",") | ||||
14380 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
14381 | } | ||||
14382 | else | ||||
14383 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||
14384 | } | ||||
14385 | else if (const ObjCIvarRefExpr *OIRE = | ||||
14386 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||
14387 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||
14388 | |||||
14389 | // Opc is not a compound assignment if CompResultTy is null. | ||||
14390 | if (CompResultTy.isNull()) { | ||||
14391 | if (ConvertHalfVec) | ||||
14392 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||
14393 | OpLoc, CurFPFeatureOverrides()); | ||||
14394 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||
14395 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||
14396 | } | ||||
14397 | |||||
14398 | // Handle compound assignments. | ||||
14399 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||
14400 | OK_ObjCProperty) { | ||||
14401 | VK = VK_LValue; | ||||
14402 | OK = LHS.get()->getObjectKind(); | ||||
14403 | } | ||||
14404 | |||||
14405 | // The LHS is not converted to the result type for fixed-point compound | ||||
14406 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||
14407 | // to the LHS type we would have gotten after unary conversions. | ||||
14408 | if (CompResultTy->isFixedPointType()) | ||||
14409 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||
14410 | |||||
14411 | if (ConvertHalfVec) | ||||
14412 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||
14413 | OpLoc, CurFPFeatureOverrides()); | ||||
14414 | |||||
14415 | return CompoundAssignOperator::Create( | ||||
14416 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||
14417 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||
14418 | } | ||||
14419 | |||||
14420 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||
14421 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||
14422 | /// comparison operators have higher precedence. The most typical example of | ||||
14423 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||
14424 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14425 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14426 | Expr *RHSExpr) { | ||||
14427 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||
14428 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||
14429 | |||||
14430 | // Check that one of the sides is a comparison operator and the other isn't. | ||||
14431 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||
14432 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||
14433 | if (isLeftComp == isRightComp) | ||||
14434 | return; | ||||
14435 | |||||
14436 | // Bitwise operations are sometimes used as eager logical ops. | ||||
14437 | // Don't diagnose this. | ||||
14438 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||
14439 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||
14440 | if (isLeftBitwise || isRightBitwise) | ||||
14441 | return; | ||||
14442 | |||||
14443 | SourceRange DiagRange = isLeftComp | ||||
14444 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||
14445 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||
14446 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||
14447 | SourceRange ParensRange = | ||||
14448 | isLeftComp | ||||
14449 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||
14450 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||
14451 | |||||
14452 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||
14453 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||
14454 | SuggestParentheses(Self, OpLoc, | ||||
14455 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||
14456 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||
14457 | SuggestParentheses(Self, OpLoc, | ||||
14458 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||
14459 | << BinaryOperator::getOpcodeStr(Opc), | ||||
14460 | ParensRange); | ||||
14461 | } | ||||
14462 | |||||
14463 | /// It accepts a '&&' expr that is inside a '||' one. | ||||
14464 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||
14465 | /// in parentheses. | ||||
14466 | static void | ||||
14467 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||
14468 | BinaryOperator *Bop) { | ||||
14469 | assert(Bop->getOpcode() == BO_LAnd)(static_cast <bool> (Bop->getOpcode() == BO_LAnd) ? void (0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14469, __extension__ __PRETTY_FUNCTION__)); | ||||
14470 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||
14471 | << Bop->getSourceRange() << OpLoc; | ||||
14472 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||
14473 | Self.PDiag(diag::note_precedence_silence) | ||||
14474 | << Bop->getOpcodeStr(), | ||||
14475 | Bop->getSourceRange()); | ||||
14476 | } | ||||
14477 | |||||
14478 | /// Returns true if the given expression can be evaluated as a constant | ||||
14479 | /// 'true'. | ||||
14480 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | ||||
14481 | bool Res; | ||||
14482 | return !E->isValueDependent() && | ||||
14483 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | ||||
14484 | } | ||||
14485 | |||||
14486 | /// Returns true if the given expression can be evaluated as a constant | ||||
14487 | /// 'false'. | ||||
14488 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | ||||
14489 | bool Res; | ||||
14490 | return !E->isValueDependent() && | ||||
14491 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | ||||
14492 | } | ||||
14493 | |||||
14494 | /// Look for '&&' in the left hand of a '||' expr. | ||||
14495 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||
14496 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14497 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||
14498 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14499 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | ||||
14500 | if (EvaluatesAsFalse(S, RHSExpr)) | ||||
14501 | return; | ||||
14502 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | ||||
14503 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | ||||
14504 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14505 | } else if (Bop->getOpcode() == BO_LOr) { | ||||
14506 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||
14507 | // If it's "a || b && 1 || c" we didn't warn earlier for | ||||
14508 | // "a || b && 1", but warn now. | ||||
14509 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | ||||
14510 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||
14511 | } | ||||
14512 | } | ||||
14513 | } | ||||
14514 | } | ||||
14515 | |||||
14516 | /// Look for '&&' in the right hand of a '||' expr. | ||||
14517 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||
14518 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14519 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||
14520 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14521 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | ||||
14522 | if (EvaluatesAsFalse(S, LHSExpr)) | ||||
14523 | return; | ||||
14524 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | ||||
14525 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | ||||
14526 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14527 | } | ||||
14528 | } | ||||
14529 | } | ||||
14530 | |||||
14531 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||
14532 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||
14533 | /// the '&' expression in parentheses. | ||||
14534 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||
14535 | SourceLocation OpLoc, Expr *SubExpr) { | ||||
14536 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14537 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||
14538 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||
14539 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||
14540 | << Bop->getSourceRange() << OpLoc; | ||||
14541 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14542 | S.PDiag(diag::note_precedence_silence) | ||||
14543 | << Bop->getOpcodeStr(), | ||||
14544 | Bop->getSourceRange()); | ||||
14545 | } | ||||
14546 | } | ||||
14547 | } | ||||
14548 | |||||
14549 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||
14550 | Expr *SubExpr, StringRef Shift) { | ||||
14551 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14552 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||
14553 | StringRef Op = Bop->getOpcodeStr(); | ||||
14554 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||
14555 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||
14556 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14557 | S.PDiag(diag::note_precedence_silence) << Op, | ||||
14558 | Bop->getSourceRange()); | ||||
14559 | } | ||||
14560 | } | ||||
14561 | } | ||||
14562 | |||||
14563 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||
14564 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14565 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||
14566 | if (!OCE) | ||||
14567 | return; | ||||
14568 | |||||
14569 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||
14570 | if (!FD || !FD->isOverloadedOperator()) | ||||
14571 | return; | ||||
14572 | |||||
14573 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||
14574 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||
14575 | return; | ||||
14576 | |||||
14577 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||
14578 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||
14579 | << (Kind == OO_LessLess); | ||||
14580 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||
14581 | S.PDiag(diag::note_precedence_silence) | ||||
14582 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||
14583 | OCE->getSourceRange()); | ||||
14584 | SuggestParentheses( | ||||
14585 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||
14586 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
14587 | } | ||||
14588 | |||||
14589 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||
14590 | /// precedence. | ||||
14591 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14592 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14593 | Expr *RHSExpr){ | ||||
14594 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||
14595 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||
14596 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||
14597 | |||||
14598 | // Diagnose "arg1 & arg2 | arg3" | ||||
14599 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||
14600 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14601 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||
14602 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||
14603 | } | ||||
14604 | |||||
14605 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||
14606 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||
14607 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14608 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14609 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14610 | } | ||||
14611 | |||||
14612 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||
14613 | || Opc == BO_Shr) { | ||||
14614 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||
14615 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||
14616 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||
14617 | } | ||||
14618 | |||||
14619 | // Warn on overloaded shift operators and comparisons, such as: | ||||
14620 | // cout << 5 == 4; | ||||
14621 | if (BinaryOperator::isComparisonOp(Opc)) | ||||
14622 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14623 | } | ||||
14624 | |||||
14625 | // Binary Operators. 'Tok' is the token for the operator. | ||||
14626 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||
14627 | tok::TokenKind Kind, | ||||
14628 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14629 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||
14630 | assert(LHSExpr && "ActOnBinOp(): missing left expression")(static_cast <bool> (LHSExpr && "ActOnBinOp(): missing left expression" ) ? void (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14630, __extension__ __PRETTY_FUNCTION__)); | ||||
14631 | assert(RHSExpr && "ActOnBinOp(): missing right expression")(static_cast <bool> (RHSExpr && "ActOnBinOp(): missing right expression" ) ? void (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14631, __extension__ __PRETTY_FUNCTION__)); | ||||
14632 | |||||
14633 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||
14634 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||
14635 | |||||
14636 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||
14637 | } | ||||
14638 | |||||
14639 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||
14640 | UnresolvedSetImpl &Functions) { | ||||
14641 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||
14642 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||
14643 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
14644 | |||||
14645 | // In C++20 onwards, we may have a second operator to look up. | ||||
14646 | if (getLangOpts().CPlusPlus20) { | ||||
14647 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||
14648 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||
14649 | } | ||||
14650 | } | ||||
14651 | |||||
14652 | /// Build an overloaded binary operator expression in the given scope. | ||||
14653 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||
14654 | BinaryOperatorKind Opc, | ||||
14655 | Expr *LHS, Expr *RHS) { | ||||
14656 | switch (Opc) { | ||||
14657 | case BO_Assign: | ||||
14658 | case BO_DivAssign: | ||||
14659 | case BO_RemAssign: | ||||
14660 | case BO_SubAssign: | ||||
14661 | case BO_AndAssign: | ||||
14662 | case BO_OrAssign: | ||||
14663 | case BO_XorAssign: | ||||
14664 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||
14665 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||
14666 | break; | ||||
14667 | default: | ||||
14668 | break; | ||||
14669 | } | ||||
14670 | |||||
14671 | // Find all of the overloaded operators visible from this point. | ||||
14672 | UnresolvedSet<16> Functions; | ||||
14673 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||
14674 | |||||
14675 | // Build the (potentially-overloaded, potentially-dependent) | ||||
14676 | // binary operation. | ||||
14677 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||
14678 | } | ||||
14679 | |||||
14680 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||
14681 | BinaryOperatorKind Opc, | ||||
14682 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14683 | ExprResult LHS, RHS; | ||||
14684 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
14685 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
14686 | return ExprError(); | ||||
14687 | LHSExpr = LHS.get(); | ||||
14688 | RHSExpr = RHS.get(); | ||||
14689 | |||||
14690 | // We want to end up calling one of checkPseudoObjectAssignment | ||||
14691 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||
14692 | // both expressions are overloadable or either is type-dependent), | ||||
14693 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||
14694 | // any placeholder types out of the way. | ||||
14695 | |||||
14696 | // Handle pseudo-objects in the LHS. | ||||
14697 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||
14698 | // Assignments with a pseudo-object l-value need special analysis. | ||||
14699 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
14700 | BinaryOperator::isAssignmentOp(Opc)) | ||||
14701 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14702 | |||||
14703 | // Don't resolve overloads if the other type is overloadable. | ||||
14704 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||
14705 | // We can't actually test that if we still have a placeholder, | ||||
14706 | // though. Fortunately, none of the exceptions we see in that | ||||
14707 | // code below are valid when the LHS is an overload set. Note | ||||
14708 | // that an overload set can be dependently-typed, but it never | ||||
14709 | // instantiates to having an overloadable type. | ||||
14710 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14711 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||
14712 | RHSExpr = resolvedRHS.get(); | ||||
14713 | |||||
14714 | if (RHSExpr->isTypeDependent() || | ||||
14715 | RHSExpr->getType()->isOverloadableType()) | ||||
14716 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14717 | } | ||||
14718 | |||||
14719 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||
14720 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||
14721 | // an invalid use of a bound member function. | ||||
14722 | // | ||||
14723 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||
14724 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||
14725 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||
14726 | (pty->getKind() == BuiltinType::BoundMember || | ||||
14727 | pty->getKind() == BuiltinType::Overload)) { | ||||
14728 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||
14729 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||
14730 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | ||||
14731 | return isa<FunctionTemplateDecl>(ND); | ||||
14732 | })) { | ||||
14733 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||
14734 | : OE->getNameLoc(), | ||||
14735 | diag::err_template_kw_missing) | ||||
14736 | << OE->getName().getAsString() << ""; | ||||
14737 | return ExprError(); | ||||
14738 | } | ||||
14739 | } | ||||
14740 | |||||
14741 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||
14742 | if (LHS.isInvalid()) return ExprError(); | ||||
14743 | LHSExpr = LHS.get(); | ||||
14744 | } | ||||
14745 | |||||
14746 | // Handle pseudo-objects in the RHS. | ||||
14747 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||
14748 | // An overload in the RHS can potentially be resolved by the type | ||||
14749 | // being assigned to. | ||||
14750 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||
14751 | if (getLangOpts().CPlusPlus && | ||||
14752 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||
14753 | LHSExpr->getType()->isOverloadableType())) | ||||
14754 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14755 | |||||
14756 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14757 | } | ||||
14758 | |||||
14759 | // Don't resolve overloads if the other type is overloadable. | ||||
14760 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||
14761 | LHSExpr->getType()->isOverloadableType()) | ||||
14762 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14763 | |||||
14764 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14765 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||
14766 | RHSExpr = resolvedRHS.get(); | ||||
14767 | } | ||||
14768 | |||||
14769 | if (getLangOpts().CPlusPlus) { | ||||
14770 | // If either expression is type-dependent, always build an | ||||
14771 | // overloaded op. | ||||
14772 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||
14773 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14774 | |||||
14775 | // Otherwise, build an overloaded op if either expression has an | ||||
14776 | // overloadable type. | ||||
14777 | if (LHSExpr->getType()->isOverloadableType() || | ||||
14778 | RHSExpr->getType()->isOverloadableType()) | ||||
14779 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14780 | } | ||||
14781 | |||||
14782 | if (getLangOpts().RecoveryAST && | ||||
14783 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||
14784 | assert(!getLangOpts().CPlusPlus)(static_cast <bool> (!getLangOpts().CPlusPlus) ? void ( 0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14784, __extension__ __PRETTY_FUNCTION__)); | ||||
14785 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14786, __extension__ __PRETTY_FUNCTION__)) | ||||
14786 | "Should only occur in error-recovery path.")(static_cast <bool> ((LHSExpr->containsErrors() || RHSExpr ->containsErrors()) && "Should only occur in error-recovery path." ) ? void (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 14786, __extension__ __PRETTY_FUNCTION__)); | ||||
14787 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||
14788 | // C [6.15.16] p3: | ||||
14789 | // An assignment expression has the value of the left operand after the | ||||
14790 | // assignment, but is not an lvalue. | ||||
14791 | return CompoundAssignOperator::Create( | ||||
14792 | Context, LHSExpr, RHSExpr, Opc, | ||||
14793 | LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, | ||||
14794 | OpLoc, CurFPFeatureOverrides()); | ||||
14795 | QualType ResultType; | ||||
14796 | switch (Opc) { | ||||
14797 | case BO_Assign: | ||||
14798 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||
14799 | break; | ||||
14800 | case BO_LT: | ||||
14801 | case BO_GT: | ||||
14802 | case BO_LE: | ||||
14803 | case BO_GE: | ||||
14804 | case BO_EQ: | ||||
14805 | case BO_NE: | ||||
14806 | case BO_LAnd: | ||||
14807 | case BO_LOr: | ||||
14808 | // These operators have a fixed result type regardless of operands. | ||||
14809 | ResultType = Context.IntTy; | ||||
14810 | break; | ||||
14811 | case BO_Comma: | ||||
14812 | ResultType = RHSExpr->getType(); | ||||
14813 | break; | ||||
14814 | default: | ||||
14815 | ResultType = Context.DependentTy; | ||||
14816 | break; | ||||
14817 | } | ||||
14818 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||
14819 | VK_PRValue, OK_Ordinary, OpLoc, | ||||
14820 | CurFPFeatureOverrides()); | ||||
14821 | } | ||||
14822 | |||||
14823 | // Build a built-in binary operation. | ||||
14824 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14825 | } | ||||
14826 | |||||
14827 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||
14828 | if (T.isNull() || T->isDependentType()) | ||||
14829 | return false; | ||||
14830 | |||||
14831 | if (!T->isPromotableIntegerType()) | ||||
14832 | return true; | ||||
14833 | |||||
14834 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||
14835 | } | ||||
14836 | |||||
14837 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||
14838 | UnaryOperatorKind Opc, | ||||
14839 | Expr *InputExpr) { | ||||
14840 | ExprResult Input = InputExpr; | ||||
14841 | ExprValueKind VK = VK_PRValue; | ||||
14842 | ExprObjectKind OK = OK_Ordinary; | ||||
14843 | QualType resultType; | ||||
14844 | bool CanOverflow = false; | ||||
14845 | |||||
14846 | bool ConvertHalfVec = false; | ||||
14847 | if (getLangOpts().OpenCL) { | ||||
14848 | QualType Ty = InputExpr->getType(); | ||||
14849 | // The only legal unary operation for atomics is '&'. | ||||
14850 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||
14851 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
14852 | // only with a builtin functions and therefore should be disallowed here. | ||||
14853 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||
14854 | || Ty->isBlockPointerType())) { | ||||
14855 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14856 | << InputExpr->getType() | ||||
14857 | << Input.get()->getSourceRange()); | ||||
14858 | } | ||||
14859 | } | ||||
14860 | |||||
14861 | switch (Opc) { | ||||
14862 | case UO_PreInc: | ||||
14863 | case UO_PreDec: | ||||
14864 | case UO_PostInc: | ||||
14865 | case UO_PostDec: | ||||
14866 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||
14867 | OpLoc, | ||||
14868 | Opc == UO_PreInc || | ||||
14869 | Opc == UO_PostInc, | ||||
14870 | Opc == UO_PreInc || | ||||
14871 | Opc == UO_PreDec); | ||||
14872 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||
14873 | break; | ||||
14874 | case UO_AddrOf: | ||||
14875 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||
14876 | CheckAddressOfNoDeref(InputExpr); | ||||
14877 | RecordModifiableNonNullParam(*this, InputExpr); | ||||
14878 | break; | ||||
14879 | case UO_Deref: { | ||||
14880 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14881 | if (Input.isInvalid()) return ExprError(); | ||||
14882 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | ||||
14883 | break; | ||||
14884 | } | ||||
14885 | case UO_Plus: | ||||
14886 | case UO_Minus: | ||||
14887 | CanOverflow = Opc == UO_Minus && | ||||
14888 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||
14889 | Input = UsualUnaryConversions(Input.get()); | ||||
14890 | if (Input.isInvalid()) return ExprError(); | ||||
14891 | // Unary plus and minus require promoting an operand of half vector to a | ||||
14892 | // float vector and truncating the result back to a half vector. For now, we | ||||
14893 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||
14894 | // arm or arm64). | ||||
14895 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||
14896 | |||||
14897 | // If the operand is a half vector, promote it to a float vector. | ||||
14898 | if (ConvertHalfVec) | ||||
14899 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||
14900 | resultType = Input.get()->getType(); | ||||
14901 | if (resultType->isDependentType()) | ||||
14902 | break; | ||||
14903 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||
14904 | break; | ||||
14905 | else if (resultType->isVectorType() && | ||||
14906 | // The z vector extensions don't allow + or - with bool vectors. | ||||
14907 | (!Context.getLangOpts().ZVector || | ||||
14908 | resultType->castAs<VectorType>()->getVectorKind() != | ||||
14909 | VectorType::AltiVecBool)) | ||||
14910 | break; | ||||
14911 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||
14912 | Opc == UO_Plus && | ||||
14913 | resultType->isPointerType()) | ||||
14914 | break; | ||||
14915 | |||||
14916 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14917 | << resultType << Input.get()->getSourceRange()); | ||||
14918 | |||||
14919 | case UO_Not: // bitwise complement | ||||
14920 | Input = UsualUnaryConversions(Input.get()); | ||||
14921 | if (Input.isInvalid()) | ||||
14922 | return ExprError(); | ||||
14923 | resultType = Input.get()->getType(); | ||||
14924 | if (resultType->isDependentType()) | ||||
14925 | break; | ||||
14926 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||
14927 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||
14928 | // C99 does not support '~' for complex conjugation. | ||||
14929 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||
14930 | << resultType << Input.get()->getSourceRange(); | ||||
14931 | else if (resultType->hasIntegerRepresentation()) | ||||
14932 | break; | ||||
14933 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||
14934 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||
14935 | // on vector float types. | ||||
14936 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14937 | if (!T->isIntegerType()) | ||||
14938 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14939 | << resultType << Input.get()->getSourceRange()); | ||||
14940 | } else { | ||||
14941 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14942 | << resultType << Input.get()->getSourceRange()); | ||||
14943 | } | ||||
14944 | break; | ||||
14945 | |||||
14946 | case UO_LNot: // logical negation | ||||
14947 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||
14948 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14949 | if (Input.isInvalid()) return ExprError(); | ||||
14950 | resultType = Input.get()->getType(); | ||||
14951 | |||||
14952 | // Though we still have to promote half FP to float... | ||||
14953 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||
14954 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||
14955 | resultType = Context.FloatTy; | ||||
14956 | } | ||||
14957 | |||||
14958 | if (resultType->isDependentType()) | ||||
14959 | break; | ||||
14960 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||
14961 | // C99 6.5.3.3p1: ok, fallthrough; | ||||
14962 | if (Context.getLangOpts().CPlusPlus) { | ||||
14963 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||
14964 | // operand contextually converted to bool. | ||||
14965 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||
14966 | ScalarTypeToBooleanCastKind(resultType)); | ||||
14967 | } else if (Context.getLangOpts().OpenCL && | ||||
14968 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
14969 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14970 | // operate on scalar float types. | ||||
14971 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||
14972 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14973 | << resultType << Input.get()->getSourceRange()); | ||||
14974 | } | ||||
14975 | } else if (resultType->isExtVectorType()) { | ||||
14976 | if (Context.getLangOpts().OpenCL && | ||||
14977 | Context.getLangOpts().OpenCLVersion < 120 && | ||||
14978 | !Context.getLangOpts().OpenCLCPlusPlus) { | ||||
14979 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14980 | // operate on vector float types. | ||||
14981 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14982 | if (!T->isIntegerType()) | ||||
14983 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14984 | << resultType << Input.get()->getSourceRange()); | ||||
14985 | } | ||||
14986 | // Vector logical not returns the signed variant of the operand type. | ||||
14987 | resultType = GetSignedVectorType(resultType); | ||||
14988 | break; | ||||
14989 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||
14990 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||
14991 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||
14992 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14993 | << resultType << Input.get()->getSourceRange()); | ||||
14994 | |||||
14995 | // Vector logical not returns the signed variant of the operand type. | ||||
14996 | resultType = GetSignedVectorType(resultType); | ||||
14997 | break; | ||||
14998 | } else { | ||||
14999 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
15000 | << resultType << Input.get()->getSourceRange()); | ||||
15001 | } | ||||
15002 | |||||
15003 | // LNot always has type int. C99 6.5.3.3p5. | ||||
15004 | // In C++, it's bool. C++ 5.3.1p8 | ||||
15005 | resultType = Context.getLogicalOperationType(); | ||||
15006 | break; | ||||
15007 | case UO_Real: | ||||
15008 | case UO_Imag: | ||||
15009 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||
15010 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||
15011 | // complex l-values to ordinary l-values and all other values to r-values. | ||||
15012 | if (Input.isInvalid()) return ExprError(); | ||||
15013 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||
15014 | if (Input.get()->isGLValue() && | ||||
15015 | Input.get()->getObjectKind() == OK_Ordinary) | ||||
15016 | VK = Input.get()->getValueKind(); | ||||
15017 | } else if (!getLangOpts().CPlusPlus) { | ||||
15018 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||
15019 | Input = DefaultLvalueConversion(Input.get()); | ||||
15020 | } | ||||
15021 | break; | ||||
15022 | case UO_Extension: | ||||
15023 | resultType = Input.get()->getType(); | ||||
15024 | VK = Input.get()->getValueKind(); | ||||
15025 | OK = Input.get()->getObjectKind(); | ||||
15026 | break; | ||||
15027 | case UO_Coawait: | ||||
15028 | // It's unnecessary to represent the pass-through operator co_await in the | ||||
15029 | // AST; just return the input expression instead. | ||||
15030 | assert(!Input.get()->getType()->isDependentType() &&(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15032, __extension__ __PRETTY_FUNCTION__)) | ||||
15031 | "the co_await expression must be non-dependant before "(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15032, __extension__ __PRETTY_FUNCTION__)) | ||||
15032 | "building operator co_await")(static_cast <bool> (!Input.get()->getType()->isDependentType () && "the co_await expression must be non-dependant before " "building operator co_await") ? void (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15032, __extension__ __PRETTY_FUNCTION__)); | ||||
15033 | return Input; | ||||
15034 | } | ||||
15035 | if (resultType.isNull() || Input.isInvalid()) | ||||
15036 | return ExprError(); | ||||
15037 | |||||
15038 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||
15039 | // except for the '*' and '&' operators that have to be handled specially | ||||
15040 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||
15041 | // that are explicitly defined as valid by the standard). | ||||
15042 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||
15043 | CheckArrayAccess(Input.get()); | ||||
15044 | |||||
15045 | auto *UO = | ||||
15046 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||
15047 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||
15048 | |||||
15049 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||
15050 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | ||||
15051 | !isUnevaluatedContext()) | ||||
15052 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||
15053 | |||||
15054 | // Convert the result back to a half vector. | ||||
15055 | if (ConvertHalfVec) | ||||
15056 | return convertVector(UO, Context.HalfTy, *this); | ||||
15057 | return UO; | ||||
15058 | } | ||||
15059 | |||||
15060 | /// Determine whether the given expression is a qualified member | ||||
15061 | /// access expression, of a form that could be turned into a pointer to member | ||||
15062 | /// with the address-of operator. | ||||
15063 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||
15064 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
15065 | if (!DRE->getQualifier()) | ||||
15066 | return false; | ||||
15067 | |||||
15068 | ValueDecl *VD = DRE->getDecl(); | ||||
15069 | if (!VD->isCXXClassMember()) | ||||
15070 | return false; | ||||
15071 | |||||
15072 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||
15073 | return true; | ||||
15074 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||
15075 | return Method->isInstance(); | ||||
15076 | |||||
15077 | return false; | ||||
15078 | } | ||||
15079 | |||||
15080 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||
15081 | if (!ULE->getQualifier()) | ||||
15082 | return false; | ||||
15083 | |||||
15084 | for (NamedDecl *D : ULE->decls()) { | ||||
15085 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||
15086 | if (Method->isInstance()) | ||||
15087 | return true; | ||||
15088 | } else { | ||||
15089 | // Overload set does not contain methods. | ||||
15090 | break; | ||||
15091 | } | ||||
15092 | } | ||||
15093 | |||||
15094 | return false; | ||||
15095 | } | ||||
15096 | |||||
15097 | return false; | ||||
15098 | } | ||||
15099 | |||||
15100 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
15101 | UnaryOperatorKind Opc, Expr *Input) { | ||||
15102 | // First things first: handle placeholders so that the | ||||
15103 | // overloaded-operator check considers the right type. | ||||
15104 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||
15105 | // Increment and decrement of pseudo-object references. | ||||
15106 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
15107 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||
15108 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||
15109 | |||||
15110 | // extension is always a builtin operator. | ||||
15111 | if (Opc == UO_Extension) | ||||
15112 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
15113 | |||||
15114 | // & gets special logic for several kinds of placeholder. | ||||
15115 | // The builtin code knows what to do. | ||||
15116 | if (Opc == UO_AddrOf && | ||||
15117 | (pty->getKind() == BuiltinType::Overload || | ||||
15118 | pty->getKind() == BuiltinType::UnknownAny || | ||||
15119 | pty->getKind() == BuiltinType::BoundMember)) | ||||
15120 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
15121 | |||||
15122 | // Anything else needs to be handled now. | ||||
15123 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||
15124 | if (Result.isInvalid()) return ExprError(); | ||||
15125 | Input = Result.get(); | ||||
15126 | } | ||||
15127 | |||||
15128 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||
15129 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||
15130 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||
15131 | // Find all of the overloaded operators visible from this point. | ||||
15132 | UnresolvedSet<16> Functions; | ||||
15133 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||
15134 | if (S && OverOp != OO_None) | ||||
15135 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
15136 | |||||
15137 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||
15138 | } | ||||
15139 | |||||
15140 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
15141 | } | ||||
15142 | |||||
15143 | // Unary Operators. 'Tok' is the token for the operator. | ||||
15144 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
15145 | tok::TokenKind Op, Expr *Input) { | ||||
15146 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | ||||
15147 | } | ||||
15148 | |||||
15149 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||
15150 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||
15151 | LabelDecl *TheDecl) { | ||||
15152 | TheDecl->markUsed(Context); | ||||
15153 | // Create the AST node. The address of a label always has type 'void*'. | ||||
15154 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | ||||
15155 | Context.getPointerType(Context.VoidTy)); | ||||
15156 | } | ||||
15157 | |||||
15158 | void Sema::ActOnStartStmtExpr() { | ||||
15159 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
15160 | } | ||||
15161 | |||||
15162 | void Sema::ActOnStmtExprError() { | ||||
15163 | // Note that function is also called by TreeTransform when leaving a | ||||
15164 | // StmtExpr scope without rebuilding anything. | ||||
15165 | |||||
15166 | DiscardCleanupsInEvaluationContext(); | ||||
15167 | PopExpressionEvaluationContext(); | ||||
15168 | } | ||||
15169 | |||||
15170 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||
15171 | SourceLocation RPLoc) { | ||||
15172 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||
15173 | } | ||||
15174 | |||||
15175 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||
15176 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||
15177 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")(static_cast <bool> (SubStmt && isa<CompoundStmt >(SubStmt) && "Invalid action invocation!") ? void (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15177, __extension__ __PRETTY_FUNCTION__)); | ||||
15178 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||
15179 | |||||
15180 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
15181 | DiscardCleanupsInEvaluationContext(); | ||||
15182 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15183, __extension__ __PRETTY_FUNCTION__)) | ||||
15183 | "cleanups within StmtExpr not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15183, __extension__ __PRETTY_FUNCTION__)); | ||||
15184 | PopExpressionEvaluationContext(); | ||||
15185 | |||||
15186 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||
15187 | // example, it is not possible to goto into a stmt expression apparently. | ||||
15188 | // More semantic analysis is needed. | ||||
15189 | |||||
15190 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||
15191 | // as the type of the stmtexpr. | ||||
15192 | QualType Ty = Context.VoidTy; | ||||
15193 | bool StmtExprMayBindToTemp = false; | ||||
15194 | if (!Compound->body_empty()) { | ||||
15195 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||
15196 | if (const auto *LastStmt = | ||||
15197 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||
15198 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||
15199 | StmtExprMayBindToTemp = true; | ||||
15200 | Ty = Value->getType(); | ||||
15201 | } | ||||
15202 | } | ||||
15203 | } | ||||
15204 | |||||
15205 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||
15206 | // expressions are not lvalues. | ||||
15207 | Expr *ResStmtExpr = | ||||
15208 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||
15209 | if (StmtExprMayBindToTemp) | ||||
15210 | return MaybeBindToTemporary(ResStmtExpr); | ||||
15211 | return ResStmtExpr; | ||||
15212 | } | ||||
15213 | |||||
15214 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||
15215 | if (ER.isInvalid()) | ||||
15216 | return ExprError(); | ||||
15217 | |||||
15218 | // Do function/array conversion on the last expression, but not | ||||
15219 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||
15220 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||
15221 | if (ER.isInvalid()) | ||||
15222 | return ExprError(); | ||||
15223 | Expr *E = ER.get(); | ||||
15224 | |||||
15225 | if (E->isTypeDependent()) | ||||
15226 | return E; | ||||
15227 | |||||
15228 | // In ARC, if the final expression ends in a consume, splice | ||||
15229 | // the consume out and bind it later. In the alternate case | ||||
15230 | // (when dealing with a retainable type), the result | ||||
15231 | // initialization will create a produce. In both cases the | ||||
15232 | // result will be +1, and we'll need to balance that out with | ||||
15233 | // a bind. | ||||
15234 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||
15235 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||
15236 | return Cast->getSubExpr(); | ||||
15237 | |||||
15238 | // FIXME: Provide a better location for the initialization. | ||||
15239 | return PerformCopyInitialization( | ||||
15240 | InitializedEntity::InitializeStmtExprResult( | ||||
15241 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||
15242 | SourceLocation(), E); | ||||
15243 | } | ||||
15244 | |||||
15245 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||
15246 | TypeSourceInfo *TInfo, | ||||
15247 | ArrayRef<OffsetOfComponent> Components, | ||||
15248 | SourceLocation RParenLoc) { | ||||
15249 | QualType ArgTy = TInfo->getType(); | ||||
15250 | bool Dependent = ArgTy->isDependentType(); | ||||
15251 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||
15252 | |||||
15253 | // We must have at least one component that refers to the type, and the first | ||||
15254 | // one is known to be a field designator. Verify that the ArgTy represents | ||||
15255 | // a struct/union/class. | ||||
15256 | if (!Dependent && !ArgTy->isRecordType()) | ||||
15257 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||
15258 | << ArgTy << TypeRange); | ||||
15259 | |||||
15260 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||
15261 | // with an incomplete type would be ill-formed. | ||||
15262 | if (!Dependent | ||||
15263 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||
15264 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||
15265 | return ExprError(); | ||||
15266 | |||||
15267 | bool DidWarnAboutNonPOD = false; | ||||
15268 | QualType CurrentType = ArgTy; | ||||
15269 | SmallVector<OffsetOfNode, 4> Comps; | ||||
15270 | SmallVector<Expr*, 4> Exprs; | ||||
15271 | for (const OffsetOfComponent &OC : Components) { | ||||
15272 | if (OC.isBrackets) { | ||||
15273 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||
15274 | if (!CurrentType->isDependentType()) { | ||||
15275 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||
15276 | if(!AT) | ||||
15277 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||
15278 | << CurrentType); | ||||
15279 | CurrentType = AT->getElementType(); | ||||
15280 | } else | ||||
15281 | CurrentType = Context.DependentTy; | ||||
15282 | |||||
15283 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||
15284 | if (IdxRval.isInvalid()) | ||||
15285 | return ExprError(); | ||||
15286 | Expr *Idx = IdxRval.get(); | ||||
15287 | |||||
15288 | // The expression must be an integral expression. | ||||
15289 | // FIXME: An integral constant expression? | ||||
15290 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||
15291 | !Idx->getType()->isIntegerType()) | ||||
15292 | return ExprError( | ||||
15293 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||
15294 | << Idx->getSourceRange()); | ||||
15295 | |||||
15296 | // Record this array index. | ||||
15297 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||
15298 | Exprs.push_back(Idx); | ||||
15299 | continue; | ||||
15300 | } | ||||
15301 | |||||
15302 | // Offset of a field. | ||||
15303 | if (CurrentType->isDependentType()) { | ||||
15304 | // We have the offset of a field, but we can't look into the dependent | ||||
15305 | // type. Just record the identifier of the field. | ||||
15306 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||
15307 | CurrentType = Context.DependentTy; | ||||
15308 | continue; | ||||
15309 | } | ||||
15310 | |||||
15311 | // We need to have a complete type to look into. | ||||
15312 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||
15313 | diag::err_offsetof_incomplete_type)) | ||||
15314 | return ExprError(); | ||||
15315 | |||||
15316 | // Look for the designated field. | ||||
15317 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||
15318 | if (!RC) | ||||
15319 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||
15320 | << CurrentType); | ||||
15321 | RecordDecl *RD = RC->getDecl(); | ||||
15322 | |||||
15323 | // C++ [lib.support.types]p5: | ||||
15324 | // The macro offsetof accepts a restricted set of type arguments in this | ||||
15325 | // International Standard. type shall be a POD structure or a POD union | ||||
15326 | // (clause 9). | ||||
15327 | // C++11 [support.types]p4: | ||||
15328 | // If type is not a standard-layout class (Clause 9), the results are | ||||
15329 | // undefined. | ||||
15330 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
15331 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||
15332 | unsigned DiagID = | ||||
15333 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||
15334 | : diag::ext_offsetof_non_pod_type; | ||||
15335 | |||||
15336 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||
15337 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||
15338 | PDiag(DiagID) | ||||
15339 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||
15340 | << CurrentType)) | ||||
15341 | DidWarnAboutNonPOD = true; | ||||
15342 | } | ||||
15343 | |||||
15344 | // Look for the field. | ||||
15345 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||
15346 | LookupQualifiedName(R, RD); | ||||
15347 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||
15348 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||
15349 | if (!MemberDecl) { | ||||
15350 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||
15351 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||
15352 | } | ||||
15353 | |||||
15354 | if (!MemberDecl) | ||||
15355 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||
15356 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||
15357 | OC.LocEnd)); | ||||
15358 | |||||
15359 | // C99 7.17p3: | ||||
15360 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||
15361 | // | ||||
15362 | // We diagnose this as an error. | ||||
15363 | if (MemberDecl->isBitField()) { | ||||
15364 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||
15365 | << MemberDecl->getDeclName() | ||||
15366 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15367 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||
15368 | return ExprError(); | ||||
15369 | } | ||||
15370 | |||||
15371 | RecordDecl *Parent = MemberDecl->getParent(); | ||||
15372 | if (IndirectMemberDecl) | ||||
15373 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||
15374 | |||||
15375 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||
15376 | // the base class indirections. | ||||
15377 | CXXBasePaths Paths; | ||||
15378 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||
15379 | Paths)) { | ||||
15380 | if (Paths.getDetectedVirtual()) { | ||||
15381 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||
15382 | << MemberDecl->getDeclName() | ||||
15383 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15384 | return ExprError(); | ||||
15385 | } | ||||
15386 | |||||
15387 | CXXBasePath &Path = Paths.front(); | ||||
15388 | for (const CXXBasePathElement &B : Path) | ||||
15389 | Comps.push_back(OffsetOfNode(B.Base)); | ||||
15390 | } | ||||
15391 | |||||
15392 | if (IndirectMemberDecl) { | ||||
15393 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||
15394 | assert(isa<FieldDecl>(FI))(static_cast <bool> (isa<FieldDecl>(FI)) ? void ( 0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15394, __extension__ __PRETTY_FUNCTION__)); | ||||
15395 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||
15396 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||
15397 | } | ||||
15398 | } else | ||||
15399 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||
15400 | |||||
15401 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
15402 | } | ||||
15403 | |||||
15404 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||
15405 | Comps, Exprs, RParenLoc); | ||||
15406 | } | ||||
15407 | |||||
15408 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||
15409 | SourceLocation BuiltinLoc, | ||||
15410 | SourceLocation TypeLoc, | ||||
15411 | ParsedType ParsedArgTy, | ||||
15412 | ArrayRef<OffsetOfComponent> Components, | ||||
15413 | SourceLocation RParenLoc) { | ||||
15414 | |||||
15415 | TypeSourceInfo *ArgTInfo; | ||||
15416 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||
15417 | if (ArgTy.isNull()) | ||||
15418 | return ExprError(); | ||||
15419 | |||||
15420 | if (!ArgTInfo) | ||||
15421 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||
15422 | |||||
15423 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||
15424 | } | ||||
15425 | |||||
15426 | |||||
15427 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||
15428 | Expr *CondExpr, | ||||
15429 | Expr *LHSExpr, Expr *RHSExpr, | ||||
15430 | SourceLocation RPLoc) { | ||||
15431 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(static_cast <bool> ((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? void (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15431, __extension__ __PRETTY_FUNCTION__)); | ||||
15432 | |||||
15433 | ExprValueKind VK = VK_PRValue; | ||||
15434 | ExprObjectKind OK = OK_Ordinary; | ||||
15435 | QualType resType; | ||||
15436 | bool CondIsTrue = false; | ||||
15437 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||
15438 | resType = Context.DependentTy; | ||||
15439 | } else { | ||||
15440 | // The conditional expression is required to be a constant expression. | ||||
15441 | llvm::APSInt condEval(32); | ||||
15442 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||
15443 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||
15444 | if (CondICE.isInvalid()) | ||||
15445 | return ExprError(); | ||||
15446 | CondExpr = CondICE.get(); | ||||
15447 | CondIsTrue = condEval.getZExtValue(); | ||||
15448 | |||||
15449 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||
15450 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||
15451 | |||||
15452 | resType = ActiveExpr->getType(); | ||||
15453 | VK = ActiveExpr->getValueKind(); | ||||
15454 | OK = ActiveExpr->getObjectKind(); | ||||
15455 | } | ||||
15456 | |||||
15457 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||
15458 | resType, VK, OK, RPLoc, CondIsTrue); | ||||
15459 | } | ||||
15460 | |||||
15461 | //===----------------------------------------------------------------------===// | ||||
15462 | // Clang Extensions. | ||||
15463 | //===----------------------------------------------------------------------===// | ||||
15464 | |||||
15465 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||
15466 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15467 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||
15468 | |||||
15469 | if (LangOpts.CPlusPlus) { | ||||
15470 | MangleNumberingContext *MCtx; | ||||
15471 | Decl *ManglingContextDecl; | ||||
15472 | std::tie(MCtx, ManglingContextDecl) = | ||||
15473 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||
15474 | if (MCtx) { | ||||
15475 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||
15476 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||
15477 | } | ||||
15478 | } | ||||
15479 | |||||
15480 | PushBlockScope(CurScope, Block); | ||||
15481 | CurContext->addDecl(Block); | ||||
15482 | if (CurScope) | ||||
15483 | PushDeclContext(CurScope, Block); | ||||
15484 | else | ||||
15485 | CurContext = Block; | ||||
15486 | |||||
15487 | getCurBlock()->HasImplicitReturnType = true; | ||||
15488 | |||||
15489 | // Enter a new evaluation context to insulate the block from any | ||||
15490 | // cleanups from the enclosing full-expression. | ||||
15491 | PushExpressionEvaluationContext( | ||||
15492 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15493 | } | ||||
15494 | |||||
15495 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||
15496 | Scope *CurScope) { | ||||
15497 | assert(ParamInfo.getIdentifier() == nullptr &&(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15498, __extension__ __PRETTY_FUNCTION__)) | ||||
15498 | "block-id should have no identifier!")(static_cast <bool> (ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!") ? void (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15498, __extension__ __PRETTY_FUNCTION__)); | ||||
15499 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)(static_cast <bool> (ParamInfo.getContext() == DeclaratorContext ::BlockLiteral) ? void (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15499, __extension__ __PRETTY_FUNCTION__)); | ||||
15500 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||
15501 | |||||
15502 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||
15503 | QualType T = Sig->getType(); | ||||
15504 | |||||
15505 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||
15506 | // in turn, make the block expression contain unexpanded parameter packs. | ||||
15507 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||
15508 | // Drop the parameters. | ||||
15509 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15510 | EPI.HasTrailingReturn = false; | ||||
15511 | EPI.TypeQuals.addConst(); | ||||
15512 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | ||||
15513 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||
15514 | } | ||||
15515 | |||||
15516 | // GetTypeForDeclarator always produces a function type for a block | ||||
15517 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||
15518 | // unless the function was written with a typedef. | ||||
15519 | assert(T->isFunctionType() &&(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15520, __extension__ __PRETTY_FUNCTION__)) | ||||
15520 | "GetTypeForDeclarator made a non-function block signature")(static_cast <bool> (T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15520, __extension__ __PRETTY_FUNCTION__)); | ||||
15521 | |||||
15522 | // Look for an explicit signature in that function type. | ||||
15523 | FunctionProtoTypeLoc ExplicitSignature; | ||||
15524 | |||||
15525 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||
15526 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||
15527 | |||||
15528 | // Check whether that explicit signature was synthesized by | ||||
15529 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||
15530 | // written signature. | ||||
15531 | if (ExplicitSignature.getLocalRangeBegin() == | ||||
15532 | ExplicitSignature.getLocalRangeEnd()) { | ||||
15533 | // This would be much cheaper if we stored TypeLocs instead of | ||||
15534 | // TypeSourceInfos. | ||||
15535 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||
15536 | unsigned Size = Result.getFullDataSize(); | ||||
15537 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||
15538 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||
15539 | |||||
15540 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||
15541 | } | ||||
15542 | } | ||||
15543 | |||||
15544 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||
15545 | CurBlock->FunctionType = T; | ||||
15546 | |||||
15547 | const auto *Fn = T->castAs<FunctionType>(); | ||||
15548 | QualType RetTy = Fn->getReturnType(); | ||||
15549 | bool isVariadic = | ||||
15550 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||
15551 | |||||
15552 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||
15553 | |||||
15554 | // Context.DependentTy is used as a placeholder for a missing block | ||||
15555 | // return type. TODO: what should we do with declarators like: | ||||
15556 | // ^ * { ... } | ||||
15557 | // If the answer is "apply template argument deduction".... | ||||
15558 | if (RetTy != Context.DependentTy) { | ||||
15559 | CurBlock->ReturnType = RetTy; | ||||
15560 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||
15561 | CurBlock->HasImplicitReturnType = false; | ||||
15562 | } | ||||
15563 | |||||
15564 | // Push block parameters from the declarator if we had them. | ||||
15565 | SmallVector<ParmVarDecl*, 8> Params; | ||||
15566 | if (ExplicitSignature) { | ||||
15567 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||
15568 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||
15569 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||
15570 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||
15571 | // Diagnose this as an extension in C17 and earlier. | ||||
15572 | if (!getLangOpts().C2x) | ||||
15573 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||
15574 | } | ||||
15575 | Params.push_back(Param); | ||||
15576 | } | ||||
15577 | |||||
15578 | // Fake up parameter variables if we have a typedef, like | ||||
15579 | // ^ fntype { ... } | ||||
15580 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||
15581 | for (const auto &I : Fn->param_types()) { | ||||
15582 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||
15583 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||
15584 | Params.push_back(Param); | ||||
15585 | } | ||||
15586 | } | ||||
15587 | |||||
15588 | // Set the parameters on the block decl. | ||||
15589 | if (!Params.empty()) { | ||||
15590 | CurBlock->TheDecl->setParams(Params); | ||||
15591 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||
15592 | /*CheckParameterNames=*/false); | ||||
15593 | } | ||||
15594 | |||||
15595 | // Finally we can process decl attributes. | ||||
15596 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||
15597 | |||||
15598 | // Put the parameter variables in scope. | ||||
15599 | for (auto AI : CurBlock->TheDecl->parameters()) { | ||||
15600 | AI->setOwningFunction(CurBlock->TheDecl); | ||||
15601 | |||||
15602 | // If this has an identifier, add it to the scope stack. | ||||
15603 | if (AI->getIdentifier()) { | ||||
15604 | CheckShadow(CurBlock->TheScope, AI); | ||||
15605 | |||||
15606 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||
15607 | } | ||||
15608 | } | ||||
15609 | } | ||||
15610 | |||||
15611 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||
15612 | /// is invoked to pop the information about the block from the action impl. | ||||
15613 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15614 | // Leave the expression-evaluation context. | ||||
15615 | DiscardCleanupsInEvaluationContext(); | ||||
15616 | PopExpressionEvaluationContext(); | ||||
15617 | |||||
15618 | // Pop off CurBlock, handle nested blocks. | ||||
15619 | PopDeclContext(); | ||||
15620 | PopFunctionScopeInfo(); | ||||
15621 | } | ||||
15622 | |||||
15623 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||
15624 | /// literal was successfully completed. ^(int x){...} | ||||
15625 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||
15626 | Stmt *Body, Scope *CurScope) { | ||||
15627 | // If blocks are disabled, emit an error. | ||||
15628 | if (!LangOpts.Blocks) | ||||
15629 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
15630 | |||||
15631 | // Leave the expression-evaluation context. | ||||
15632 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
15633 | DiscardCleanupsInEvaluationContext(); | ||||
15634 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15635, __extension__ __PRETTY_FUNCTION__)) | ||||
15635 | "cleanups within block not correctly bound!")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15635, __extension__ __PRETTY_FUNCTION__)); | ||||
15636 | PopExpressionEvaluationContext(); | ||||
15637 | |||||
15638 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||
15639 | BlockDecl *BD = BSI->TheDecl; | ||||
15640 | |||||
15641 | if (BSI->HasImplicitReturnType) | ||||
15642 | deduceClosureReturnType(*BSI); | ||||
15643 | |||||
15644 | QualType RetTy = Context.VoidTy; | ||||
15645 | if (!BSI->ReturnType.isNull()) | ||||
15646 | RetTy = BSI->ReturnType; | ||||
15647 | |||||
15648 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||
15649 | QualType BlockTy; | ||||
15650 | |||||
15651 | // If the user wrote a function type in some form, try to use that. | ||||
15652 | if (!BSI->FunctionType.isNull()) { | ||||
15653 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||
15654 | |||||
15655 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||
15656 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||
15657 | |||||
15658 | // Turn protoless block types into nullary block types. | ||||
15659 | if (isa<FunctionNoProtoType>(FTy)) { | ||||
15660 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15661 | EPI.ExtInfo = Ext; | ||||
15662 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15663 | |||||
15664 | // Otherwise, if we don't need to change anything about the function type, | ||||
15665 | // preserve its sugar structure. | ||||
15666 | } else if (FTy->getReturnType() == RetTy && | ||||
15667 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||
15668 | BlockTy = BSI->FunctionType; | ||||
15669 | |||||
15670 | // Otherwise, make the minimal modifications to the function type. | ||||
15671 | } else { | ||||
15672 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||
15673 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
15674 | EPI.TypeQuals = Qualifiers(); | ||||
15675 | EPI.ExtInfo = Ext; | ||||
15676 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||
15677 | } | ||||
15678 | |||||
15679 | // If we don't have a function type, just build one from nothing. | ||||
15680 | } else { | ||||
15681 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15682 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||
15683 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15684 | } | ||||
15685 | |||||
15686 | DiagnoseUnusedParameters(BD->parameters()); | ||||
15687 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||
15688 | |||||
15689 | // If needed, diagnose invalid gotos and switches in the block. | ||||
15690 | if (getCurFunction()->NeedsScopeChecking() && | ||||
15691 | !PP.isCodeCompletionEnabled()) | ||||
15692 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||
15693 | |||||
15694 | BD->setBody(cast<CompoundStmt>(Body)); | ||||
15695 | |||||
15696 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
15697 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||
15698 | |||||
15699 | // Try to apply the named return value optimization. We have to check again | ||||
15700 | // if we can do this, though, because blocks keep return statements around | ||||
15701 | // to deduce an implicit return type. | ||||
15702 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||
15703 | !BD->isDependentContext()) | ||||
15704 | computeNRVO(Body, BSI); | ||||
15705 | |||||
15706 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
15707 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
15708 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||
15709 | NTCUK_Destruct|NTCUK_Copy); | ||||
15710 | |||||
15711 | PopDeclContext(); | ||||
15712 | |||||
15713 | // Set the captured variables on the block. | ||||
15714 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||
15715 | for (Capture &Cap : BSI->Captures) { | ||||
15716 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||
15717 | continue; | ||||
15718 | |||||
15719 | VarDecl *Var = Cap.getVariable(); | ||||
15720 | Expr *CopyExpr = nullptr; | ||||
15721 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||
15722 | if (const RecordType *Record = | ||||
15723 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||
15724 | // The capture logic needs the destructor, so make sure we mark it. | ||||
15725 | // Usually this is unnecessary because most local variables have | ||||
15726 | // their destructors marked at declaration time, but parameters are | ||||
15727 | // an exception because it's technically only the call site that | ||||
15728 | // actually requires the destructor. | ||||
15729 | if (isa<ParmVarDecl>(Var)) | ||||
15730 | FinalizeVarWithDestructor(Var, Record); | ||||
15731 | |||||
15732 | // Enter a separate potentially-evaluated context while building block | ||||
15733 | // initializers to isolate their cleanups from those of the block | ||||
15734 | // itself. | ||||
15735 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||
15736 | // unevaluated operand? | ||||
15737 | EnterExpressionEvaluationContext EvalContext( | ||||
15738 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15739 | |||||
15740 | SourceLocation Loc = Cap.getLocation(); | ||||
15741 | |||||
15742 | ExprResult Result = BuildDeclarationNameExpr( | ||||
15743 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||
15744 | |||||
15745 | // According to the blocks spec, the capture of a variable from | ||||
15746 | // the stack requires a const copy constructor. This is not true | ||||
15747 | // of the copy/move done to move a __block variable to the heap. | ||||
15748 | if (!Result.isInvalid() && | ||||
15749 | !Result.get()->getType().isConstQualified()) { | ||||
15750 | Result = ImpCastExprToType(Result.get(), | ||||
15751 | Result.get()->getType().withConst(), | ||||
15752 | CK_NoOp, VK_LValue); | ||||
15753 | } | ||||
15754 | |||||
15755 | if (!Result.isInvalid()) { | ||||
15756 | Result = PerformCopyInitialization( | ||||
15757 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||
15758 | Cap.getCaptureType(), false), | ||||
15759 | Loc, Result.get()); | ||||
15760 | } | ||||
15761 | |||||
15762 | // Build a full-expression copy expression if initialization | ||||
15763 | // succeeded and used a non-trivial constructor. Recover from | ||||
15764 | // errors by pretending that the copy isn't necessary. | ||||
15765 | if (!Result.isInvalid() && | ||||
15766 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||
15767 | ->isTrivial()) { | ||||
15768 | Result = MaybeCreateExprWithCleanups(Result); | ||||
15769 | CopyExpr = Result.get(); | ||||
15770 | } | ||||
15771 | } | ||||
15772 | } | ||||
15773 | |||||
15774 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||
15775 | CopyExpr); | ||||
15776 | Captures.push_back(NewCap); | ||||
15777 | } | ||||
15778 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||
15779 | |||||
15780 | // Pop the block scope now but keep it alive to the end of this function. | ||||
15781 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
15782 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||
15783 | |||||
15784 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||
15785 | |||||
15786 | // If the block isn't obviously global, i.e. it captures anything at | ||||
15787 | // all, then we need to do a few things in the surrounding context: | ||||
15788 | if (Result->getBlockDecl()->hasCaptures()) { | ||||
15789 | // First, this expression has a new cleanup object. | ||||
15790 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||
15791 | Cleanup.setExprNeedsCleanups(true); | ||||
15792 | |||||
15793 | // It also gets a branch-protected scope if any of the captured | ||||
15794 | // variables needs destruction. | ||||
15795 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||
15796 | const VarDecl *var = CI.getVariable(); | ||||
15797 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||
15798 | setFunctionHasBranchProtectedScope(); | ||||
15799 | break; | ||||
15800 | } | ||||
15801 | } | ||||
15802 | } | ||||
15803 | |||||
15804 | if (getCurFunction()) | ||||
15805 | getCurFunction()->addBlock(BD); | ||||
15806 | |||||
15807 | return Result; | ||||
15808 | } | ||||
15809 | |||||
15810 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||
15811 | SourceLocation RPLoc) { | ||||
15812 | TypeSourceInfo *TInfo; | ||||
15813 | GetTypeFromParser(Ty, &TInfo); | ||||
15814 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||
15815 | } | ||||
15816 | |||||
15817 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||
15818 | Expr *E, TypeSourceInfo *TInfo, | ||||
15819 | SourceLocation RPLoc) { | ||||
15820 | Expr *OrigExpr = E; | ||||
15821 | bool IsMS = false; | ||||
15822 | |||||
15823 | // CUDA device code does not support varargs. | ||||
15824 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||
15825 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||
15826 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||
15827 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||
15828 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||
15829 | } | ||||
15830 | } | ||||
15831 | |||||
15832 | // NVPTX does not support va_arg expression. | ||||
15833 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||
15834 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||
15835 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||
15836 | |||||
15837 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||
15838 | // as Microsoft ABI on an actual Microsoft platform, where | ||||
15839 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||
15840 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||
15841 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||
15842 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||
15843 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||
15844 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15845 | return ExprError(); | ||||
15846 | IsMS = true; | ||||
15847 | } | ||||
15848 | } | ||||
15849 | |||||
15850 | // Get the va_list type | ||||
15851 | QualType VaListType = Context.getBuiltinVaListType(); | ||||
15852 | if (!IsMS) { | ||||
15853 | if (VaListType->isArrayType()) { | ||||
15854 | // Deal with implicit array decay; for example, on x86-64, | ||||
15855 | // va_list is an array, but it's supposed to decay to | ||||
15856 | // a pointer for va_arg. | ||||
15857 | VaListType = Context.getArrayDecayedType(VaListType); | ||||
15858 | // Make sure the input expression also decays appropriately. | ||||
15859 | ExprResult Result = UsualUnaryConversions(E); | ||||
15860 | if (Result.isInvalid()) | ||||
15861 | return ExprError(); | ||||
15862 | E = Result.get(); | ||||
15863 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||
15864 | // If va_list is a record type and we are compiling in C++ mode, | ||||
15865 | // check the argument using reference binding. | ||||
15866 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
15867 | Context, Context.getLValueReferenceType(VaListType), false); | ||||
15868 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||
15869 | if (Init.isInvalid()) | ||||
15870 | return ExprError(); | ||||
15871 | E = Init.getAs<Expr>(); | ||||
15872 | } else { | ||||
15873 | // Otherwise, the va_list argument must be an l-value because | ||||
15874 | // it is modified by va_arg. | ||||
15875 | if (!E->isTypeDependent() && | ||||
15876 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15877 | return ExprError(); | ||||
15878 | } | ||||
15879 | } | ||||
15880 | |||||
15881 | if (!IsMS && !E->isTypeDependent() && | ||||
15882 | !Context.hasSameType(VaListType, E->getType())) | ||||
15883 | return ExprError( | ||||
15884 | Diag(E->getBeginLoc(), | ||||
15885 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||
15886 | << OrigExpr->getType() << E->getSourceRange()); | ||||
15887 | |||||
15888 | if (!TInfo->getType()->isDependentType()) { | ||||
15889 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||
15890 | diag::err_second_parameter_to_va_arg_incomplete, | ||||
15891 | TInfo->getTypeLoc())) | ||||
15892 | return ExprError(); | ||||
15893 | |||||
15894 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||
15895 | TInfo->getType(), | ||||
15896 | diag::err_second_parameter_to_va_arg_abstract, | ||||
15897 | TInfo->getTypeLoc())) | ||||
15898 | return ExprError(); | ||||
15899 | |||||
15900 | if (!TInfo->getType().isPODType(Context)) { | ||||
15901 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||
15902 | TInfo->getType()->isObjCLifetimeType() | ||||
15903 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||
15904 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||
15905 | << TInfo->getType() | ||||
15906 | << TInfo->getTypeLoc().getSourceRange(); | ||||
15907 | } | ||||
15908 | |||||
15909 | // Check for va_arg where arguments of the given type will be promoted | ||||
15910 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||
15911 | QualType PromoteType; | ||||
15912 | if (TInfo->getType()->isPromotableIntegerType()) { | ||||
15913 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||
15914 | // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, | ||||
15915 | // and C2x 7.16.1.1p2 says, in part: | ||||
15916 | // If type is not compatible with the type of the actual next argument | ||||
15917 | // (as promoted according to the default argument promotions), the | ||||
15918 | // behavior is undefined, except for the following cases: | ||||
15919 | // - both types are pointers to qualified or unqualified versions of | ||||
15920 | // compatible types; | ||||
15921 | // - one type is a signed integer type, the other type is the | ||||
15922 | // corresponding unsigned integer type, and the value is | ||||
15923 | // representable in both types; | ||||
15924 | // - one type is pointer to qualified or unqualified void and the | ||||
15925 | // other is a pointer to a qualified or unqualified character type. | ||||
15926 | // Given that type compatibility is the primary requirement (ignoring | ||||
15927 | // qualifications), you would think we could call typesAreCompatible() | ||||
15928 | // directly to test this. However, in C++, that checks for *same type*, | ||||
15929 | // which causes false positives when passing an enumeration type to | ||||
15930 | // va_arg. Instead, get the underlying type of the enumeration and pass | ||||
15931 | // that. | ||||
15932 | QualType UnderlyingType = TInfo->getType(); | ||||
15933 | if (const auto *ET = UnderlyingType->getAs<EnumType>()) | ||||
15934 | UnderlyingType = ET->getDecl()->getIntegerType(); | ||||
15935 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
15936 | /*CompareUnqualified*/ true)) | ||||
15937 | PromoteType = QualType(); | ||||
15938 | |||||
15939 | // If the types are still not compatible, we need to test whether the | ||||
15940 | // promoted type and the underlying type are the same except for | ||||
15941 | // signedness. Ask the AST for the correctly corresponding type and see | ||||
15942 | // if that's compatible. | ||||
15943 | if (!PromoteType.isNull() && | ||||
15944 | PromoteType->isUnsignedIntegerType() != | ||||
15945 | UnderlyingType->isUnsignedIntegerType()) { | ||||
15946 | UnderlyingType = | ||||
15947 | UnderlyingType->isUnsignedIntegerType() | ||||
15948 | ? Context.getCorrespondingSignedType(UnderlyingType) | ||||
15949 | : Context.getCorrespondingUnsignedType(UnderlyingType); | ||||
15950 | if (Context.typesAreCompatible(PromoteType, UnderlyingType, | ||||
15951 | /*CompareUnqualified*/ true)) | ||||
15952 | PromoteType = QualType(); | ||||
15953 | } | ||||
15954 | } | ||||
15955 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||
15956 | PromoteType = Context.DoubleTy; | ||||
15957 | if (!PromoteType.isNull()) | ||||
15958 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||
15959 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||
15960 | << TInfo->getType() | ||||
15961 | << PromoteType | ||||
15962 | << TInfo->getTypeLoc().getSourceRange()); | ||||
15963 | } | ||||
15964 | |||||
15965 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||
15966 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||
15967 | } | ||||
15968 | |||||
15969 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||
15970 | // The type of __null will be int or long, depending on the size of | ||||
15971 | // pointers on the target. | ||||
15972 | QualType Ty; | ||||
15973 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | ||||
15974 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||
15975 | Ty = Context.IntTy; | ||||
15976 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||
15977 | Ty = Context.LongTy; | ||||
15978 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||
15979 | Ty = Context.LongLongTy; | ||||
15980 | else { | ||||
15981 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 15981); | ||||
15982 | } | ||||
15983 | |||||
15984 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||
15985 | } | ||||
15986 | |||||
15987 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15988 | SourceLocation BuiltinLoc, | ||||
15989 | SourceLocation RPLoc) { | ||||
15990 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | ||||
15991 | } | ||||
15992 | |||||
15993 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15994 | SourceLocation BuiltinLoc, | ||||
15995 | SourceLocation RPLoc, | ||||
15996 | DeclContext *ParentContext) { | ||||
15997 | return new (Context) | ||||
15998 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | ||||
15999 | } | ||||
16000 | |||||
16001 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||
16002 | bool Diagnose) { | ||||
16003 | if (!getLangOpts().ObjC) | ||||
16004 | return false; | ||||
16005 | |||||
16006 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||
16007 | if (!PT) | ||||
16008 | return false; | ||||
16009 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||
16010 | |||||
16011 | // Ignore any parens, implicit casts (should only be | ||||
16012 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||
16013 | // important for making this trigger for property assignments. | ||||
16014 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||
16015 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||
16016 | if (OV->getSourceExpr()) | ||||
16017 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||
16018 | |||||
16019 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||
16020 | if (!PT->isObjCIdType() && | ||||
16021 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||
16022 | return false; | ||||
16023 | if (!SL->isAscii()) | ||||
16024 | return false; | ||||
16025 | |||||
16026 | if (Diagnose) { | ||||
16027 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
16028 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||
16029 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||
16030 | } | ||||
16031 | return true; | ||||
16032 | } | ||||
16033 | |||||
16034 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||
16035 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||
16036 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||
16037 | !SrcExpr->isNullPointerConstant( | ||||
16038 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||
16039 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||
16040 | return false; | ||||
16041 | if (Diagnose) { | ||||
16042 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
16043 | << /*number*/1 | ||||
16044 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||
16045 | Expr *NumLit = | ||||
16046 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||
16047 | if (NumLit) | ||||
16048 | Exp = NumLit; | ||||
16049 | } | ||||
16050 | return true; | ||||
16051 | } | ||||
16052 | |||||
16053 | return false; | ||||
16054 | } | ||||
16055 | |||||
16056 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||
16057 | const Expr *SrcExpr) { | ||||
16058 | if (!DstType->isFunctionPointerType() || | ||||
16059 | !SrcExpr->getType()->isFunctionType()) | ||||
16060 | return false; | ||||
16061 | |||||
16062 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||
16063 | if (!DRE) | ||||
16064 | return false; | ||||
16065 | |||||
16066 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
16067 | if (!FD) | ||||
16068 | return false; | ||||
16069 | |||||
16070 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||
16071 | /*Complain=*/true, | ||||
16072 | SrcExpr->getBeginLoc()); | ||||
16073 | } | ||||
16074 | |||||
16075 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||
16076 | SourceLocation Loc, | ||||
16077 | QualType DstType, QualType SrcType, | ||||
16078 | Expr *SrcExpr, AssignmentAction Action, | ||||
16079 | bool *Complained) { | ||||
16080 | if (Complained) | ||||
16081 | *Complained = false; | ||||
16082 | |||||
16083 | // Decode the result (notice that AST's are still created for extensions). | ||||
16084 | bool CheckInferredResultType = false; | ||||
16085 | bool isInvalid = false; | ||||
16086 | unsigned DiagKind = 0; | ||||
16087 | ConversionFixItGenerator ConvHints; | ||||
16088 | bool MayHaveConvFixit = false; | ||||
16089 | bool MayHaveFunctionDiff = false; | ||||
16090 | const ObjCInterfaceDecl *IFace = nullptr; | ||||
16091 | const ObjCProtocolDecl *PDecl = nullptr; | ||||
16092 | |||||
16093 | switch (ConvTy) { | ||||
16094 | case Compatible: | ||||
16095 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||
16096 | return false; | ||||
16097 | |||||
16098 | case PointerToInt: | ||||
16099 | if (getLangOpts().CPlusPlus) { | ||||
16100 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||
16101 | isInvalid = true; | ||||
16102 | } else { | ||||
16103 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||
16104 | } | ||||
16105 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16106 | MayHaveConvFixit = true; | ||||
16107 | break; | ||||
16108 | case IntToPointer: | ||||
16109 | if (getLangOpts().CPlusPlus) { | ||||
16110 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||
16111 | isInvalid = true; | ||||
16112 | } else { | ||||
16113 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||
16114 | } | ||||
16115 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16116 | MayHaveConvFixit = true; | ||||
16117 | break; | ||||
16118 | case IncompatibleFunctionPointer: | ||||
16119 | if (getLangOpts().CPlusPlus) { | ||||
16120 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||
16121 | isInvalid = true; | ||||
16122 | } else { | ||||
16123 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||
16124 | } | ||||
16125 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16126 | MayHaveConvFixit = true; | ||||
16127 | break; | ||||
16128 | case IncompatiblePointer: | ||||
16129 | if (Action == AA_Passing_CFAudited) { | ||||
16130 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||
16131 | } else if (getLangOpts().CPlusPlus) { | ||||
16132 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||
16133 | isInvalid = true; | ||||
16134 | } else { | ||||
16135 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||
16136 | } | ||||
16137 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||
16138 | SrcType->isObjCObjectPointerType(); | ||||
16139 | if (!CheckInferredResultType) { | ||||
16140 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16141 | } else if (CheckInferredResultType) { | ||||
16142 | SrcType = SrcType.getUnqualifiedType(); | ||||
16143 | DstType = DstType.getUnqualifiedType(); | ||||
16144 | } | ||||
16145 | MayHaveConvFixit = true; | ||||
16146 | break; | ||||
16147 | case IncompatiblePointerSign: | ||||
16148 | if (getLangOpts().CPlusPlus) { | ||||
16149 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||
16150 | isInvalid = true; | ||||
16151 | } else { | ||||
16152 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||
16153 | } | ||||
16154 | break; | ||||
16155 | case FunctionVoidPointer: | ||||
16156 | if (getLangOpts().CPlusPlus) { | ||||
16157 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||
16158 | isInvalid = true; | ||||
16159 | } else { | ||||
16160 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||
16161 | } | ||||
16162 | break; | ||||
16163 | case IncompatiblePointerDiscardsQualifiers: { | ||||
16164 | // Perform array-to-pointer decay if necessary. | ||||
16165 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||
16166 | |||||
16167 | isInvalid = true; | ||||
16168 | |||||
16169 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||
16170 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||
16171 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||
16172 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||
16173 | break; | ||||
16174 | |||||
16175 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||
16176 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||
16177 | break; | ||||
16178 | } | ||||
16179 | |||||
16180 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16180); | ||||
16181 | // fallthrough | ||||
16182 | } | ||||
16183 | case CompatiblePointerDiscardsQualifiers: | ||||
16184 | // If the qualifiers lost were because we were applying the | ||||
16185 | // (deprecated) C++ conversion from a string literal to a char* | ||||
16186 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||
16187 | // Ideally, this check would be performed in | ||||
16188 | // checkPointerTypesForAssignment. However, that would require a | ||||
16189 | // bit of refactoring (so that the second argument is an | ||||
16190 | // expression, rather than a type), which should be done as part | ||||
16191 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||
16192 | // C++ semantics. | ||||
16193 | if (getLangOpts().CPlusPlus && | ||||
16194 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||
16195 | return false; | ||||
16196 | if (getLangOpts().CPlusPlus) { | ||||
16197 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||
16198 | isInvalid = true; | ||||
16199 | } else { | ||||
16200 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||
16201 | } | ||||
16202 | |||||
16203 | break; | ||||
16204 | case IncompatibleNestedPointerQualifiers: | ||||
16205 | if (getLangOpts().CPlusPlus) { | ||||
16206 | isInvalid = true; | ||||
16207 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||
16208 | } else { | ||||
16209 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||
16210 | } | ||||
16211 | break; | ||||
16212 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||
16213 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||
16214 | isInvalid = true; | ||||
16215 | break; | ||||
16216 | case IntToBlockPointer: | ||||
16217 | DiagKind = diag::err_int_to_block_pointer; | ||||
16218 | isInvalid = true; | ||||
16219 | break; | ||||
16220 | case IncompatibleBlockPointer: | ||||
16221 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||
16222 | isInvalid = true; | ||||
16223 | break; | ||||
16224 | case IncompatibleObjCQualifiedId: { | ||||
16225 | if (SrcType->isObjCQualifiedIdType()) { | ||||
16226 | const ObjCObjectPointerType *srcOPT = | ||||
16227 | SrcType->castAs<ObjCObjectPointerType>(); | ||||
16228 | for (auto *srcProto : srcOPT->quals()) { | ||||
16229 | PDecl = srcProto; | ||||
16230 | break; | ||||
16231 | } | ||||
16232 | if (const ObjCInterfaceType *IFaceT = | ||||
16233 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
16234 | IFace = IFaceT->getDecl(); | ||||
16235 | } | ||||
16236 | else if (DstType->isObjCQualifiedIdType()) { | ||||
16237 | const ObjCObjectPointerType *dstOPT = | ||||
16238 | DstType->castAs<ObjCObjectPointerType>(); | ||||
16239 | for (auto *dstProto : dstOPT->quals()) { | ||||
16240 | PDecl = dstProto; | ||||
16241 | break; | ||||
16242 | } | ||||
16243 | if (const ObjCInterfaceType *IFaceT = | ||||
16244 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
16245 | IFace = IFaceT->getDecl(); | ||||
16246 | } | ||||
16247 | if (getLangOpts().CPlusPlus) { | ||||
16248 | DiagKind = diag::err_incompatible_qualified_id; | ||||
16249 | isInvalid = true; | ||||
16250 | } else { | ||||
16251 | DiagKind = diag::warn_incompatible_qualified_id; | ||||
16252 | } | ||||
16253 | break; | ||||
16254 | } | ||||
16255 | case IncompatibleVectors: | ||||
16256 | if (getLangOpts().CPlusPlus) { | ||||
16257 | DiagKind = diag::err_incompatible_vectors; | ||||
16258 | isInvalid = true; | ||||
16259 | } else { | ||||
16260 | DiagKind = diag::warn_incompatible_vectors; | ||||
16261 | } | ||||
16262 | break; | ||||
16263 | case IncompatibleObjCWeakRef: | ||||
16264 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||
16265 | isInvalid = true; | ||||
16266 | break; | ||||
16267 | case Incompatible: | ||||
16268 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||
16269 | if (Complained) | ||||
16270 | *Complained = true; | ||||
16271 | return true; | ||||
16272 | } | ||||
16273 | |||||
16274 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||
16275 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
16276 | MayHaveConvFixit = true; | ||||
16277 | isInvalid = true; | ||||
16278 | MayHaveFunctionDiff = true; | ||||
16279 | break; | ||||
16280 | } | ||||
16281 | |||||
16282 | QualType FirstType, SecondType; | ||||
16283 | switch (Action) { | ||||
16284 | case AA_Assigning: | ||||
16285 | case AA_Initializing: | ||||
16286 | // The destination type comes first. | ||||
16287 | FirstType = DstType; | ||||
16288 | SecondType = SrcType; | ||||
16289 | break; | ||||
16290 | |||||
16291 | case AA_Returning: | ||||
16292 | case AA_Passing: | ||||
16293 | case AA_Passing_CFAudited: | ||||
16294 | case AA_Converting: | ||||
16295 | case AA_Sending: | ||||
16296 | case AA_Casting: | ||||
16297 | // The source type comes first. | ||||
16298 | FirstType = SrcType; | ||||
16299 | SecondType = DstType; | ||||
16300 | break; | ||||
16301 | } | ||||
16302 | |||||
16303 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||
16304 | if (Action == AA_Passing_CFAudited) | ||||
16305 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | ||||
16306 | else | ||||
16307 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | ||||
16308 | |||||
16309 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | ||||
16310 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | ||||
16311 | auto isPlainChar = [](const clang::Type *Type) { | ||||
16312 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
16313 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | ||||
16314 | }; | ||||
16315 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | ||||
16316 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | ||||
16317 | } | ||||
16318 | |||||
16319 | // If we can fix the conversion, suggest the FixIts. | ||||
16320 | if (!ConvHints.isNull()) { | ||||
16321 | for (FixItHint &H : ConvHints.Hints) | ||||
16322 | FDiag << H; | ||||
16323 | } | ||||
16324 | |||||
16325 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||
16326 | |||||
16327 | if (MayHaveFunctionDiff) | ||||
16328 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||
16329 | |||||
16330 | Diag(Loc, FDiag); | ||||
16331 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||
16332 | DiagKind == diag::err_incompatible_qualified_id) && | ||||
16333 | PDecl && IFace && !IFace->hasDefinition()) | ||||
16334 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||
16335 | << IFace << PDecl; | ||||
16336 | |||||
16337 | if (SecondType == Context.OverloadTy) | ||||
16338 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||
16339 | FirstType, /*TakingAddress=*/true); | ||||
16340 | |||||
16341 | if (CheckInferredResultType) | ||||
16342 | EmitRelatedResultTypeNote(SrcExpr); | ||||
16343 | |||||
16344 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||
16345 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||
16346 | |||||
16347 | if (Complained) | ||||
16348 | *Complained = true; | ||||
16349 | return isInvalid; | ||||
16350 | } | ||||
16351 | |||||
16352 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16353 | llvm::APSInt *Result, | ||||
16354 | AllowFoldKind CanFold) { | ||||
16355 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||
16356 | public: | ||||
16357 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16358 | QualType T) override { | ||||
16359 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||
16360 | << T << S.LangOpts.CPlusPlus; | ||||
16361 | } | ||||
16362 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16363 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16364 | } | ||||
16365 | } Diagnoser; | ||||
16366 | |||||
16367 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16368 | } | ||||
16369 | |||||
16370 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16371 | llvm::APSInt *Result, | ||||
16372 | unsigned DiagID, | ||||
16373 | AllowFoldKind CanFold) { | ||||
16374 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||
16375 | unsigned DiagID; | ||||
16376 | |||||
16377 | public: | ||||
16378 | IDDiagnoser(unsigned DiagID) | ||||
16379 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||
16380 | |||||
16381 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16382 | return S.Diag(Loc, DiagID); | ||||
16383 | } | ||||
16384 | } Diagnoser(DiagID); | ||||
16385 | |||||
16386 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16387 | } | ||||
16388 | |||||
16389 | Sema::SemaDiagnosticBuilder | ||||
16390 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16391 | QualType T) { | ||||
16392 | return diagnoseNotICE(S, Loc); | ||||
16393 | } | ||||
16394 | |||||
16395 | Sema::SemaDiagnosticBuilder | ||||
16396 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||
16397 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16398 | } | ||||
16399 | |||||
16400 | ExprResult | ||||
16401 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||
16402 | VerifyICEDiagnoser &Diagnoser, | ||||
16403 | AllowFoldKind CanFold) { | ||||
16404 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||
16405 | |||||
16406 | if (getLangOpts().CPlusPlus11) { | ||||
16407 | // C++11 [expr.const]p5: | ||||
16408 | // If an expression of literal class type is used in a context where an | ||||
16409 | // integral constant expression is required, then that class type shall | ||||
16410 | // have a single non-explicit conversion function to an integral or | ||||
16411 | // unscoped enumeration type | ||||
16412 | ExprResult Converted; | ||||
16413 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||
16414 | VerifyICEDiagnoser &BaseDiagnoser; | ||||
16415 | public: | ||||
16416 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||
16417 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||
16418 | BaseDiagnoser.Suppress, true), | ||||
16419 | BaseDiagnoser(BaseDiagnoser) {} | ||||
16420 | |||||
16421 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||
16422 | QualType T) override { | ||||
16423 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||
16424 | } | ||||
16425 | |||||
16426 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||
16427 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16428 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||
16429 | } | ||||
16430 | |||||
16431 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||
16432 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16433 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||
16434 | } | ||||
16435 | |||||
16436 | SemaDiagnosticBuilder noteExplicitConv( | ||||
16437 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16438 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16439 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16440 | } | ||||
16441 | |||||
16442 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||
16443 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16444 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||
16445 | } | ||||
16446 | |||||
16447 | SemaDiagnosticBuilder noteAmbiguous( | ||||
16448 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16449 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16450 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16451 | } | ||||
16452 | |||||
16453 | SemaDiagnosticBuilder diagnoseConversion( | ||||
16454 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16455 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16455); | ||||
16456 | } | ||||
16457 | } ConvertDiagnoser(Diagnoser); | ||||
16458 | |||||
16459 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||
16460 | ConvertDiagnoser); | ||||
16461 | if (Converted.isInvalid()) | ||||
16462 | return Converted; | ||||
16463 | E = Converted.get(); | ||||
16464 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||
16465 | return ExprError(); | ||||
16466 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
16467 | // An ICE must be of integral or unscoped enumeration type. | ||||
16468 | if (!Diagnoser.Suppress) | ||||
16469 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||
16470 | << E->getSourceRange(); | ||||
16471 | return ExprError(); | ||||
16472 | } | ||||
16473 | |||||
16474 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||
16475 | if (RValueExpr.isInvalid()) | ||||
16476 | return ExprError(); | ||||
16477 | |||||
16478 | E = RValueExpr.get(); | ||||
16479 | |||||
16480 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||
16481 | // in the non-ICE case. | ||||
16482 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||
16483 | if (Result) | ||||
16484 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||
16485 | if (!isa<ConstantExpr>(E)) | ||||
16486 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | ||||
16487 | : ConstantExpr::Create(Context, E); | ||||
16488 | return E; | ||||
16489 | } | ||||
16490 | |||||
16491 | Expr::EvalResult EvalResult; | ||||
16492 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16493 | EvalResult.Diag = &Notes; | ||||
16494 | |||||
16495 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||
16496 | // not a constant expression as a side-effect. | ||||
16497 | bool Folded = | ||||
16498 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||
16499 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||
16500 | |||||
16501 | if (!isa<ConstantExpr>(E)) | ||||
16502 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||
16503 | |||||
16504 | // In C++11, we can rely on diagnostics being produced for any expression | ||||
16505 | // which is not a constant expression. If no diagnostics were produced, then | ||||
16506 | // this is a constant expression. | ||||
16507 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||
16508 | if (Result) | ||||
16509 | *Result = EvalResult.Val.getInt(); | ||||
16510 | return E; | ||||
16511 | } | ||||
16512 | |||||
16513 | // If our only note is the usual "invalid subexpression" note, just point | ||||
16514 | // the caret at its location rather than producing an essentially | ||||
16515 | // redundant note. | ||||
16516 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
16517 | diag::note_invalid_subexpr_in_const_expr) { | ||||
16518 | DiagLoc = Notes[0].first; | ||||
16519 | Notes.clear(); | ||||
16520 | } | ||||
16521 | |||||
16522 | if (!Folded || !CanFold) { | ||||
16523 | if (!Diagnoser.Suppress) { | ||||
16524 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||
16525 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16526 | Diag(Note.first, Note.second); | ||||
16527 | } | ||||
16528 | |||||
16529 | return ExprError(); | ||||
16530 | } | ||||
16531 | |||||
16532 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||
16533 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16534 | Diag(Note.first, Note.second); | ||||
16535 | |||||
16536 | if (Result) | ||||
16537 | *Result = EvalResult.Val.getInt(); | ||||
16538 | return E; | ||||
16539 | } | ||||
16540 | |||||
16541 | namespace { | ||||
16542 | // Handle the case where we conclude a expression which we speculatively | ||||
16543 | // considered to be unevaluated is actually evaluated. | ||||
16544 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||
16545 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||
16546 | |||||
16547 | public: | ||||
16548 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||
16549 | |||||
16550 | // Make sure we redo semantic analysis | ||||
16551 | bool AlwaysRebuild() { return true; } | ||||
16552 | bool ReplacingOriginal() { return true; } | ||||
16553 | |||||
16554 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||
16555 | // are not part of a member pointer formation; normal TreeTransforming | ||||
16556 | // doesn't catch this case because of the way we represent them in the AST. | ||||
16557 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||
16558 | // case? | ||||
16559 | // | ||||
16560 | // Error on DeclRefExprs referring to FieldDecls. | ||||
16561 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16562 | if (isa<FieldDecl>(E->getDecl()) && | ||||
16563 | !SemaRef.isUnevaluatedContext()) | ||||
16564 | return SemaRef.Diag(E->getLocation(), | ||||
16565 | diag::err_invalid_non_static_member_use) | ||||
16566 | << E->getDecl() << E->getSourceRange(); | ||||
16567 | |||||
16568 | return BaseTransform::TransformDeclRefExpr(E); | ||||
16569 | } | ||||
16570 | |||||
16571 | // Exception: filter out member pointer formation | ||||
16572 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||
16573 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||
16574 | return E; | ||||
16575 | |||||
16576 | return BaseTransform::TransformUnaryOperator(E); | ||||
16577 | } | ||||
16578 | |||||
16579 | // The body of a lambda-expression is in a separate expression evaluation | ||||
16580 | // context so never needs to be transformed. | ||||
16581 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||
16582 | // just recreate the capture expressions and lambda expression. | ||||
16583 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||
16584 | return SkipLambdaBody(E, Body); | ||||
16585 | } | ||||
16586 | }; | ||||
16587 | } | ||||
16588 | |||||
16589 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||
16590 | assert(isUnevaluatedContext() &&(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16591, __extension__ __PRETTY_FUNCTION__)) | ||||
16591 | "Should only transform unevaluated expressions")(static_cast <bool> (isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? void (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16591, __extension__ __PRETTY_FUNCTION__)); | ||||
16592 | ExprEvalContexts.back().Context = | ||||
16593 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||
16594 | if (isUnevaluatedContext()) | ||||
16595 | return E; | ||||
16596 | return TransformToPE(*this).TransformExpr(E); | ||||
16597 | } | ||||
16598 | |||||
16599 | void | ||||
16600 | Sema::PushExpressionEvaluationContext( | ||||
16601 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||
16602 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16603 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||
16604 | LambdaContextDecl, ExprContext); | ||||
16605 | Cleanup.reset(); | ||||
16606 | if (!MaybeODRUseExprs.empty()) | ||||
16607 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||
16608 | } | ||||
16609 | |||||
16610 | void | ||||
16611 | Sema::PushExpressionEvaluationContext( | ||||
16612 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||
16613 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16614 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||
16615 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||
16616 | } | ||||
16617 | |||||
16618 | namespace { | ||||
16619 | |||||
16620 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||
16621 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||
16622 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||
16623 | if (E->getOpcode() == UO_Deref) | ||||
16624 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||
16625 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||
16626 | return CheckPossibleDeref(S, E->getBase()); | ||||
16627 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||
16628 | return CheckPossibleDeref(S, E->getBase()); | ||||
16629 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||
16630 | QualType Inner; | ||||
16631 | QualType Ty = E->getType(); | ||||
16632 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||
16633 | Inner = Ptr->getPointeeType(); | ||||
16634 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||
16635 | Inner = Arr->getElementType(); | ||||
16636 | else | ||||
16637 | return nullptr; | ||||
16638 | |||||
16639 | if (Inner->hasAttr(attr::NoDeref)) | ||||
16640 | return E; | ||||
16641 | } | ||||
16642 | return nullptr; | ||||
16643 | } | ||||
16644 | |||||
16645 | } // namespace | ||||
16646 | |||||
16647 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||
16648 | for (const Expr *E : Rec.PossibleDerefs) { | ||||
16649 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||
16650 | if (DeclRef) { | ||||
16651 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||
16652 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||
16653 | << Decl->getName() << E->getSourceRange(); | ||||
16654 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||
16655 | } else { | ||||
16656 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||
16657 | << E->getSourceRange(); | ||||
16658 | } | ||||
16659 | } | ||||
16660 | Rec.PossibleDerefs.clear(); | ||||
16661 | } | ||||
16662 | |||||
16663 | /// Check whether E, which is either a discarded-value expression or an | ||||
16664 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||
16665 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||
16666 | /// we are going to warn are deprecated. | ||||
16667 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||
16668 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||
16669 | return; | ||||
16670 | |||||
16671 | // Note: ignoring parens here is not justified by the standard rules, but | ||||
16672 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||
16673 | // drives a deprecation warning so doesn't affect conformance. | ||||
16674 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||
16675 | if (BO->getOpcode() == BO_Assign) { | ||||
16676 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||
16677 | LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), | ||||
16678 | LHSs.end()); | ||||
16679 | } | ||||
16680 | } | ||||
16681 | } | ||||
16682 | |||||
16683 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||
16684 | if (isUnevaluatedContext() || !E.isUsable() || !Decl || | ||||
16685 | !Decl->isConsteval() || isConstantEvaluated() || | ||||
16686 | RebuildingImmediateInvocation) | ||||
16687 | return E; | ||||
16688 | |||||
16689 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||
16690 | /// It's OK if this fails; we'll also remove this in | ||||
16691 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||
16692 | /// walking the AST looking for it in simple cases. | ||||
16693 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||
16694 | if (auto *DeclRef = | ||||
16695 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||
16696 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||
16697 | |||||
16698 | E = MaybeCreateExprWithCleanups(E); | ||||
16699 | |||||
16700 | ConstantExpr *Res = ConstantExpr::Create( | ||||
16701 | getASTContext(), E.get(), | ||||
16702 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||
16703 | getASTContext()), | ||||
16704 | /*IsImmediateInvocation*/ true); | ||||
16705 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||
16706 | return Res; | ||||
16707 | } | ||||
16708 | |||||
16709 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||
16710 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||
16711 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16712 | Expr::EvalResult Eval; | ||||
16713 | Eval.Diag = &Notes; | ||||
16714 | ConstantExpr *CE = Candidate.getPointer(); | ||||
16715 | bool Result = CE->EvaluateAsConstantExpr( | ||||
16716 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||
16717 | if (!Result || !Notes.empty()) { | ||||
16718 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||
16719 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||
16720 | InnerExpr = FunctionalCast->getSubExpr(); | ||||
16721 | FunctionDecl *FD = nullptr; | ||||
16722 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||
16723 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||
16724 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||
16725 | FD = Call->getConstructor(); | ||||
16726 | else | ||||
16727 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16727); | ||||
16728 | assert(FD->isConsteval())(static_cast <bool> (FD->isConsteval()) ? void (0) : __assert_fail ("FD->isConsteval()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16728, __extension__ __PRETTY_FUNCTION__)); | ||||
16729 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||
16730 | for (auto &Note : Notes) | ||||
16731 | SemaRef.Diag(Note.first, Note.second); | ||||
16732 | return; | ||||
16733 | } | ||||
16734 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||
16735 | } | ||||
16736 | |||||
16737 | static void RemoveNestedImmediateInvocation( | ||||
16738 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||
16739 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||
16740 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||
16741 | using Base = TreeTransform<ComplexRemove>; | ||||
16742 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16743 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||
16744 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||
16745 | CurrentII; | ||||
16746 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||
16747 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||
16748 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||
16749 | 4>::reverse_iterator Current) | ||||
16750 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||
16751 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||
16752 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||
16753 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||
16754 | return Elem.getPointer() == E; | ||||
16755 | }); | ||||
16756 | assert(It != IISet.rend() &&(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16758, __extension__ __PRETTY_FUNCTION__)) | ||||
16757 | "ConstantExpr marked IsImmediateInvocation should "(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16758, __extension__ __PRETTY_FUNCTION__)) | ||||
16758 | "be present")(static_cast <bool> (It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? void (0) : __assert_fail ("It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16758, __extension__ __PRETTY_FUNCTION__)); | ||||
16759 | It->setInt(1); // Mark as deleted | ||||
16760 | } | ||||
16761 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||
16762 | if (!E->isImmediateInvocation()) | ||||
16763 | return Base::TransformConstantExpr(E); | ||||
16764 | RemoveImmediateInvocation(E); | ||||
16765 | return Base::TransformExpr(E->getSubExpr()); | ||||
16766 | } | ||||
16767 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||
16768 | /// we need to remove its DeclRefExpr from the DRSet. | ||||
16769 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
16770 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||
16771 | return Base::TransformCXXOperatorCallExpr(E); | ||||
16772 | } | ||||
16773 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||
16774 | /// here. | ||||
16775 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||
16776 | if (!Init) | ||||
16777 | return Init; | ||||
16778 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||
16779 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||
16780 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
16781 | if (CE->isImmediateInvocation()) | ||||
16782 | RemoveImmediateInvocation(CE); | ||||
16783 | return Base::TransformInitializer(Init, NotCopyInit); | ||||
16784 | } | ||||
16785 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16786 | DRSet.erase(E); | ||||
16787 | return E; | ||||
16788 | } | ||||
16789 | bool AlwaysRebuild() { return false; } | ||||
16790 | bool ReplacingOriginal() { return true; } | ||||
16791 | bool AllowSkippingCXXConstructExpr() { | ||||
16792 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||
16793 | AllowSkippingFirstCXXConstructExpr = true; | ||||
16794 | return Res; | ||||
16795 | } | ||||
16796 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||
16797 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||
16798 | Rec.ImmediateInvocationCandidates, It); | ||||
16799 | |||||
16800 | /// CXXConstructExpr with a single argument are getting skipped by | ||||
16801 | /// TreeTransform in some situtation because they could be implicit. This | ||||
16802 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||
16803 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||
16804 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||
16805 | /// skipping the first CXXConstructExpr. | ||||
16806 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||
16807 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||
16808 | |||||
16809 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||
16810 | assert(Res.isUsable())(static_cast <bool> (Res.isUsable()) ? void (0) : __assert_fail ("Res.isUsable()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16810, __extension__ __PRETTY_FUNCTION__)); | ||||
16811 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||
16812 | It->getPointer()->setSubExpr(Res.get()); | ||||
16813 | } | ||||
16814 | |||||
16815 | static void | ||||
16816 | HandleImmediateInvocations(Sema &SemaRef, | ||||
16817 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||
16818 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||
16819 | Rec.ReferenceToConsteval.size() == 0) || | ||||
16820 | SemaRef.RebuildingImmediateInvocation) | ||||
16821 | return; | ||||
16822 | |||||
16823 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||
16824 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||
16825 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||
16826 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||
16827 | |||||
16828 | /// Prevent sema calls during the tree transform from adding pointers that | ||||
16829 | /// are already in the sets. | ||||
16830 | llvm::SaveAndRestore<bool> DisableIITracking( | ||||
16831 | SemaRef.RebuildingImmediateInvocation, true); | ||||
16832 | |||||
16833 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||
16834 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||
16835 | |||||
16836 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||
16837 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||
16838 | if (!It->getInt()) | ||||
16839 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||
16840 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||
16841 | Rec.ReferenceToConsteval.size()) { | ||||
16842 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||
16843 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16844 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||
16845 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||
16846 | DRSet.erase(E); | ||||
16847 | return DRSet.size(); | ||||
16848 | } | ||||
16849 | } Visitor(Rec.ReferenceToConsteval); | ||||
16850 | Visitor.TraverseStmt( | ||||
16851 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||
16852 | } | ||||
16853 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||
16854 | if (!CE.getInt()) | ||||
16855 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||
16856 | for (auto DR : Rec.ReferenceToConsteval) { | ||||
16857 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||
16858 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||
16859 | << FD; | ||||
16860 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||
16861 | } | ||||
16862 | } | ||||
16863 | |||||
16864 | void Sema::PopExpressionEvaluationContext() { | ||||
16865 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||
16866 | unsigned NumTypos = Rec.NumTypos; | ||||
16867 | |||||
16868 | if (!Rec.Lambdas.empty()) { | ||||
16869 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||
16870 | if (!getLangOpts().CPlusPlus20 && | ||||
16871 | (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || | ||||
16872 | Rec.isUnevaluated() || | ||||
16873 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { | ||||
16874 | unsigned D; | ||||
16875 | if (Rec.isUnevaluated()) { | ||||
16876 | // C++11 [expr.prim.lambda]p2: | ||||
16877 | // A lambda-expression shall not appear in an unevaluated operand | ||||
16878 | // (Clause 5). | ||||
16879 | D = diag::err_lambda_unevaluated_operand; | ||||
16880 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||
16881 | // C++1y [expr.const]p2: | ||||
16882 | // A conditional-expression e is a core constant expression unless the | ||||
16883 | // evaluation of e, following the rules of the abstract machine, would | ||||
16884 | // evaluate [...] a lambda-expression. | ||||
16885 | D = diag::err_lambda_in_constant_expression; | ||||
16886 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||
16887 | // C++17 [expr.prim.lamda]p2: | ||||
16888 | // A lambda-expression shall not appear [...] in a template-argument. | ||||
16889 | D = diag::err_lambda_in_invalid_context; | ||||
16890 | } else | ||||
16891 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16891); | ||||
16892 | |||||
16893 | for (const auto *L : Rec.Lambdas) | ||||
16894 | Diag(L->getBeginLoc(), D); | ||||
16895 | } | ||||
16896 | } | ||||
16897 | |||||
16898 | WarnOnPendingNoDerefs(Rec); | ||||
16899 | HandleImmediateInvocations(*this, Rec); | ||||
16900 | |||||
16901 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||
16902 | // value expressions nor unevaluated operands (those cases get removed from | ||||
16903 | // this list by CheckUnusedVolatileAssignment). | ||||
16904 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||
16905 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||
16906 | << BO->getType(); | ||||
16907 | |||||
16908 | // When are coming out of an unevaluated context, clear out any | ||||
16909 | // temporaries that we may have created as part of the evaluation of | ||||
16910 | // the expression in that context: they aren't relevant because they | ||||
16911 | // will never be constructed. | ||||
16912 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||
16913 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||
16914 | ExprCleanupObjects.end()); | ||||
16915 | Cleanup = Rec.ParentCleanup; | ||||
16916 | CleanupVarDeclMarking(); | ||||
16917 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||
16918 | // Otherwise, merge the contexts together. | ||||
16919 | } else { | ||||
16920 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||
16921 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||
16922 | Rec.SavedMaybeODRUseExprs.end()); | ||||
16923 | } | ||||
16924 | |||||
16925 | // Pop the current expression evaluation context off the stack. | ||||
16926 | ExprEvalContexts.pop_back(); | ||||
16927 | |||||
16928 | // The global expression evaluation context record is never popped. | ||||
16929 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||
16930 | } | ||||
16931 | |||||
16932 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||
16933 | ExprCleanupObjects.erase( | ||||
16934 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||
16935 | ExprCleanupObjects.end()); | ||||
16936 | Cleanup.reset(); | ||||
16937 | MaybeODRUseExprs.clear(); | ||||
16938 | } | ||||
16939 | |||||
16940 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||
16941 | ExprResult Result = CheckPlaceholderExpr(E); | ||||
16942 | if (Result.isInvalid()) | ||||
16943 | return ExprError(); | ||||
16944 | E = Result.get(); | ||||
16945 | if (!E->getType()->isVariablyModifiedType()) | ||||
16946 | return E; | ||||
16947 | return TransformToPotentiallyEvaluated(E); | ||||
16948 | } | ||||
16949 | |||||
16950 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||
16951 | /// [expr.const]p12? | ||||
16952 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||
16953 | /// C++2a [expr.const]p12: | ||||
16954 | // An expression or conversion is potentially constant evaluated if it is | ||||
16955 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
16956 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
16957 | // -- a manifestly constant-evaluated expression, | ||||
16958 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
16959 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
16960 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
16961 | // -- a potentially-evaluated expression, | ||||
16962 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
16963 | // -- an immediate subexpression of a braced-init-list, | ||||
16964 | |||||
16965 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||
16966 | // within a templated entity | ||||
16967 | // -- a subexpression of one of the above that is not a subexpression of | ||||
16968 | // a nested unevaluated operand. | ||||
16969 | return true; | ||||
16970 | |||||
16971 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
16972 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
16973 | // Expressions in this context are never evaluated. | ||||
16974 | return false; | ||||
16975 | } | ||||
16976 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 16976); | ||||
16977 | } | ||||
16978 | |||||
16979 | /// Return true if this function has a calling convention that requires mangling | ||||
16980 | /// in the size of the parameter pack. | ||||
16981 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||
16982 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||
16983 | // we don't need parameter type sizes. | ||||
16984 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||
16985 | if (!TT.isOSWindows() || !TT.isX86()) | ||||
16986 | return false; | ||||
16987 | |||||
16988 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||
16989 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||
16990 | // use the size of the parameters. | ||||
16991 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||
16992 | return false; | ||||
16993 | |||||
16994 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||
16995 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
16996 | switch (CC) { | ||||
16997 | case CC_X86StdCall: | ||||
16998 | case CC_X86FastCall: | ||||
16999 | case CC_X86VectorCall: | ||||
17000 | return true; | ||||
17001 | default: | ||||
17002 | break; | ||||
17003 | } | ||||
17004 | return false; | ||||
17005 | } | ||||
17006 | |||||
17007 | /// Require that all of the parameter types of function be complete. Normally, | ||||
17008 | /// parameter types are only required to be complete when a function is called | ||||
17009 | /// or defined, but to mangle functions with certain calling conventions, the | ||||
17010 | /// mangler needs to know the size of the parameter list. In this situation, | ||||
17011 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||
17012 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||
17013 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||
17014 | /// attempts to error at compile time. | ||||
17015 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||
17016 | SourceLocation Loc) { | ||||
17017 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||
17018 | FunctionDecl *FD; | ||||
17019 | ParmVarDecl *Param; | ||||
17020 | |||||
17021 | public: | ||||
17022 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||
17023 | : FD(FD), Param(Param) {} | ||||
17024 | |||||
17025 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
17026 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
17027 | StringRef CCName; | ||||
17028 | switch (CC) { | ||||
17029 | case CC_X86StdCall: | ||||
17030 | CCName = "stdcall"; | ||||
17031 | break; | ||||
17032 | case CC_X86FastCall: | ||||
17033 | CCName = "fastcall"; | ||||
17034 | break; | ||||
17035 | case CC_X86VectorCall: | ||||
17036 | CCName = "vectorcall"; | ||||
17037 | break; | ||||
17038 | default: | ||||
17039 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 17039); | ||||
17040 | } | ||||
17041 | |||||
17042 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||
17043 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||
17044 | } | ||||
17045 | }; | ||||
17046 | |||||
17047 | for (ParmVarDecl *Param : FD->parameters()) { | ||||
17048 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||
17049 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||
17050 | } | ||||
17051 | } | ||||
17052 | |||||
17053 | namespace { | ||||
17054 | enum class OdrUseContext { | ||||
17055 | /// Declarations in this context are not odr-used. | ||||
17056 | None, | ||||
17057 | /// Declarations in this context are formally odr-used, but this is a | ||||
17058 | /// dependent context. | ||||
17059 | Dependent, | ||||
17060 | /// Declarations in this context are odr-used but not actually used (yet). | ||||
17061 | FormallyOdrUsed, | ||||
17062 | /// Declarations in this context are used. | ||||
17063 | Used | ||||
17064 | }; | ||||
17065 | } | ||||
17066 | |||||
17067 | /// Are we within a context in which references to resolved functions or to | ||||
17068 | /// variables result in odr-use? | ||||
17069 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||
17070 | OdrUseContext Result; | ||||
17071 | |||||
17072 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
17073 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
17074 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
17075 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
17076 | return OdrUseContext::None; | ||||
17077 | |||||
17078 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
17079 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
17080 | Result = OdrUseContext::Used; | ||||
17081 | break; | ||||
17082 | |||||
17083 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
17084 | Result = OdrUseContext::FormallyOdrUsed; | ||||
17085 | break; | ||||
17086 | |||||
17087 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
17088 | // A default argument formally results in odr-use, but doesn't actually | ||||
17089 | // result in a use in any real sense until it itself is used. | ||||
17090 | Result = OdrUseContext::FormallyOdrUsed; | ||||
17091 | break; | ||||
17092 | } | ||||
17093 | |||||
17094 | if (SemaRef.CurContext->isDependentContext()) | ||||
17095 | return OdrUseContext::Dependent; | ||||
17096 | |||||
17097 | return Result; | ||||
17098 | } | ||||
17099 | |||||
17100 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||
17101 | if (!Func->isConstexpr()) | ||||
17102 | return false; | ||||
17103 | |||||
17104 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||
17105 | return true; | ||||
17106 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||
17107 | return CCD && CCD->getInheritedConstructor(); | ||||
17108 | } | ||||
17109 | |||||
17110 | /// Mark a function referenced, and check whether it is odr-used | ||||
17111 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||
17112 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||
17113 | bool MightBeOdrUse) { | ||||
17114 | assert(Func && "No function?")(static_cast <bool> (Func && "No function?") ? void (0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 17114, __extension__ __PRETTY_FUNCTION__)); | ||||
17115 | |||||
17116 | Func->setReferenced(); | ||||
17117 | |||||
17118 | // Recursive functions aren't really used until they're used from some other | ||||
17119 | // context. | ||||
17120 | bool IsRecursiveCall = CurContext == Func; | ||||
17121 | |||||
17122 | // C++11 [basic.def.odr]p3: | ||||
17123 | // A function whose name appears as a potentially-evaluated expression is | ||||
17124 | // odr-used if it is the unique lookup result or the selected member of a | ||||
17125 | // set of overloaded functions [...]. | ||||
17126 | // | ||||
17127 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||
17128 | // can just check that here. | ||||
17129 | OdrUseContext OdrUse = | ||||
17130 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||
17131 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||
17132 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17133 | |||||
17134 | // Trivial default constructors and destructors are never actually used. | ||||
17135 | // FIXME: What about other special members? | ||||
17136 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||
17137 | OdrUse == OdrUseContext::Used) { | ||||
17138 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||
17139 | if (Constructor->isDefaultConstructor()) | ||||
17140 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17141 | if (isa<CXXDestructorDecl>(Func)) | ||||
17142 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
17143 | } | ||||
17144 | |||||
17145 | // C++20 [expr.const]p12: | ||||
17146 | // A function [...] is needed for constant evaluation if it is [...] a | ||||
17147 | // constexpr function that is named by an expression that is potentially | ||||
17148 | // constant evaluated | ||||
17149 | bool NeededForConstantEvaluation = | ||||
17150 | isPotentiallyConstantEvaluatedContext(*this) && | ||||
17151 | isImplicitlyDefinableConstexprFunction(Func); | ||||
17152 | |||||
17153 | // Determine whether we require a function definition to exist, per | ||||
17154 | // C++11 [temp.inst]p3: | ||||
17155 | // Unless a function template specialization has been explicitly | ||||
17156 | // instantiated or explicitly specialized, the function template | ||||
17157 | // specialization is implicitly instantiated when the specialization is | ||||
17158 | // referenced in a context that requires a function definition to exist. | ||||
17159 | // C++20 [temp.inst]p7: | ||||
17160 | // The existence of a definition of a [...] function is considered to | ||||
17161 | // affect the semantics of the program if the [...] function is needed for | ||||
17162 | // constant evaluation by an expression | ||||
17163 | // C++20 [basic.def.odr]p10: | ||||
17164 | // Every program shall contain exactly one definition of every non-inline | ||||
17165 | // function or variable that is odr-used in that program outside of a | ||||
17166 | // discarded statement | ||||
17167 | // C++20 [special]p1: | ||||
17168 | // The implementation will implicitly define [defaulted special members] | ||||
17169 | // if they are odr-used or needed for constant evaluation. | ||||
17170 | // | ||||
17171 | // Note that we skip the implicit instantiation of templates that are only | ||||
17172 | // used in unused default arguments or by recursive calls to themselves. | ||||
17173 | // This is formally non-conforming, but seems reasonable in practice. | ||||
17174 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||
17175 | NeededForConstantEvaluation); | ||||
17176 | |||||
17177 | // C++14 [temp.expl.spec]p6: | ||||
17178 | // If a template [...] is explicitly specialized then that specialization | ||||
17179 | // shall be declared before the first use of that specialization that would | ||||
17180 | // cause an implicit instantiation to take place, in every translation unit | ||||
17181 | // in which such a use occurs | ||||
17182 | if (NeedDefinition && | ||||
17183 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||
17184 | Func->getMemberSpecializationInfo())) | ||||
17185 | checkSpecializationVisibility(Loc, Func); | ||||
17186 | |||||
17187 | if (getLangOpts().CUDA) | ||||
17188 | CheckCUDACall(Loc, Func); | ||||
17189 | |||||
17190 | if (getLangOpts().SYCLIsDevice) | ||||
17191 | checkSYCLDeviceFunction(Loc, Func); | ||||
17192 | |||||
17193 | // If we need a definition, try to create one. | ||||
17194 | if (NeedDefinition && !Func->getBody()) { | ||||
17195 | runWithSufficientStackSpace(Loc, [&] { | ||||
17196 | if (CXXConstructorDecl *Constructor = | ||||
17197 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||
17198 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||
17199 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||
17200 | if (Constructor->isDefaultConstructor()) { | ||||
17201 | if (Constructor->isTrivial() && | ||||
17202 | !Constructor->hasAttr<DLLExportAttr>()) | ||||
17203 | return; | ||||
17204 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
17205 | } else if (Constructor->isCopyConstructor()) { | ||||
17206 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||
17207 | } else if (Constructor->isMoveConstructor()) { | ||||
17208 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||
17209 | } | ||||
17210 | } else if (Constructor->getInheritedConstructor()) { | ||||
17211 | DefineInheritingConstructor(Loc, Constructor); | ||||
17212 | } | ||||
17213 | } else if (CXXDestructorDecl *Destructor = | ||||
17214 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||
17215 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||
17216 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||
17217 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||
17218 | return; | ||||
17219 | DefineImplicitDestructor(Loc, Destructor); | ||||
17220 | } | ||||
17221 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||
17222 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||
17223 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||
17224 | if (MethodDecl->isOverloadedOperator() && | ||||
17225 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||
17226 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||
17227 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||
17228 | if (MethodDecl->isCopyAssignmentOperator()) | ||||
17229 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||
17230 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||
17231 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||
17232 | } | ||||
17233 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||
17234 | MethodDecl->getParent()->isLambda()) { | ||||
17235 | CXXConversionDecl *Conversion = | ||||
17236 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||
17237 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||
17238 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||
17239 | else | ||||
17240 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||
17241 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||
17242 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||
17243 | } | ||||
17244 | |||||
17245 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||
17246 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||
17247 | if (DCK != DefaultedComparisonKind::None) | ||||
17248 | DefineDefaultedComparison(Loc, Func, DCK); | ||||
17249 | } | ||||
17250 | |||||
17251 | // Implicit instantiation of function templates and member functions of | ||||
17252 | // class templates. | ||||
17253 | if (Func->isImplicitlyInstantiable()) { | ||||
17254 | TemplateSpecializationKind TSK = | ||||
17255 | Func->getTemplateSpecializationKindForInstantiation(); | ||||
17256 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||
17257 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
17258 | if (FirstInstantiation) { | ||||
17259 | PointOfInstantiation = Loc; | ||||
17260 | if (auto *MSI = Func->getMemberSpecializationInfo()) | ||||
17261 | MSI->setPointOfInstantiation(Loc); | ||||
17262 | // FIXME: Notify listener. | ||||
17263 | else | ||||
17264 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
17265 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||
17266 | // Use the point of use as the point of instantiation, instead of the | ||||
17267 | // point of explicit instantiation (which we track as the actual point | ||||
17268 | // of instantiation). This gives better backtraces in diagnostics. | ||||
17269 | PointOfInstantiation = Loc; | ||||
17270 | } | ||||
17271 | |||||
17272 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||
17273 | Func->isConstexpr()) { | ||||
17274 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||
17275 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||
17276 | CodeSynthesisContexts.size()) | ||||
17277 | PendingLocalImplicitInstantiations.push_back( | ||||
17278 | std::make_pair(Func, PointOfInstantiation)); | ||||
17279 | else if (Func->isConstexpr()) | ||||
17280 | // Do not defer instantiations of constexpr functions, to avoid the | ||||
17281 | // expression evaluator needing to call back into Sema if it sees a | ||||
17282 | // call to such a function. | ||||
17283 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||
17284 | else { | ||||
17285 | Func->setInstantiationIsPending(true); | ||||
17286 | PendingInstantiations.push_back( | ||||
17287 | std::make_pair(Func, PointOfInstantiation)); | ||||
17288 | // Notify the consumer that a function was implicitly instantiated. | ||||
17289 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||
17290 | } | ||||
17291 | } | ||||
17292 | } else { | ||||
17293 | // Walk redefinitions, as some of them may be instantiable. | ||||
17294 | for (auto i : Func->redecls()) { | ||||
17295 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||
17296 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||
17297 | } | ||||
17298 | } | ||||
17299 | }); | ||||
17300 | } | ||||
17301 | |||||
17302 | // C++14 [except.spec]p17: | ||||
17303 | // An exception-specification is considered to be needed when: | ||||
17304 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||
17305 | // would be odr-used if the expression were potentially-evaluated; | ||||
17306 | // | ||||
17307 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||
17308 | // function is a pure virtual function we're calling, and in that case the | ||||
17309 | // function was selected by overload resolution and we need to resolve its | ||||
17310 | // exception specification for a different reason. | ||||
17311 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||
17312 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||
17313 | ResolveExceptionSpec(Loc, FPT); | ||||
17314 | |||||
17315 | // If this is the first "real" use, act on that. | ||||
17316 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||
17317 | // Keep track of used but undefined functions. | ||||
17318 | if (!Func->isDefined()) { | ||||
17319 | if (mightHaveNonExternalLinkage(Func)) | ||||
17320 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17321 | else if (Func->getMostRecentDecl()->isInlined() && | ||||
17322 | !LangOpts.GNUInline && | ||||
17323 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||
17324 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17325 | else if (isExternalWithNoLinkageType(Func)) | ||||
17326 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
17327 | } | ||||
17328 | |||||
17329 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||
17330 | // pack into the name. Computing the size of the parameters requires the | ||||
17331 | // parameter types to be complete. Check that now. | ||||
17332 | if (funcHasParameterSizeMangling(*this, Func)) | ||||
17333 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||
17334 | |||||
17335 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||
17336 | // used. If the destructor is used here but defined elsewhere, mark the | ||||
17337 | // virtual base destructors referenced. If those virtual base destructors | ||||
17338 | // are inline, this will ensure they are defined when emitting the complete | ||||
17339 | // destructor variant. This checking may be redundant if the destructor is | ||||
17340 | // provided later in this TU. | ||||
17341 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
17342 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||
17343 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||
17344 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||
17345 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||
17346 | } | ||||
17347 | } | ||||
17348 | |||||
17349 | Func->markUsed(Context); | ||||
17350 | } | ||||
17351 | } | ||||
17352 | |||||
17353 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||
17354 | /// MarkVariableReferenced since it does additional checks and then | ||||
17355 | /// calls MarkVarDeclODRUsed. | ||||
17356 | /// If the variable must be captured: | ||||
17357 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||
17358 | /// - else capture it in the DeclContext that maps to the | ||||
17359 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||
17360 | static void | ||||
17361 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | ||||
17362 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||
17363 | // Keep track of used but undefined variables. | ||||
17364 | // FIXME: We shouldn't suppress this warning for static data members. | ||||
17365 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||
17366 | (!Var->isExternallyVisible() || Var->isInline() || | ||||
17367 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||
17368 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||
17369 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||
17370 | if (old.isInvalid()) | ||||
17371 | old = Loc; | ||||
17372 | } | ||||
17373 | QualType CaptureType, DeclRefType; | ||||
17374 | if (SemaRef.LangOpts.OpenMP) | ||||
17375 | SemaRef.tryCaptureOpenMPLambdas(Var); | ||||
17376 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | ||||
17377 | /*EllipsisLoc*/ SourceLocation(), | ||||
17378 | /*BuildAndDiagnose*/ true, | ||||
17379 | CaptureType, DeclRefType, | ||||
17380 | FunctionScopeIndexToStopAt); | ||||
17381 | |||||
17382 | if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { | ||||
17383 | auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); | ||||
17384 | auto VarTarget = SemaRef.IdentifyCUDATarget(Var); | ||||
17385 | auto UserTarget = SemaRef.IdentifyCUDATarget(FD); | ||||
17386 | if (VarTarget == Sema::CVT_Host && | ||||
17387 | (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || | ||||
17388 | UserTarget == Sema::CFT_Global)) { | ||||
17389 | // Diagnose ODR-use of host global variables in device functions. | ||||
17390 | // Reference of device global variables in host functions is allowed | ||||
17391 | // through shadow variables therefore it is not diagnosed. | ||||
17392 | if (SemaRef.LangOpts.CUDAIsDevice) { | ||||
17393 | SemaRef.targetDiag(Loc, diag::err_ref_bad_target) | ||||
17394 | << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; | ||||
17395 | SemaRef.targetDiag(Var->getLocation(), | ||||
17396 | Var->getType().isConstQualified() | ||||
17397 | ? diag::note_cuda_const_var_unpromoted | ||||
17398 | : diag::note_cuda_host_var); | ||||
17399 | } | ||||
17400 | } else if (VarTarget == Sema::CVT_Device && | ||||
17401 | (UserTarget == Sema::CFT_Host || | ||||
17402 | UserTarget == Sema::CFT_HostDevice) && | ||||
17403 | !Var->hasExternalStorage()) { | ||||
17404 | // Record a CUDA/HIP device side variable if it is ODR-used | ||||
17405 | // by host code. This is done conservatively, when the variable is | ||||
17406 | // referenced in any of the following contexts: | ||||
17407 | // - a non-function context | ||||
17408 | // - a host function | ||||
17409 | // - a host device function | ||||
17410 | // This makes the ODR-use of the device side variable by host code to | ||||
17411 | // be visible in the device compilation for the compiler to be able to | ||||
17412 | // emit template variables instantiated by host code only and to | ||||
17413 | // externalize the static device side variable ODR-used by host code. | ||||
17414 | SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); | ||||
17415 | } | ||||
17416 | } | ||||
17417 | |||||
17418 | Var->markUsed(SemaRef.Context); | ||||
17419 | } | ||||
17420 | |||||
17421 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | ||||
17422 | SourceLocation Loc, | ||||
17423 | unsigned CapturingScopeIndex) { | ||||
17424 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||
17425 | } | ||||
17426 | |||||
17427 | static void | ||||
17428 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
17429 | ValueDecl *var, DeclContext *DC) { | ||||
17430 | DeclContext *VarDC = var->getDeclContext(); | ||||
17431 | |||||
17432 | // If the parameter still belongs to the translation unit, then | ||||
17433 | // we're actually just using one parameter in the declaration of | ||||
17434 | // the next. | ||||
17435 | if (isa<ParmVarDecl>(var) && | ||||
17436 | isa<TranslationUnitDecl>(VarDC)) | ||||
17437 | return; | ||||
17438 | |||||
17439 | // For C code, don't diagnose about capture if we're not actually in code | ||||
17440 | // right now; it's impossible to write a non-constant expression outside of | ||||
17441 | // function context, so we'll get other (more useful) diagnostics later. | ||||
17442 | // | ||||
17443 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||
17444 | // diagnostic for certain cases like using a local variable in an array bound | ||||
17445 | // for a member of a local class, but the correct predicate is not obvious. | ||||
17446 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||
17447 | return; | ||||
17448 | |||||
17449 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||
17450 | unsigned ContextKind = 3; // unknown | ||||
17451 | if (isa<CXXMethodDecl>(VarDC) && | ||||
17452 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||
17453 | ContextKind = 2; | ||||
17454 | } else if (isa<FunctionDecl>(VarDC)) { | ||||
17455 | ContextKind = 0; | ||||
17456 | } else if (isa<BlockDecl>(VarDC)) { | ||||
17457 | ContextKind = 1; | ||||
17458 | } | ||||
17459 | |||||
17460 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||
17461 | << var << ValueKind << ContextKind << VarDC; | ||||
17462 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||
17463 | << var; | ||||
17464 | |||||
17465 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||
17466 | // capture. | ||||
17467 | } | ||||
17468 | |||||
17469 | |||||
17470 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17471 | bool &SubCapturesAreNested, | ||||
17472 | QualType &CaptureType, | ||||
17473 | QualType &DeclRefType) { | ||||
17474 | // Check whether we've already captured it. | ||||
17475 | if (CSI->CaptureMap.count(Var)) { | ||||
17476 | // If we found a capture, any subcaptures are nested. | ||||
17477 | SubCapturesAreNested = true; | ||||
17478 | |||||
17479 | // Retrieve the capture type for this variable. | ||||
17480 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||
17481 | |||||
17482 | // Compute the type of an expression that refers to this variable. | ||||
17483 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17484 | |||||
17485 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||
17486 | // are mutable in the sense that user can change their value - they are | ||||
17487 | // private instances of the captured declarations. | ||||
17488 | const Capture &Cap = CSI->getCapture(Var); | ||||
17489 | if (Cap.isCopyCapture() && | ||||
17490 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||
17491 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||
17492 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||
17493 | DeclRefType.addConst(); | ||||
17494 | return true; | ||||
17495 | } | ||||
17496 | return false; | ||||
17497 | } | ||||
17498 | |||||
17499 | // Only block literals, captured statements, and lambda expressions can | ||||
17500 | // capture; other scopes don't work. | ||||
17501 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | ||||
17502 | SourceLocation Loc, | ||||
17503 | const bool Diagnose, Sema &S) { | ||||
17504 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||
17505 | return getLambdaAwareParentOfDeclContext(DC); | ||||
17506 | else if (Var->hasLocalStorage()) { | ||||
17507 | if (Diagnose) | ||||
17508 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | ||||
17509 | } | ||||
17510 | return nullptr; | ||||
17511 | } | ||||
17512 | |||||
17513 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
17514 | // certain types of variables (unnamed, variably modified types etc.) | ||||
17515 | // so check for eligibility. | ||||
17516 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17517 | SourceLocation Loc, | ||||
17518 | const bool Diagnose, Sema &S) { | ||||
17519 | |||||
17520 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||
17521 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||
17522 | |||||
17523 | // Lambdas are not allowed to capture unnamed variables | ||||
17524 | // (e.g. anonymous unions). | ||||
17525 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||
17526 | // assuming that's the intent. | ||||
17527 | if (IsLambda && !Var->getDeclName()) { | ||||
17528 | if (Diagnose) { | ||||
17529 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||
17530 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||
17531 | } | ||||
17532 | return false; | ||||
17533 | } | ||||
17534 | |||||
17535 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||
17536 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||
17537 | if (Diagnose) { | ||||
17538 | S.Diag(Loc, diag::err_ref_vm_type); | ||||
17539 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17540 | } | ||||
17541 | return false; | ||||
17542 | } | ||||
17543 | // Prohibit structs with flexible array members too. | ||||
17544 | // We cannot capture what is in the tail end of the struct. | ||||
17545 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||
17546 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
17547 | if (Diagnose) { | ||||
17548 | if (IsBlock) | ||||
17549 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||
17550 | else | ||||
17551 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||
17552 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17553 | } | ||||
17554 | return false; | ||||
17555 | } | ||||
17556 | } | ||||
17557 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17558 | // Lambdas and captured statements are not allowed to capture __block | ||||
17559 | // variables; they don't support the expected semantics. | ||||
17560 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||
17561 | if (Diagnose) { | ||||
17562 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||
17563 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17564 | } | ||||
17565 | return false; | ||||
17566 | } | ||||
17567 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||
17568 | if (S.getLangOpts().OpenCL && IsBlock && | ||||
17569 | Var->getType()->isBlockPointerType()) { | ||||
17570 | if (Diagnose) | ||||
17571 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||
17572 | return false; | ||||
17573 | } | ||||
17574 | |||||
17575 | return true; | ||||
17576 | } | ||||
17577 | |||||
17578 | // Returns true if the capture by block was successful. | ||||
17579 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | ||||
17580 | SourceLocation Loc, | ||||
17581 | const bool BuildAndDiagnose, | ||||
17582 | QualType &CaptureType, | ||||
17583 | QualType &DeclRefType, | ||||
17584 | const bool Nested, | ||||
17585 | Sema &S, bool Invalid) { | ||||
17586 | bool ByRef = false; | ||||
17587 | |||||
17588 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||
17589 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||
17590 | // (decayed to pointers). | ||||
17591 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||
17592 | if (BuildAndDiagnose) { | ||||
17593 | S.Diag(Loc, diag::err_ref_array_type); | ||||
17594 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17595 | Invalid = true; | ||||
17596 | } else { | ||||
17597 | return false; | ||||
17598 | } | ||||
17599 | } | ||||
17600 | |||||
17601 | // Forbid the block-capture of autoreleasing variables. | ||||
17602 | if (!Invalid && | ||||
17603 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17604 | if (BuildAndDiagnose) { | ||||
17605 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||
17606 | << /*block*/ 0; | ||||
17607 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17608 | Invalid = true; | ||||
17609 | } else { | ||||
17610 | return false; | ||||
17611 | } | ||||
17612 | } | ||||
17613 | |||||
17614 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||
17615 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||
17616 | QualType PointeeTy = PT->getPointeeType(); | ||||
17617 | |||||
17618 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||
17619 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||
17620 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||
17621 | if (BuildAndDiagnose) { | ||||
17622 | SourceLocation VarLoc = Var->getLocation(); | ||||
17623 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||
17624 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||
17625 | } | ||||
17626 | } | ||||
17627 | } | ||||
17628 | |||||
17629 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17630 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||
17631 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||
17632 | // Block capture by reference does not change the capture or | ||||
17633 | // declaration reference types. | ||||
17634 | ByRef = true; | ||||
17635 | } else { | ||||
17636 | // Block capture by copy introduces 'const'. | ||||
17637 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||
17638 | DeclRefType = CaptureType; | ||||
17639 | } | ||||
17640 | |||||
17641 | // Actually capture the variable. | ||||
17642 | if (BuildAndDiagnose) | ||||
17643 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||
17644 | CaptureType, Invalid); | ||||
17645 | |||||
17646 | return !Invalid; | ||||
17647 | } | ||||
17648 | |||||
17649 | |||||
17650 | /// Capture the given variable in the captured region. | ||||
17651 | static bool captureInCapturedRegion( | ||||
17652 | CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, | ||||
17653 | const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, | ||||
17654 | const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, | ||||
17655 | bool IsTopScope, Sema &S, bool Invalid) { | ||||
17656 | // By default, capture variables by reference. | ||||
17657 | bool ByRef = true; | ||||
17658 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
17659 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
17660 | } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||
17661 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||
17662 | if (S.isOpenMPCapturedDecl(Var)) { | ||||
17663 | bool HasConst = DeclRefType.isConstQualified(); | ||||
17664 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
17665 | // Don't lose diagnostics about assignments to const. | ||||
17666 | if (HasConst) | ||||
17667 | DeclRefType.addConst(); | ||||
17668 | } | ||||
17669 | // Do not capture firstprivates in tasks. | ||||
17670 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||
17671 | OMPC_unknown) | ||||
17672 | return true; | ||||
17673 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||
17674 | RSI->OpenMPCaptureLevel); | ||||
17675 | } | ||||
17676 | |||||
17677 | if (ByRef) | ||||
17678 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17679 | else | ||||
17680 | CaptureType = DeclRefType; | ||||
17681 | |||||
17682 | // Actually capture the variable. | ||||
17683 | if (BuildAndDiagnose) | ||||
17684 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||
17685 | Loc, SourceLocation(), CaptureType, Invalid); | ||||
17686 | |||||
17687 | return !Invalid; | ||||
17688 | } | ||||
17689 | |||||
17690 | /// Capture the given variable in the lambda. | ||||
17691 | static bool captureInLambda(LambdaScopeInfo *LSI, | ||||
17692 | VarDecl *Var, | ||||
17693 | SourceLocation Loc, | ||||
17694 | const bool BuildAndDiagnose, | ||||
17695 | QualType &CaptureType, | ||||
17696 | QualType &DeclRefType, | ||||
17697 | const bool RefersToCapturedVariable, | ||||
17698 | const Sema::TryCaptureKind Kind, | ||||
17699 | SourceLocation EllipsisLoc, | ||||
17700 | const bool IsTopScope, | ||||
17701 | Sema &S, bool Invalid) { | ||||
17702 | // Determine whether we are capturing by reference or by value. | ||||
17703 | bool ByRef = false; | ||||
17704 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
17705 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
17706 | } else { | ||||
17707 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||
17708 | } | ||||
17709 | |||||
17710 | // Compute the type of the field that will capture this variable. | ||||
17711 | if (ByRef) { | ||||
17712 | // C++11 [expr.prim.lambda]p15: | ||||
17713 | // An entity is captured by reference if it is implicitly or | ||||
17714 | // explicitly captured but not captured by copy. It is | ||||
17715 | // unspecified whether additional unnamed non-static data | ||||
17716 | // members are declared in the closure type for entities | ||||
17717 | // captured by reference. | ||||
17718 | // | ||||
17719 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||
17720 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||
17721 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||
17722 | // clarify, but for now we follow GCC because it's a more permissive and | ||||
17723 | // easily defensible position. | ||||
17724 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17725 | } else { | ||||
17726 | // C++11 [expr.prim.lambda]p14: | ||||
17727 | // For each entity captured by copy, an unnamed non-static | ||||
17728 | // data member is declared in the closure type. The | ||||
17729 | // declaration order of these members is unspecified. The type | ||||
17730 | // of such a data member is the type of the corresponding | ||||
17731 | // captured entity if the entity is not a reference to an | ||||
17732 | // object, or the referenced type otherwise. [Note: If the | ||||
17733 | // captured entity is a reference to a function, the | ||||
17734 | // corresponding data member is also a reference to a | ||||
17735 | // function. - end note ] | ||||
17736 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||
17737 | if (!RefType->getPointeeType()->isFunctionType()) | ||||
17738 | CaptureType = RefType->getPointeeType(); | ||||
17739 | } | ||||
17740 | |||||
17741 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||
17742 | if (!Invalid && | ||||
17743 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17744 | if (BuildAndDiagnose) { | ||||
17745 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||
17746 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||
17747 | << Var->getDeclName(); | ||||
17748 | Invalid = true; | ||||
17749 | } else { | ||||
17750 | return false; | ||||
17751 | } | ||||
17752 | } | ||||
17753 | |||||
17754 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||
17755 | if (!Invalid && BuildAndDiagnose) { | ||||
17756 | if (!CaptureType->isDependentType() && | ||||
17757 | S.RequireCompleteSizedType( | ||||
17758 | Loc, CaptureType, | ||||
17759 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||
17760 | Var->getDeclName())) | ||||
17761 | Invalid = true; | ||||
17762 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||
17763 | diag::err_capture_of_abstract_type)) | ||||
17764 | Invalid = true; | ||||
17765 | } | ||||
17766 | } | ||||
17767 | |||||
17768 | // Compute the type of a reference to this captured variable. | ||||
17769 | if (ByRef) | ||||
17770 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17771 | else { | ||||
17772 | // C++ [expr.prim.lambda]p5: | ||||
17773 | // The closure type for a lambda-expression has a public inline | ||||
17774 | // function call operator [...]. This function call operator is | ||||
17775 | // declared const (9.3.1) if and only if the lambda-expression's | ||||
17776 | // parameter-declaration-clause is not followed by mutable. | ||||
17777 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17778 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||
17779 | DeclRefType.addConst(); | ||||
17780 | } | ||||
17781 | |||||
17782 | // Add the capture. | ||||
17783 | if (BuildAndDiagnose) | ||||
17784 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||
17785 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||
17786 | |||||
17787 | return !Invalid; | ||||
17788 | } | ||||
17789 | |||||
17790 | static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { | ||||
17791 | // Offer a Copy fix even if the type is dependent. | ||||
17792 | if (Var->getType()->isDependentType()) | ||||
17793 | return true; | ||||
17794 | QualType T = Var->getType().getNonReferenceType(); | ||||
17795 | if (T.isTriviallyCopyableType(Context)) | ||||
17796 | return true; | ||||
17797 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | ||||
17798 | |||||
17799 | if (!(RD = RD->getDefinition())) | ||||
17800 | return false; | ||||
17801 | if (RD->hasSimpleCopyConstructor()) | ||||
17802 | return true; | ||||
17803 | if (RD->hasUserDeclaredCopyConstructor()) | ||||
17804 | for (CXXConstructorDecl *Ctor : RD->ctors()) | ||||
17805 | if (Ctor->isCopyConstructor()) | ||||
17806 | return !Ctor->isDeleted(); | ||||
17807 | } | ||||
17808 | return false; | ||||
17809 | } | ||||
17810 | |||||
17811 | /// Create up to 4 fix-its for explicit reference and value capture of \p Var or | ||||
17812 | /// default capture. Fixes may be omitted if they aren't allowed by the | ||||
17813 | /// standard, for example we can't emit a default copy capture fix-it if we | ||||
17814 | /// already explicitly copy capture capture another variable. | ||||
17815 | static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, | ||||
17816 | VarDecl *Var) { | ||||
17817 | assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None)(static_cast <bool> (LSI->ImpCaptureStyle == CapturingScopeInfo ::ImpCap_None) ? void (0) : __assert_fail ("LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 17817, __extension__ __PRETTY_FUNCTION__)); | ||||
17818 | // Don't offer Capture by copy of default capture by copy fixes if Var is | ||||
17819 | // known not to be copy constructible. | ||||
17820 | bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); | ||||
17821 | |||||
17822 | SmallString<32> FixBuffer; | ||||
17823 | StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; | ||||
17824 | if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { | ||||
17825 | SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); | ||||
17826 | if (ShouldOfferCopyFix) { | ||||
17827 | // Offer fixes to insert an explicit capture for the variable. | ||||
17828 | // [] -> [VarName] | ||||
17829 | // [OtherCapture] -> [OtherCapture, VarName] | ||||
17830 | FixBuffer.assign({Separator, Var->getName()}); | ||||
17831 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
17832 | << Var << /*value*/ 0 | ||||
17833 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
17834 | } | ||||
17835 | // As above but capture by reference. | ||||
17836 | FixBuffer.assign({Separator, "&", Var->getName()}); | ||||
17837 | Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) | ||||
17838 | << Var << /*reference*/ 1 | ||||
17839 | << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); | ||||
17840 | } | ||||
17841 | |||||
17842 | // Only try to offer default capture if there are no captures excluding this | ||||
17843 | // and init captures. | ||||
17844 | // [this]: OK. | ||||
17845 | // [X = Y]: OK. | ||||
17846 | // [&A, &B]: Don't offer. | ||||
17847 | // [A, B]: Don't offer. | ||||
17848 | if (llvm::any_of(LSI->Captures, [](Capture &C) { | ||||
17849 | return !C.isThisCapture() && !C.isInitCapture(); | ||||
17850 | })) | ||||
17851 | return; | ||||
17852 | |||||
17853 | // The default capture specifiers, '=' or '&', must appear first in the | ||||
17854 | // capture body. | ||||
17855 | SourceLocation DefaultInsertLoc = | ||||
17856 | LSI->IntroducerRange.getBegin().getLocWithOffset(1); | ||||
17857 | |||||
17858 | if (ShouldOfferCopyFix) { | ||||
17859 | bool CanDefaultCopyCapture = true; | ||||
17860 | // [=, *this] OK since c++17 | ||||
17861 | // [=, this] OK since c++20 | ||||
17862 | if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) | ||||
17863 | CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 | ||||
17864 | ? LSI->getCXXThisCapture().isCopyCapture() | ||||
17865 | : false; | ||||
17866 | // We can't use default capture by copy if any captures already specified | ||||
17867 | // capture by copy. | ||||
17868 | if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
17869 | return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); | ||||
17870 | })) { | ||||
17871 | FixBuffer.assign({"=", Separator}); | ||||
17872 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
17873 | << /*value*/ 0 | ||||
17874 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
17875 | } | ||||
17876 | } | ||||
17877 | |||||
17878 | // We can't use default capture by reference if any captures already specified | ||||
17879 | // capture by reference. | ||||
17880 | if (llvm::none_of(LSI->Captures, [](Capture &C) { | ||||
17881 | return !C.isInitCapture() && C.isReferenceCapture() && | ||||
17882 | !C.isThisCapture(); | ||||
17883 | })) { | ||||
17884 | FixBuffer.assign({"&", Separator}); | ||||
17885 | Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) | ||||
17886 | << /*reference*/ 1 | ||||
17887 | << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); | ||||
17888 | } | ||||
17889 | } | ||||
17890 | |||||
17891 | bool Sema::tryCaptureVariable( | ||||
17892 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||
17893 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||
17894 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||
17895 | // An init-capture is notionally from the context surrounding its | ||||
17896 | // declaration, but its parent DC is the lambda class. | ||||
17897 | DeclContext *VarDC = Var->getDeclContext(); | ||||
17898 | if (Var->isInitCapture()) | ||||
17899 | VarDC = VarDC->getParent(); | ||||
17900 | |||||
17901 | DeclContext *DC = CurContext; | ||||
17902 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||
17903 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||
17904 | // We need to sync up the Declaration Context with the | ||||
17905 | // FunctionScopeIndexToStopAt | ||||
17906 | if (FunctionScopeIndexToStopAt) { | ||||
17907 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||
17908 | while (FSIndex != MaxFunctionScopesIndex) { | ||||
17909 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||
17910 | --FSIndex; | ||||
17911 | } | ||||
17912 | } | ||||
17913 | |||||
17914 | |||||
17915 | // If the variable is declared in the current context, there is no need to | ||||
17916 | // capture it. | ||||
17917 | if (VarDC == DC) return true; | ||||
17918 | |||||
17919 | // Capture global variables if it is required to use private copy of this | ||||
17920 | // variable. | ||||
17921 | bool IsGlobal = !Var->hasLocalStorage(); | ||||
17922 | if (IsGlobal && | ||||
17923 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||
17924 | MaxFunctionScopesIndex))) | ||||
17925 | return true; | ||||
17926 | Var = Var->getCanonicalDecl(); | ||||
17927 | |||||
17928 | // Walk up the stack to determine whether we can capture the variable, | ||||
17929 | // performing the "simple" checks that don't depend on type. We stop when | ||||
17930 | // we've either hit the declared scope of the variable or find an existing | ||||
17931 | // capture of that variable. We start from the innermost capturing-entity | ||||
17932 | // (the DC) and ensure that all intervening capturing-entities | ||||
17933 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||
17934 | // declcontext can either capture the variable or have already captured | ||||
17935 | // the variable. | ||||
17936 | CaptureType = Var->getType(); | ||||
17937 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17938 | bool Nested = false; | ||||
17939 | bool Explicit = (Kind != TryCapture_Implicit); | ||||
17940 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||
17941 | do { | ||||
17942 | // Only block literals, captured statements, and lambda expressions can | ||||
17943 | // capture; other scopes don't work. | ||||
17944 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||
17945 | ExprLoc, | ||||
17946 | BuildAndDiagnose, | ||||
17947 | *this); | ||||
17948 | // We need to check for the parent *first* because, if we *have* | ||||
17949 | // private-captured a global variable, we need to recursively capture it in | ||||
17950 | // intermediate blocks, lambdas, etc. | ||||
17951 | if (!ParentDC) { | ||||
17952 | if (IsGlobal) { | ||||
17953 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||
17954 | break; | ||||
17955 | } | ||||
17956 | return true; | ||||
17957 | } | ||||
17958 | |||||
17959 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||
17960 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||
17961 | |||||
17962 | |||||
17963 | // Check whether we've already captured it. | ||||
17964 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||
17965 | DeclRefType)) { | ||||
17966 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||
17967 | break; | ||||
17968 | } | ||||
17969 | // If we are instantiating a generic lambda call operator body, | ||||
17970 | // we do not want to capture new variables. What was captured | ||||
17971 | // during either a lambdas transformation or initial parsing | ||||
17972 | // should be used. | ||||
17973 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||
17974 | if (BuildAndDiagnose) { | ||||
17975 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17976 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||
17977 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
17978 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17979 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
17980 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
17981 | } else | ||||
17982 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | ||||
17983 | } | ||||
17984 | return true; | ||||
17985 | } | ||||
17986 | |||||
17987 | // Try to capture variable-length arrays types. | ||||
17988 | if (Var->getType()->isVariablyModifiedType()) { | ||||
17989 | // We're going to walk down into the type and look for VLA | ||||
17990 | // expressions. | ||||
17991 | QualType QTy = Var->getType(); | ||||
17992 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
17993 | QTy = PVD->getOriginalType(); | ||||
17994 | captureVariablyModifiedType(Context, QTy, CSI); | ||||
17995 | } | ||||
17996 | |||||
17997 | if (getLangOpts().OpenMP) { | ||||
17998 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
17999 | // OpenMP private variables should not be captured in outer scope, so | ||||
18000 | // just break here. Similarly, global variables that are captured in a | ||||
18001 | // target region should not be captured outside the scope of the region. | ||||
18002 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||
18003 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||
18004 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||
18005 | // If the variable is private (i.e. not captured) and has variably | ||||
18006 | // modified type, we still need to capture the type for correct | ||||
18007 | // codegen in all regions, associated with the construct. Currently, | ||||
18008 | // it is captured in the innermost captured region only. | ||||
18009 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||
18010 | Var->getType()->isVariablyModifiedType()) { | ||||
18011 | QualType QTy = Var->getType(); | ||||
18012 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
18013 | QTy = PVD->getOriginalType(); | ||||
18014 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||
18015 | I < E; ++I) { | ||||
18016 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||
18017 | FunctionScopes[FunctionScopesIndex - I]); | ||||
18018 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18020, __extension__ __PRETTY_FUNCTION__)) | ||||
18019 | "Wrong number of captured regions associated with the "(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18020, __extension__ __PRETTY_FUNCTION__)) | ||||
18020 | "OpenMP construct.")(static_cast <bool> (RSI->OpenMPLevel == OuterRSI-> OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? void (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18020, __extension__ __PRETTY_FUNCTION__)); | ||||
18021 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||
18022 | } | ||||
18023 | } | ||||
18024 | bool IsTargetCap = | ||||
18025 | IsOpenMPPrivateDecl != OMPC_private && | ||||
18026 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||
18027 | RSI->OpenMPCaptureLevel); | ||||
18028 | // Do not capture global if it is not privatized in outer regions. | ||||
18029 | bool IsGlobalCap = | ||||
18030 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||
18031 | RSI->OpenMPCaptureLevel); | ||||
18032 | |||||
18033 | // When we detect target captures we are looking from inside the | ||||
18034 | // target region, therefore we need to propagate the capture from the | ||||
18035 | // enclosing region. Therefore, the capture is not initially nested. | ||||
18036 | if (IsTargetCap) | ||||
18037 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||
18038 | |||||
18039 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||
18040 | (IsGlobal && !IsGlobalCap)) { | ||||
18041 | Nested = !IsTargetCap; | ||||
18042 | bool HasConst = DeclRefType.isConstQualified(); | ||||
18043 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
18044 | // Don't lose diagnostics about assignments to const. | ||||
18045 | if (HasConst) | ||||
18046 | DeclRefType.addConst(); | ||||
18047 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||
18048 | break; | ||||
18049 | } | ||||
18050 | } | ||||
18051 | } | ||||
18052 | } | ||||
18053 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||
18054 | // No capture-default, and this is not an explicit capture | ||||
18055 | // so cannot capture this variable. | ||||
18056 | if (BuildAndDiagnose) { | ||||
18057 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
18058 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
18059 | auto *LSI = cast<LambdaScopeInfo>(CSI); | ||||
18060 | if (LSI->Lambda) { | ||||
18061 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
18062 | buildLambdaCaptureFixit(*this, LSI, Var); | ||||
18063 | } | ||||
18064 | // FIXME: If we error out because an outer lambda can not implicitly | ||||
18065 | // capture a variable that an inner lambda explicitly captures, we | ||||
18066 | // should have the inner lambda do the explicit capture - because | ||||
18067 | // it makes for cleaner diagnostics later. This would purely be done | ||||
18068 | // so that the diagnostic does not misleadingly claim that a variable | ||||
18069 | // can not be captured by a lambda implicitly even though it is captured | ||||
18070 | // explicitly. Suggestion: | ||||
18071 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||
18072 | // at the function head | ||||
18073 | // - cache the StartingDeclContext - this must be a lambda | ||||
18074 | // - captureInLambda in the innermost lambda the variable. | ||||
18075 | } | ||||
18076 | return true; | ||||
18077 | } | ||||
18078 | |||||
18079 | FunctionScopesIndex--; | ||||
18080 | DC = ParentDC; | ||||
18081 | Explicit = false; | ||||
18082 | } while (!VarDC->Equals(DC)); | ||||
18083 | |||||
18084 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||
18085 | // computing the type of the capture at each step, checking type-specific | ||||
18086 | // requirements, and adding captures if requested. | ||||
18087 | // If the variable had already been captured previously, we start capturing | ||||
18088 | // at the lambda nested within that one. | ||||
18089 | bool Invalid = false; | ||||
18090 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||
18091 | ++I) { | ||||
18092 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||
18093 | |||||
18094 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
18095 | // certain types of variables (unnamed, variably modified types etc.) | ||||
18096 | // so check for eligibility. | ||||
18097 | if (!Invalid) | ||||
18098 | Invalid = | ||||
18099 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||
18100 | |||||
18101 | // After encountering an error, if we're actually supposed to capture, keep | ||||
18102 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||
18103 | if (Invalid && !BuildAndDiagnose) | ||||
18104 | return true; | ||||
18105 | |||||
18106 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||
18107 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
18108 | DeclRefType, Nested, *this, Invalid); | ||||
18109 | Nested = true; | ||||
18110 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
18111 | Invalid = !captureInCapturedRegion( | ||||
18112 | RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, | ||||
18113 | Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
18114 | Nested = true; | ||||
18115 | } else { | ||||
18116 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
18117 | Invalid = | ||||
18118 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
18119 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||
18120 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
18121 | Nested = true; | ||||
18122 | } | ||||
18123 | |||||
18124 | if (Invalid && !BuildAndDiagnose) | ||||
18125 | return true; | ||||
18126 | } | ||||
18127 | return Invalid; | ||||
18128 | } | ||||
18129 | |||||
18130 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | ||||
18131 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||
18132 | QualType CaptureType; | ||||
18133 | QualType DeclRefType; | ||||
18134 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||
18135 | /*BuildAndDiagnose=*/true, CaptureType, | ||||
18136 | DeclRefType, nullptr); | ||||
18137 | } | ||||
18138 | |||||
18139 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | ||||
18140 | QualType CaptureType; | ||||
18141 | QualType DeclRefType; | ||||
18142 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
18143 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
18144 | DeclRefType, nullptr); | ||||
18145 | } | ||||
18146 | |||||
18147 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | ||||
18148 | QualType CaptureType; | ||||
18149 | QualType DeclRefType; | ||||
18150 | |||||
18151 | // Determine whether we can capture this variable. | ||||
18152 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
18153 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
18154 | DeclRefType, nullptr)) | ||||
18155 | return QualType(); | ||||
18156 | |||||
18157 | return DeclRefType; | ||||
18158 | } | ||||
18159 | |||||
18160 | namespace { | ||||
18161 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||
18162 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||
18163 | // object, so should only be used in contexts where the pointer will not be | ||||
18164 | // used after the CopiedTemplateArgs object is destroyed. | ||||
18165 | class CopiedTemplateArgs { | ||||
18166 | bool HasArgs; | ||||
18167 | TemplateArgumentListInfo TemplateArgStorage; | ||||
18168 | public: | ||||
18169 | template<typename RefExpr> | ||||
18170 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||
18171 | if (HasArgs) | ||||
18172 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||
18173 | } | ||||
18174 | operator TemplateArgumentListInfo*() | ||||
18175 | #ifdef __has_cpp_attribute | ||||
18176 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||
18177 | [[clang::lifetimebound]] | ||||
18178 | #endif | ||||
18179 | #endif | ||||
18180 | { | ||||
18181 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||
18182 | } | ||||
18183 | }; | ||||
18184 | } | ||||
18185 | |||||
18186 | /// Walk the set of potential results of an expression and mark them all as | ||||
18187 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||
18188 | /// | ||||
18189 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||
18190 | /// not, and ExprError() if we diagnosed an error. | ||||
18191 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||
18192 | NonOdrUseReason NOUR) { | ||||
18193 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||
18194 | // an object that satisfies the requirements for appearing in a | ||||
18195 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||
18196 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||
18197 | // conversion part. | ||||
18198 | // | ||||
18199 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||
18200 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||
18201 | // tree of nodes leading to it. | ||||
18202 | // | ||||
18203 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||
18204 | // nodes (and only certain operands of them). | ||||
18205 | |||||
18206 | // Rebuild a subexpression. | ||||
18207 | auto Rebuild = [&](Expr *Sub) { | ||||
18208 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||
18209 | }; | ||||
18210 | |||||
18211 | // Check whether a potential result satisfies the requirements of NOUR. | ||||
18212 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||
18213 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||
18214 | // in a potentially-evaluated expression. | ||||
18215 | auto *VD = dyn_cast<VarDecl>(D); | ||||
18216 | if (!VD) | ||||
18217 | return true; | ||||
18218 | |||||
18219 | // C++2a [basic.def.odr]p4: | ||||
18220 | // A variable x whose name appears as a potentially-evalauted expression | ||||
18221 | // e is odr-used by e unless | ||||
18222 | // -- x is a reference that is usable in constant expressions, or | ||||
18223 | // -- x is a variable of non-reference type that is usable in constant | ||||
18224 | // expressions and has no mutable subobjects, and e is an element of | ||||
18225 | // the set of potential results of an expression of | ||||
18226 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
18227 | // conversion is applied, or | ||||
18228 | // -- x is a variable of non-reference type, and e is an element of the | ||||
18229 | // set of potential results of a discarded-value expression to which | ||||
18230 | // the lvalue-to-rvalue conversion is not applied | ||||
18231 | // | ||||
18232 | // We check the first bullet and the "potentially-evaluated" condition in | ||||
18233 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||
18234 | // in CheckLValueToRValueConversionOperand below. | ||||
18235 | switch (NOUR) { | ||||
18236 | case NOUR_None: | ||||
18237 | case NOUR_Unevaluated: | ||||
18238 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18238); | ||||
18239 | |||||
18240 | case NOUR_Constant: | ||||
18241 | // Constant references were handled when they were built. | ||||
18242 | if (VD->getType()->isReferenceType()) | ||||
18243 | return true; | ||||
18244 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||
18245 | if (RD->hasMutableFields()) | ||||
18246 | return true; | ||||
18247 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||
18248 | return true; | ||||
18249 | break; | ||||
18250 | |||||
18251 | case NOUR_Discarded: | ||||
18252 | if (VD->getType()->isReferenceType()) | ||||
18253 | return true; | ||||
18254 | break; | ||||
18255 | } | ||||
18256 | return false; | ||||
18257 | }; | ||||
18258 | |||||
18259 | // Mark that this expression does not constitute an odr-use. | ||||
18260 | auto MarkNotOdrUsed = [&] { | ||||
18261 | S.MaybeODRUseExprs.remove(E); | ||||
18262 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||
18263 | LSI->markVariableExprAsNonODRUsed(E); | ||||
18264 | }; | ||||
18265 | |||||
18266 | // C++2a [basic.def.odr]p2: | ||||
18267 | // The set of potential results of an expression e is defined as follows: | ||||
18268 | switch (E->getStmtClass()) { | ||||
18269 | // -- If e is an id-expression, ... | ||||
18270 | case Expr::DeclRefExprClass: { | ||||
18271 | auto *DRE = cast<DeclRefExpr>(E); | ||||
18272 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||
18273 | break; | ||||
18274 | |||||
18275 | // Rebuild as a non-odr-use DeclRefExpr. | ||||
18276 | MarkNotOdrUsed(); | ||||
18277 | return DeclRefExpr::Create( | ||||
18278 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||
18279 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||
18280 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||
18281 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||
18282 | } | ||||
18283 | |||||
18284 | case Expr::FunctionParmPackExprClass: { | ||||
18285 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||
18286 | // If any of the declarations in the pack is odr-used, then the expression | ||||
18287 | // as a whole constitutes an odr-use. | ||||
18288 | for (VarDecl *D : *FPPE) | ||||
18289 | if (IsPotentialResultOdrUsed(D)) | ||||
18290 | return ExprEmpty(); | ||||
18291 | |||||
18292 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||
18293 | // nothing cares about whether we marked this as an odr-use, but it might | ||||
18294 | // be useful for non-compiler tools. | ||||
18295 | MarkNotOdrUsed(); | ||||
18296 | break; | ||||
18297 | } | ||||
18298 | |||||
18299 | // -- If e is a subscripting operation with an array operand... | ||||
18300 | case Expr::ArraySubscriptExprClass: { | ||||
18301 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||
18302 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||
18303 | if (!OldBase->getType()->isArrayType()) | ||||
18304 | break; | ||||
18305 | ExprResult Base = Rebuild(OldBase); | ||||
18306 | if (!Base.isUsable()) | ||||
18307 | return Base; | ||||
18308 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||
18309 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||
18310 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||
18311 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||
18312 | ASE->getRBracketLoc()); | ||||
18313 | } | ||||
18314 | |||||
18315 | case Expr::MemberExprClass: { | ||||
18316 | auto *ME = cast<MemberExpr>(E); | ||||
18317 | // -- If e is a class member access expression [...] naming a non-static | ||||
18318 | // data member... | ||||
18319 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||
18320 | ExprResult Base = Rebuild(ME->getBase()); | ||||
18321 | if (!Base.isUsable()) | ||||
18322 | return Base; | ||||
18323 | return MemberExpr::Create( | ||||
18324 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||
18325 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||
18326 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||
18327 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||
18328 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||
18329 | } | ||||
18330 | |||||
18331 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||
18332 | break; | ||||
18333 | |||||
18334 | // -- If e is a class member access expression naming a static data member, | ||||
18335 | // ... | ||||
18336 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||
18337 | break; | ||||
18338 | |||||
18339 | // Rebuild as a non-odr-use MemberExpr. | ||||
18340 | MarkNotOdrUsed(); | ||||
18341 | return MemberExpr::Create( | ||||
18342 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||
18343 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||
18344 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||
18345 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||
18346 | } | ||||
18347 | |||||
18348 | case Expr::BinaryOperatorClass: { | ||||
18349 | auto *BO = cast<BinaryOperator>(E); | ||||
18350 | Expr *LHS = BO->getLHS(); | ||||
18351 | Expr *RHS = BO->getRHS(); | ||||
18352 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||
18353 | if (BO->getOpcode() == BO_PtrMemD) { | ||||
18354 | ExprResult Sub = Rebuild(LHS); | ||||
18355 | if (!Sub.isUsable()) | ||||
18356 | return Sub; | ||||
18357 | LHS = Sub.get(); | ||||
18358 | // -- If e is a comma expression, ... | ||||
18359 | } else if (BO->getOpcode() == BO_Comma) { | ||||
18360 | ExprResult Sub = Rebuild(RHS); | ||||
18361 | if (!Sub.isUsable()) | ||||
18362 | return Sub; | ||||
18363 | RHS = Sub.get(); | ||||
18364 | } else { | ||||
18365 | break; | ||||
18366 | } | ||||
18367 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||
18368 | LHS, RHS); | ||||
18369 | } | ||||
18370 | |||||
18371 | // -- If e has the form (e1)... | ||||
18372 | case Expr::ParenExprClass: { | ||||
18373 | auto *PE = cast<ParenExpr>(E); | ||||
18374 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||
18375 | if (!Sub.isUsable()) | ||||
18376 | return Sub; | ||||
18377 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||
18378 | } | ||||
18379 | |||||
18380 | // -- If e is a glvalue conditional expression, ... | ||||
18381 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||
18382 | case Expr::ConditionalOperatorClass: { | ||||
18383 | auto *CO = cast<ConditionalOperator>(E); | ||||
18384 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||
18385 | if (LHS.isInvalid()) | ||||
18386 | return ExprError(); | ||||
18387 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||
18388 | if (RHS.isInvalid()) | ||||
18389 | return ExprError(); | ||||
18390 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||
18391 | return ExprEmpty(); | ||||
18392 | if (!LHS.isUsable()) | ||||
18393 | LHS = CO->getLHS(); | ||||
18394 | if (!RHS.isUsable()) | ||||
18395 | RHS = CO->getRHS(); | ||||
18396 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||
18397 | CO->getCond(), LHS.get(), RHS.get()); | ||||
18398 | } | ||||
18399 | |||||
18400 | // [Clang extension] | ||||
18401 | // -- If e has the form __extension__ e1... | ||||
18402 | case Expr::UnaryOperatorClass: { | ||||
18403 | auto *UO = cast<UnaryOperator>(E); | ||||
18404 | if (UO->getOpcode() != UO_Extension) | ||||
18405 | break; | ||||
18406 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||
18407 | if (!Sub.isUsable()) | ||||
18408 | return Sub; | ||||
18409 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||
18410 | Sub.get()); | ||||
18411 | } | ||||
18412 | |||||
18413 | // [Clang extension] | ||||
18414 | // -- If e has the form _Generic(...), the set of potential results is the | ||||
18415 | // union of the sets of potential results of the associated expressions. | ||||
18416 | case Expr::GenericSelectionExprClass: { | ||||
18417 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||
18418 | |||||
18419 | SmallVector<Expr *, 4> AssocExprs; | ||||
18420 | bool AnyChanged = false; | ||||
18421 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||
18422 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||
18423 | if (AssocExpr.isInvalid()) | ||||
18424 | return ExprError(); | ||||
18425 | if (AssocExpr.isUsable()) { | ||||
18426 | AssocExprs.push_back(AssocExpr.get()); | ||||
18427 | AnyChanged = true; | ||||
18428 | } else { | ||||
18429 | AssocExprs.push_back(OrigAssocExpr); | ||||
18430 | } | ||||
18431 | } | ||||
18432 | |||||
18433 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||
18434 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||
18435 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||
18436 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||
18437 | : ExprEmpty(); | ||||
18438 | } | ||||
18439 | |||||
18440 | // [Clang extension] | ||||
18441 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||
18442 | // results is the union of the sets of potential results of the | ||||
18443 | // second and third subexpressions. | ||||
18444 | case Expr::ChooseExprClass: { | ||||
18445 | auto *CE = cast<ChooseExpr>(E); | ||||
18446 | |||||
18447 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||
18448 | if (LHS.isInvalid()) | ||||
18449 | return ExprError(); | ||||
18450 | |||||
18451 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||
18452 | if (RHS.isInvalid()) | ||||
18453 | return ExprError(); | ||||
18454 | |||||
18455 | if (!LHS.get() && !RHS.get()) | ||||
18456 | return ExprEmpty(); | ||||
18457 | if (!LHS.isUsable()) | ||||
18458 | LHS = CE->getLHS(); | ||||
18459 | if (!RHS.isUsable()) | ||||
18460 | RHS = CE->getRHS(); | ||||
18461 | |||||
18462 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||
18463 | RHS.get(), CE->getRParenLoc()); | ||||
18464 | } | ||||
18465 | |||||
18466 | // Step through non-syntactic nodes. | ||||
18467 | case Expr::ConstantExprClass: { | ||||
18468 | auto *CE = cast<ConstantExpr>(E); | ||||
18469 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||
18470 | if (!Sub.isUsable()) | ||||
18471 | return Sub; | ||||
18472 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||
18473 | } | ||||
18474 | |||||
18475 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||
18476 | // casts, but not at the top level, so rebuild them here. | ||||
18477 | case Expr::ImplicitCastExprClass: { | ||||
18478 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||
18479 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||
18480 | // Anything else suggests we've left the region in which potential results | ||||
18481 | // can be found. | ||||
18482 | switch (ICE->getCastKind()) { | ||||
18483 | case CK_NoOp: | ||||
18484 | case CK_DerivedToBase: | ||||
18485 | case CK_UncheckedDerivedToBase: { | ||||
18486 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||
18487 | if (!Sub.isUsable()) | ||||
18488 | return Sub; | ||||
18489 | CXXCastPath Path(ICE->path()); | ||||
18490 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||
18491 | ICE->getValueKind(), &Path); | ||||
18492 | } | ||||
18493 | |||||
18494 | default: | ||||
18495 | break; | ||||
18496 | } | ||||
18497 | break; | ||||
18498 | } | ||||
18499 | |||||
18500 | default: | ||||
18501 | break; | ||||
18502 | } | ||||
18503 | |||||
18504 | // Can't traverse through this node. Nothing to do. | ||||
18505 | return ExprEmpty(); | ||||
18506 | } | ||||
18507 | |||||
18508 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||
18509 | // Check whether the operand is or contains an object of non-trivial C union | ||||
18510 | // type. | ||||
18511 | if (E->getType().isVolatileQualified() && | ||||
18512 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
18513 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||
18514 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
18515 | Sema::NTCUC_LValueToRValueVolatile, | ||||
18516 | NTCUK_Destruct|NTCUK_Copy); | ||||
18517 | |||||
18518 | // C++2a [basic.def.odr]p4: | ||||
18519 | // [...] an expression of non-volatile-qualified non-class type to which | ||||
18520 | // the lvalue-to-rvalue conversion is applied [...] | ||||
18521 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||
18522 | return E; | ||||
18523 | |||||
18524 | ExprResult Result = | ||||
18525 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||
18526 | if (Result.isInvalid()) | ||||
18527 | return ExprError(); | ||||
18528 | return Result.get() ? Result : E; | ||||
18529 | } | ||||
18530 | |||||
18531 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||
18532 | Res = CorrectDelayedTyposInExpr(Res); | ||||
18533 | |||||
18534 | if (!Res.isUsable()) | ||||
18535 | return Res; | ||||
18536 | |||||
18537 | // If a constant-expression is a reference to a variable where we delay | ||||
18538 | // deciding whether it is an odr-use, just assume we will apply the | ||||
18539 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||
18540 | // (a non-type template argument), we have special handling anyway. | ||||
18541 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||
18542 | } | ||||
18543 | |||||
18544 | void Sema::CleanupVarDeclMarking() { | ||||
18545 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||
18546 | // call. | ||||
18547 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||
18548 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||
18549 | |||||
18550 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||
18551 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
18552 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||
18553 | DRE->getLocation(), *this); | ||||
18554 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
18555 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||
18556 | *this); | ||||
18557 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||
18558 | for (VarDecl *VD : *FP) | ||||
18559 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||
18560 | } else { | ||||
18561 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18561); | ||||
18562 | } | ||||
18563 | } | ||||
18564 | |||||
18565 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18566, __extension__ __PRETTY_FUNCTION__)) | ||||
18566 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")(static_cast <bool> (MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18566, __extension__ __PRETTY_FUNCTION__)); | ||||
18567 | } | ||||
18568 | |||||
18569 | static void DoMarkVarDeclReferenced( | ||||
18570 | Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, | ||||
18571 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
18572 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18574, __extension__ __PRETTY_FUNCTION__)) | ||||
18573 | isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18574, __extension__ __PRETTY_FUNCTION__)) | ||||
18574 | "Invalid Expr argument to DoMarkVarDeclReferenced")(static_cast <bool> ((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>( E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? void (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18574, __extension__ __PRETTY_FUNCTION__)); | ||||
18575 | Var->setReferenced(); | ||||
18576 | |||||
18577 | if (Var->isInvalidDecl()) | ||||
18578 | return; | ||||
18579 | |||||
18580 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||
18581 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||
18582 | : Var->getTemplateSpecializationKind(); | ||||
18583 | |||||
18584 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
18585 | bool UsableInConstantExpr = | ||||
18586 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||
18587 | |||||
18588 | if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { | ||||
18589 | RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; | ||||
18590 | } | ||||
18591 | |||||
18592 | // C++20 [expr.const]p12: | ||||
18593 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||
18594 | // variable whose name appears as a potentially constant evaluated | ||||
18595 | // expression that is either a contexpr variable or is of non-volatile | ||||
18596 | // const-qualified integral type or of reference type | ||||
18597 | bool NeededForConstantEvaluation = | ||||
18598 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||
18599 | |||||
18600 | bool NeedDefinition = | ||||
18601 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||
18602 | |||||
18603 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18604, __extension__ __PRETTY_FUNCTION__)) | ||||
18604 | "Can't instantiate a partial template specialization.")(static_cast <bool> (!isa<VarTemplatePartialSpecializationDecl >(Var) && "Can't instantiate a partial template specialization." ) ? void (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18604, __extension__ __PRETTY_FUNCTION__)); | ||||
18605 | |||||
18606 | // If this might be a member specialization of a static data member, check | ||||
18607 | // the specialization is visible. We already did the checks for variable | ||||
18608 | // template specializations when we created them. | ||||
18609 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||
18610 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||
18611 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||
18612 | |||||
18613 | // Perform implicit instantiation of static data members, static data member | ||||
18614 | // templates of class templates, and variable template specializations. Delay | ||||
18615 | // instantiations of variable templates, except for those that could be used | ||||
18616 | // in a constant expression. | ||||
18617 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||
18618 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||
18619 | // instantiation declaration if a variable is usable in a constant | ||||
18620 | // expression (among other cases). | ||||
18621 | bool TryInstantiating = | ||||
18622 | TSK == TSK_ImplicitInstantiation || | ||||
18623 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||
18624 | |||||
18625 | if (TryInstantiating) { | ||||
18626 | SourceLocation PointOfInstantiation = | ||||
18627 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||
18628 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
18629 | if (FirstInstantiation) { | ||||
18630 | PointOfInstantiation = Loc; | ||||
18631 | if (MSI) | ||||
18632 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||
18633 | // FIXME: Notify listener. | ||||
18634 | else | ||||
18635 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
18636 | } | ||||
18637 | |||||
18638 | if (UsableInConstantExpr) { | ||||
18639 | // Do not defer instantiations of variables that could be used in a | ||||
18640 | // constant expression. | ||||
18641 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
18642 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
18643 | }); | ||||
18644 | |||||
18645 | // Re-set the member to trigger a recomputation of the dependence bits | ||||
18646 | // for the expression. | ||||
18647 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18648 | DRE->setDecl(DRE->getDecl()); | ||||
18649 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18650 | ME->setMemberDecl(ME->getMemberDecl()); | ||||
18651 | } else if (FirstInstantiation || | ||||
18652 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||
18653 | // FIXME: For a specialization of a variable template, we don't | ||||
18654 | // distinguish between "declaration and type implicitly instantiated" | ||||
18655 | // and "implicit instantiation of definition requested", so we have | ||||
18656 | // no direct way to avoid enqueueing the pending instantiation | ||||
18657 | // multiple times. | ||||
18658 | SemaRef.PendingInstantiations | ||||
18659 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||
18660 | } | ||||
18661 | } | ||||
18662 | } | ||||
18663 | |||||
18664 | // C++2a [basic.def.odr]p4: | ||||
18665 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
18666 | // is odr-used by e unless | ||||
18667 | // -- x is a reference that is usable in constant expressions | ||||
18668 | // -- x is a variable of non-reference type that is usable in constant | ||||
18669 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||
18670 | // element of the set of potential results of an expression of | ||||
18671 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
18672 | // conversion is applied | ||||
18673 | // -- x is a variable of non-reference type, and e is an element of the set | ||||
18674 | // of potential results of a discarded-value expression to which the | ||||
18675 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||
18676 | // | ||||
18677 | // We check the first part of the second bullet here, and | ||||
18678 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||
18679 | // FIXME: To get the third bullet right, we need to delay this even for | ||||
18680 | // variables that are not usable in constant expressions. | ||||
18681 | |||||
18682 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||
18683 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18684 | if (DRE->isNonOdrUse()) | ||||
18685 | return; | ||||
18686 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18687 | if (ME->isNonOdrUse()) | ||||
18688 | return; | ||||
18689 | |||||
18690 | switch (OdrUse) { | ||||
18691 | case OdrUseContext::None: | ||||
18692 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18693, __extension__ __PRETTY_FUNCTION__)) | ||||
18693 | "missing non-odr-use marking for unevaluated decl ref")(static_cast <bool> ((!E || isa<FunctionParmPackExpr >(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? void (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18693, __extension__ __PRETTY_FUNCTION__)); | ||||
18694 | break; | ||||
18695 | |||||
18696 | case OdrUseContext::FormallyOdrUsed: | ||||
18697 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||
18698 | // behavior. | ||||
18699 | break; | ||||
18700 | |||||
18701 | case OdrUseContext::Used: | ||||
18702 | // If we might later find that this expression isn't actually an odr-use, | ||||
18703 | // delay the marking. | ||||
18704 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18705 | SemaRef.MaybeODRUseExprs.insert(E); | ||||
18706 | else | ||||
18707 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||
18708 | break; | ||||
18709 | |||||
18710 | case OdrUseContext::Dependent: | ||||
18711 | // If this is a dependent context, we don't need to mark variables as | ||||
18712 | // odr-used, but we may still need to track them for lambda capture. | ||||
18713 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||
18714 | // (which are modeled as unevaluated at this point)? | ||||
18715 | const bool RefersToEnclosingScope = | ||||
18716 | (SemaRef.CurContext != Var->getDeclContext() && | ||||
18717 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | ||||
18718 | if (RefersToEnclosingScope) { | ||||
18719 | LambdaScopeInfo *const LSI = | ||||
18720 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||
18721 | if (LSI && (!LSI->CallOperator || | ||||
18722 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||
18723 | // If a variable could potentially be odr-used, defer marking it so | ||||
18724 | // until we finish analyzing the full expression for any | ||||
18725 | // lvalue-to-rvalue | ||||
18726 | // or discarded value conversions that would obviate odr-use. | ||||
18727 | // Add it to the list of potential captures that will be analyzed | ||||
18728 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||
18729 | // unless the variable is a reference that was initialized by a constant | ||||
18730 | // expression (this will never need to be captured or odr-used). | ||||
18731 | // | ||||
18732 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||
18733 | assert(E && "Capture variable should be used in an expression.")(static_cast <bool> (E && "Capture variable should be used in an expression." ) ? void (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 18733, __extension__ __PRETTY_FUNCTION__)); | ||||
18734 | if (!Var->getType()->isReferenceType() || | ||||
18735 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18736 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||
18737 | } | ||||
18738 | } | ||||
18739 | break; | ||||
18740 | } | ||||
18741 | } | ||||
18742 | |||||
18743 | /// Mark a variable referenced, and check whether it is odr-used | ||||
18744 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||
18745 | /// used directly for normal expressions referring to VarDecl. | ||||
18746 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||
18747 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); | ||||
18748 | } | ||||
18749 | |||||
18750 | static void | ||||
18751 | MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, | ||||
18752 | bool MightBeOdrUse, | ||||
18753 | llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | ||||
18754 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||
18755 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||
18756 | |||||
18757 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||
18758 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); | ||||
18759 | return; | ||||
18760 | } | ||||
18761 | |||||
18762 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||
18763 | |||||
18764 | // If this is a call to a method via a cast, also mark the method in the | ||||
18765 | // derived class used in case codegen can devirtualize the call. | ||||
18766 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
18767 | if (!ME) | ||||
18768 | return; | ||||
18769 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
18770 | if (!MD) | ||||
18771 | return; | ||||
18772 | // Only attempt to devirtualize if this is truly a virtual call. | ||||
18773 | bool IsVirtualCall = MD->isVirtual() && | ||||
18774 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||
18775 | if (!IsVirtualCall) | ||||
18776 | return; | ||||
18777 | |||||
18778 | // If it's possible to devirtualize the call, mark the called function | ||||
18779 | // referenced. | ||||
18780 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||
18781 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||
18782 | if (DM) | ||||
18783 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||
18784 | } | ||||
18785 | |||||
18786 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||
18787 | /// | ||||
18788 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | ||||
18789 | /// handled with care if the DeclRefExpr is not newly-created. | ||||
18790 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||
18791 | // TODO: update this with DR# once a defect report is filed. | ||||
18792 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||
18793 | // if it's a qualified reference. | ||||
18794 | bool OdrUse = true; | ||||
18795 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||
18796 | if (Method->isVirtual() && | ||||
18797 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||
18798 | OdrUse = false; | ||||
18799 | |||||
18800 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
18801 | if (!isUnevaluatedContext() && !isConstantEvaluated() && | ||||
18802 | FD->isConsteval() && !RebuildingImmediateInvocation) | ||||
18803 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||
18804 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, | ||||
18805 | RefsMinusAssignments); | ||||
18806 | } | ||||
18807 | |||||
18808 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||
18809 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||
18810 | // C++11 [basic.def.odr]p2: | ||||
18811 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||
18812 | // expression or a member of a set of candidate functions, if selected by | ||||
18813 | // overload resolution when referred to from a potentially-evaluated | ||||
18814 | // expression, is odr-used, unless it is a pure virtual function and its | ||||
18815 | // name is not explicitly qualified. | ||||
18816 | bool MightBeOdrUse = true; | ||||
18817 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||
18818 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||
18819 | if (Method->isPure()) | ||||
18820 | MightBeOdrUse = false; | ||||
18821 | } | ||||
18822 | SourceLocation Loc = | ||||
18823 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||
18824 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, | ||||
18825 | RefsMinusAssignments); | ||||
18826 | } | ||||
18827 | |||||
18828 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||
18829 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||
18830 | for (VarDecl *VD : *E) | ||||
18831 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, | ||||
18832 | RefsMinusAssignments); | ||||
18833 | } | ||||
18834 | |||||
18835 | /// Perform marking for a reference to an arbitrary declaration. It | ||||
18836 | /// marks the declaration referenced, and performs odr-use checking for | ||||
18837 | /// functions and variables. This method should not be used when building a | ||||
18838 | /// normal expression which refers to a variable. | ||||
18839 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||
18840 | bool MightBeOdrUse) { | ||||
18841 | if (MightBeOdrUse) { | ||||
18842 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
18843 | MarkVariableReferenced(Loc, VD); | ||||
18844 | return; | ||||
18845 | } | ||||
18846 | } | ||||
18847 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
18848 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||
18849 | return; | ||||
18850 | } | ||||
18851 | D->setReferenced(); | ||||
18852 | } | ||||
18853 | |||||
18854 | namespace { | ||||
18855 | // Mark all of the declarations used by a type as referenced. | ||||
18856 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||
18857 | // of when we're entering a context we should not recurse into. | ||||
18858 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||
18859 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||
18860 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||
18861 | // Currently that causes problems when rebuilding LambdaExprs. | ||||
18862 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||
18863 | Sema &S; | ||||
18864 | SourceLocation Loc; | ||||
18865 | |||||
18866 | public: | ||||
18867 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||
18868 | |||||
18869 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||
18870 | |||||
18871 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||
18872 | }; | ||||
18873 | } | ||||
18874 | |||||
18875 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||
18876 | const TemplateArgument &Arg) { | ||||
18877 | { | ||||
18878 | // A non-type template argument is a constant-evaluated context. | ||||
18879 | EnterExpressionEvaluationContext Evaluated( | ||||
18880 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
18881 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||
18882 | if (Decl *D = Arg.getAsDecl()) | ||||
18883 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||
18884 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||
18885 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||
18886 | } | ||||
18887 | } | ||||
18888 | |||||
18889 | return Inherited::TraverseTemplateArgument(Arg); | ||||
18890 | } | ||||
18891 | |||||
18892 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||
18893 | MarkReferencedDecls Marker(*this, Loc); | ||||
18894 | Marker.TraverseType(T); | ||||
18895 | } | ||||
18896 | |||||
18897 | namespace { | ||||
18898 | /// Helper class that marks all of the declarations referenced by | ||||
18899 | /// potentially-evaluated subexpressions as "referenced". | ||||
18900 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||
18901 | public: | ||||
18902 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||
18903 | bool SkipLocalVariables; | ||||
18904 | |||||
18905 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | ||||
18906 | : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} | ||||
18907 | |||||
18908 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||
18909 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||
18910 | } | ||||
18911 | |||||
18912 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18913 | // If we were asked not to visit local variables, don't. | ||||
18914 | if (SkipLocalVariables) { | ||||
18915 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
18916 | if (VD->hasLocalStorage()) | ||||
18917 | return; | ||||
18918 | } | ||||
18919 | |||||
18920 | // FIXME: This can trigger the instantiation of the initializer of a | ||||
18921 | // variable, which can cause the expression to become value-dependent | ||||
18922 | // or error-dependent. Do we need to propagate the new dependence bits? | ||||
18923 | S.MarkDeclRefReferenced(E); | ||||
18924 | } | ||||
18925 | |||||
18926 | void VisitMemberExpr(MemberExpr *E) { | ||||
18927 | S.MarkMemberReferenced(E); | ||||
18928 | Visit(E->getBase()); | ||||
18929 | } | ||||
18930 | }; | ||||
18931 | } // namespace | ||||
18932 | |||||
18933 | /// Mark any declarations that appear within this expression or any | ||||
18934 | /// potentially-evaluated subexpressions as "referenced". | ||||
18935 | /// | ||||
18936 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||
18937 | /// 'referenced'. | ||||
18938 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||
18939 | bool SkipLocalVariables) { | ||||
18940 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | ||||
18941 | } | ||||
18942 | |||||
18943 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||
18944 | /// of the program being compiled. | ||||
18945 | /// | ||||
18946 | /// This routine emits the given diagnostic when the code currently being | ||||
18947 | /// type-checked is "potentially evaluated", meaning that there is a | ||||
18948 | /// possibility that the code will actually be executable. Code in sizeof() | ||||
18949 | /// expressions, code used only during overload resolution, etc., are not | ||||
18950 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||
18951 | /// in the absolutely nutty case of potentially potentially evaluated | ||||
18952 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||
18953 | /// later. | ||||
18954 | /// | ||||
18955 | /// This routine should be used for all diagnostics that describe the run-time | ||||
18956 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||
18957 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||
18958 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||
18959 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||
18960 | const PartialDiagnostic &PD) { | ||||
18961 | switch (ExprEvalContexts.back().Context) { | ||||
18962 | case ExpressionEvaluationContext::Unevaluated: | ||||
18963 | case ExpressionEvaluationContext::UnevaluatedList: | ||||
18964 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
18965 | case ExpressionEvaluationContext::DiscardedStatement: | ||||
18966 | // The argument will never be evaluated, so don't complain. | ||||
18967 | break; | ||||
18968 | |||||
18969 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||
18970 | // Relevant diagnostics should be produced by constant evaluation. | ||||
18971 | break; | ||||
18972 | |||||
18973 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
18974 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
18975 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||
18976 | FunctionScopes.back()->PossiblyUnreachableDiags. | ||||
18977 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||
18978 | return true; | ||||
18979 | } | ||||
18980 | |||||
18981 | // The initializer of a constexpr variable or of the first declaration of a | ||||
18982 | // static data member is not syntactically a constant evaluated constant, | ||||
18983 | // but nonetheless is always required to be a constant expression, so we | ||||
18984 | // can skip diagnosing. | ||||
18985 | // FIXME: Using the mangling context here is a hack. | ||||
18986 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||
18987 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||
18988 | if (VD->isConstexpr() || | ||||
18989 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||
18990 | break; | ||||
18991 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||
18992 | // initializer and check whether the context in question is reachable. | ||||
18993 | } | ||||
18994 | |||||
18995 | Diag(Loc, PD); | ||||
18996 | return true; | ||||
18997 | } | ||||
18998 | |||||
18999 | return false; | ||||
19000 | } | ||||
19001 | |||||
19002 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||
19003 | const PartialDiagnostic &PD) { | ||||
19004 | return DiagRuntimeBehavior( | ||||
19005 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | ||||
19006 | } | ||||
19007 | |||||
19008 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||
19009 | CallExpr *CE, FunctionDecl *FD) { | ||||
19010 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||
19011 | return false; | ||||
19012 | |||||
19013 | // If we're inside a decltype's expression, don't check for a valid return | ||||
19014 | // type or construct temporaries until we know whether this is the last call. | ||||
19015 | if (ExprEvalContexts.back().ExprContext == | ||||
19016 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||
19017 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||
19018 | return false; | ||||
19019 | } | ||||
19020 | |||||
19021 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||
19022 | FunctionDecl *FD; | ||||
19023 | CallExpr *CE; | ||||
19024 | |||||
19025 | public: | ||||
19026 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||
19027 | : FD(FD), CE(CE) { } | ||||
19028 | |||||
19029 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
19030 | if (!FD) { | ||||
19031 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||
19032 | << T << CE->getSourceRange(); | ||||
19033 | return; | ||||
19034 | } | ||||
19035 | |||||
19036 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||
19037 | << CE->getSourceRange() << FD << T; | ||||
19038 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||
19039 | << FD->getDeclName(); | ||||
19040 | } | ||||
19041 | } Diagnoser(FD, CE); | ||||
19042 | |||||
19043 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||
19044 | return true; | ||||
19045 | |||||
19046 | return false; | ||||
19047 | } | ||||
19048 | |||||
19049 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||
19050 | // will prevent this condition from triggering, which is what we want. | ||||
19051 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||
19052 | SourceLocation Loc; | ||||
19053 | |||||
19054 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||
19055 | bool IsOrAssign = false; | ||||
19056 | |||||
19057 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||
19058 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||
19059 | return; | ||||
19060 | |||||
19061 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||
19062 | |||||
19063 | // Greylist some idioms by putting them into a warning subcategory. | ||||
19064 | if (ObjCMessageExpr *ME | ||||
19065 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||
19066 | Selector Sel = ME->getSelector(); | ||||
19067 | |||||
19068 | // self = [<foo> init...] | ||||
19069 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||
19070 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
19071 | |||||
19072 | // <foo> = [<bar> nextObject] | ||||
19073 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||
19074 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
19075 | } | ||||
19076 | |||||
19077 | Loc = Op->getOperatorLoc(); | ||||
19078 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
19079 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||
19080 | return; | ||||
19081 | |||||
19082 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||
19083 | Loc = Op->getOperatorLoc(); | ||||
19084 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||
19085 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||
19086 | else { | ||||
19087 | // Not an assignment. | ||||
19088 | return; | ||||
19089 | } | ||||
19090 | |||||
19091 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||
19092 | |||||
19093 | SourceLocation Open = E->getBeginLoc(); | ||||
19094 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||
19095 | Diag(Loc, diag::note_condition_assign_silence) | ||||
19096 | << FixItHint::CreateInsertion(Open, "(") | ||||
19097 | << FixItHint::CreateInsertion(Close, ")"); | ||||
19098 | |||||
19099 | if (IsOrAssign) | ||||
19100 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||
19101 | << FixItHint::CreateReplacement(Loc, "!="); | ||||
19102 | else | ||||
19103 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||
19104 | << FixItHint::CreateReplacement(Loc, "=="); | ||||
19105 | } | ||||
19106 | |||||
19107 | /// Redundant parentheses over an equality comparison can indicate | ||||
19108 | /// that the user intended an assignment used as condition. | ||||
19109 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||
19110 | // Don't warn if the parens came from a macro. | ||||
19111 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||
19112 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||
19113 | return; | ||||
19114 | // Don't warn for dependent expressions. | ||||
19115 | if (ParenE->isTypeDependent()) | ||||
19116 | return; | ||||
19117 | |||||
19118 | Expr *E = ParenE->IgnoreParens(); | ||||
19119 | |||||
19120 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||
19121 | if (opE->getOpcode() == BO_EQ && | ||||
19122 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||
19123 | == Expr::MLV_Valid) { | ||||
19124 | SourceLocation Loc = opE->getOperatorLoc(); | ||||
19125 | |||||
19126 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||
19127 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||
19128 | Diag(Loc, diag::note_equality_comparison_silence) | ||||
19129 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||
19130 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||
19131 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||
19132 | << FixItHint::CreateReplacement(Loc, "="); | ||||
19133 | } | ||||
19134 | } | ||||
19135 | |||||
19136 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||
19137 | bool IsConstexpr) { | ||||
19138 | DiagnoseAssignmentAsCondition(E); | ||||
19139 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||
19140 | DiagnoseEqualityWithExtraParens(parenE); | ||||
19141 | |||||
19142 | ExprResult result = CheckPlaceholderExpr(E); | ||||
19143 | if (result.isInvalid()) return ExprError(); | ||||
19144 | E = result.get(); | ||||
19145 | |||||
19146 | if (!E->isTypeDependent()) { | ||||
19147 | if (getLangOpts().CPlusPlus) | ||||
19148 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||
19149 | |||||
19150 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||
19151 | if (ERes.isInvalid()) | ||||
19152 | return ExprError(); | ||||
19153 | E = ERes.get(); | ||||
19154 | |||||
19155 | QualType T = E->getType(); | ||||
19156 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||
19157 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||
19158 | << T << E->getSourceRange(); | ||||
19159 | return ExprError(); | ||||
19160 | } | ||||
19161 | CheckBoolLikeConversion(E, Loc); | ||||
19162 | } | ||||
19163 | |||||
19164 | return E; | ||||
19165 | } | ||||
19166 | |||||
19167 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||
19168 | Expr *SubExpr, ConditionKind CK) { | ||||
19169 | // Empty conditions are valid in for-statements. | ||||
19170 | if (!SubExpr) | ||||
19171 | return ConditionResult(); | ||||
19172 | |||||
19173 | ExprResult Cond; | ||||
19174 | switch (CK) { | ||||
19175 | case ConditionKind::Boolean: | ||||
19176 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||
19177 | break; | ||||
19178 | |||||
19179 | case ConditionKind::ConstexprIf: | ||||
19180 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||
19181 | break; | ||||
19182 | |||||
19183 | case ConditionKind::Switch: | ||||
19184 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||
19185 | break; | ||||
19186 | } | ||||
19187 | if (Cond.isInvalid()) { | ||||
19188 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||
19189 | {SubExpr}); | ||||
19190 | if (!Cond.get()) | ||||
19191 | return ConditionError(); | ||||
19192 | } | ||||
19193 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||
19194 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||
19195 | if (!FullExpr.get()) | ||||
19196 | return ConditionError(); | ||||
19197 | |||||
19198 | return ConditionResult(*this, nullptr, FullExpr, | ||||
19199 | CK == ConditionKind::ConstexprIf); | ||||
19200 | } | ||||
19201 | |||||
19202 | namespace { | ||||
19203 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||
19204 | /// to have an appropriate type. | ||||
19205 | struct RebuildUnknownAnyFunction | ||||
19206 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||
19207 | |||||
19208 | Sema &S; | ||||
19209 | |||||
19210 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||
19211 | |||||
19212 | ExprResult VisitStmt(Stmt *S) { | ||||
19213 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19213); | ||||
19214 | } | ||||
19215 | |||||
19216 | ExprResult VisitExpr(Expr *E) { | ||||
19217 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||
19218 | << E->getSourceRange(); | ||||
19219 | return ExprError(); | ||||
19220 | } | ||||
19221 | |||||
19222 | /// Rebuild an expression which simply semantically wraps another | ||||
19223 | /// expression which it shares the type and value kind of. | ||||
19224 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
19225 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19226 | if (SubResult.isInvalid()) return ExprError(); | ||||
19227 | |||||
19228 | Expr *SubExpr = SubResult.get(); | ||||
19229 | E->setSubExpr(SubExpr); | ||||
19230 | E->setType(SubExpr->getType()); | ||||
19231 | E->setValueKind(SubExpr->getValueKind()); | ||||
19232 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19232, __extension__ __PRETTY_FUNCTION__)); | ||||
19233 | return E; | ||||
19234 | } | ||||
19235 | |||||
19236 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
19237 | return rebuildSugarExpr(E); | ||||
19238 | } | ||||
19239 | |||||
19240 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
19241 | return rebuildSugarExpr(E); | ||||
19242 | } | ||||
19243 | |||||
19244 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
19245 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19246 | if (SubResult.isInvalid()) return ExprError(); | ||||
19247 | |||||
19248 | Expr *SubExpr = SubResult.get(); | ||||
19249 | E->setSubExpr(SubExpr); | ||||
19250 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||
19251 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19251, __extension__ __PRETTY_FUNCTION__)); | ||||
19252 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19252, __extension__ __PRETTY_FUNCTION__)); | ||||
19253 | return E; | ||||
19254 | } | ||||
19255 | |||||
19256 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||
19257 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||
19258 | |||||
19259 | E->setType(VD->getType()); | ||||
19260 | |||||
19261 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19261, __extension__ __PRETTY_FUNCTION__)); | ||||
19262 | if (S.getLangOpts().CPlusPlus && | ||||
19263 | !(isa<CXXMethodDecl>(VD) && | ||||
19264 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||
19265 | E->setValueKind(VK_LValue); | ||||
19266 | |||||
19267 | return E; | ||||
19268 | } | ||||
19269 | |||||
19270 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
19271 | return resolveDecl(E, E->getMemberDecl()); | ||||
19272 | } | ||||
19273 | |||||
19274 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
19275 | return resolveDecl(E, E->getDecl()); | ||||
19276 | } | ||||
19277 | }; | ||||
19278 | } | ||||
19279 | |||||
19280 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
19281 | /// to have a function type. | ||||
19282 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||
19283 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||
19284 | if (Result.isInvalid()) return ExprError(); | ||||
19285 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||
19286 | } | ||||
19287 | |||||
19288 | namespace { | ||||
19289 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||
19290 | /// into one which resolves the type directly on the referring | ||||
19291 | /// expression. Strict preservation of the original source | ||||
19292 | /// structure is not a goal. | ||||
19293 | struct RebuildUnknownAnyExpr | ||||
19294 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||
19295 | |||||
19296 | Sema &S; | ||||
19297 | |||||
19298 | /// The current destination type. | ||||
19299 | QualType DestType; | ||||
19300 | |||||
19301 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||
19302 | : S(S), DestType(CastType) {} | ||||
19303 | |||||
19304 | ExprResult VisitStmt(Stmt *S) { | ||||
19305 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19305); | ||||
19306 | } | ||||
19307 | |||||
19308 | ExprResult VisitExpr(Expr *E) { | ||||
19309 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
19310 | << E->getSourceRange(); | ||||
19311 | return ExprError(); | ||||
19312 | } | ||||
19313 | |||||
19314 | ExprResult VisitCallExpr(CallExpr *E); | ||||
19315 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||
19316 | |||||
19317 | /// Rebuild an expression which simply semantically wraps another | ||||
19318 | /// expression which it shares the type and value kind of. | ||||
19319 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
19320 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19321 | if (SubResult.isInvalid()) return ExprError(); | ||||
19322 | Expr *SubExpr = SubResult.get(); | ||||
19323 | E->setSubExpr(SubExpr); | ||||
19324 | E->setType(SubExpr->getType()); | ||||
19325 | E->setValueKind(SubExpr->getValueKind()); | ||||
19326 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19326, __extension__ __PRETTY_FUNCTION__)); | ||||
19327 | return E; | ||||
19328 | } | ||||
19329 | |||||
19330 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
19331 | return rebuildSugarExpr(E); | ||||
19332 | } | ||||
19333 | |||||
19334 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
19335 | return rebuildSugarExpr(E); | ||||
19336 | } | ||||
19337 | |||||
19338 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
19339 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||
19340 | if (!Ptr) { | ||||
19341 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||
19342 | << E->getSourceRange(); | ||||
19343 | return ExprError(); | ||||
19344 | } | ||||
19345 | |||||
19346 | if (isa<CallExpr>(E->getSubExpr())) { | ||||
19347 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||
19348 | << E->getSourceRange(); | ||||
19349 | return ExprError(); | ||||
19350 | } | ||||
19351 | |||||
19352 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19352, __extension__ __PRETTY_FUNCTION__)); | ||||
19353 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19353, __extension__ __PRETTY_FUNCTION__)); | ||||
19354 | E->setType(DestType); | ||||
19355 | |||||
19356 | // Build the sub-expression as if it were an object of the pointee type. | ||||
19357 | DestType = Ptr->getPointeeType(); | ||||
19358 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
19359 | if (SubResult.isInvalid()) return ExprError(); | ||||
19360 | E->setSubExpr(SubResult.get()); | ||||
19361 | return E; | ||||
19362 | } | ||||
19363 | |||||
19364 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||
19365 | |||||
19366 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||
19367 | |||||
19368 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
19369 | return resolveDecl(E, E->getMemberDecl()); | ||||
19370 | } | ||||
19371 | |||||
19372 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
19373 | return resolveDecl(E, E->getDecl()); | ||||
19374 | } | ||||
19375 | }; | ||||
19376 | } | ||||
19377 | |||||
19378 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||
19379 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||
19380 | Expr *CalleeExpr = E->getCallee(); | ||||
19381 | |||||
19382 | enum FnKind { | ||||
19383 | FK_MemberFunction, | ||||
19384 | FK_FunctionPointer, | ||||
19385 | FK_BlockPointer | ||||
19386 | }; | ||||
19387 | |||||
19388 | FnKind Kind; | ||||
19389 | QualType CalleeType = CalleeExpr->getType(); | ||||
19390 | if (CalleeType == S.Context.BoundMemberTy) { | ||||
19391 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))(static_cast <bool> (isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)) ? void (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19391, __extension__ __PRETTY_FUNCTION__)); | ||||
19392 | Kind = FK_MemberFunction; | ||||
19393 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||
19394 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||
19395 | CalleeType = Ptr->getPointeeType(); | ||||
19396 | Kind = FK_FunctionPointer; | ||||
19397 | } else { | ||||
19398 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||
19399 | Kind = FK_BlockPointer; | ||||
19400 | } | ||||
19401 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||
19402 | |||||
19403 | // Verify that this is a legal result type of a function. | ||||
19404 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
19405 | unsigned diagID = diag::err_func_returning_array_function; | ||||
19406 | if (Kind == FK_BlockPointer) | ||||
19407 | diagID = diag::err_block_returning_array_function; | ||||
19408 | |||||
19409 | S.Diag(E->getExprLoc(), diagID) | ||||
19410 | << DestType->isFunctionType() << DestType; | ||||
19411 | return ExprError(); | ||||
19412 | } | ||||
19413 | |||||
19414 | // Otherwise, go ahead and set DestType as the call's result. | ||||
19415 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||
19416 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
19417 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19417, __extension__ __PRETTY_FUNCTION__)); | ||||
19418 | |||||
19419 | // Rebuild the function type, replacing the result type with DestType. | ||||
19420 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||
19421 | if (Proto) { | ||||
19422 | // __unknown_anytype(...) is a special case used by the debugger when | ||||
19423 | // it has no idea what a function's signature is. | ||||
19424 | // | ||||
19425 | // We want to build this call essentially under the K&R | ||||
19426 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||
19427 | // would foul up all sorts of assumptions. However, we cannot | ||||
19428 | // simply pass all arguments as variadic arguments, nor can we | ||||
19429 | // portably just call the function under a non-variadic type; see | ||||
19430 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||
19431 | // However, it turns out that in practice it is generally safe to | ||||
19432 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||
19433 | // "A foo(B,C,D,...);". The only known exception is with the | ||||
19434 | // Windows ABI, where any variadic function is implicitly cdecl | ||||
19435 | // regardless of its normal CC. Therefore we change the parameter | ||||
19436 | // types to match the types of the arguments. | ||||
19437 | // | ||||
19438 | // This is a hack, but it is far superior to moving the | ||||
19439 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||
19440 | |||||
19441 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||
19442 | SmallVector<QualType, 8> ArgTypes; | ||||
19443 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||
19444 | ArgTypes.reserve(E->getNumArgs()); | ||||
19445 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||
19446 | ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); | ||||
19447 | } | ||||
19448 | ParamTypes = ArgTypes; | ||||
19449 | } | ||||
19450 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||
19451 | Proto->getExtProtoInfo()); | ||||
19452 | } else { | ||||
19453 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||
19454 | FnType->getExtInfo()); | ||||
19455 | } | ||||
19456 | |||||
19457 | // Rebuild the appropriate pointer-to-function type. | ||||
19458 | switch (Kind) { | ||||
19459 | case FK_MemberFunction: | ||||
19460 | // Nothing to do. | ||||
19461 | break; | ||||
19462 | |||||
19463 | case FK_FunctionPointer: | ||||
19464 | DestType = S.Context.getPointerType(DestType); | ||||
19465 | break; | ||||
19466 | |||||
19467 | case FK_BlockPointer: | ||||
19468 | DestType = S.Context.getBlockPointerType(DestType); | ||||
19469 | break; | ||||
19470 | } | ||||
19471 | |||||
19472 | // Finally, we can recurse. | ||||
19473 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||
19474 | if (!CalleeResult.isUsable()) return ExprError(); | ||||
19475 | E->setCallee(CalleeResult.get()); | ||||
19476 | |||||
19477 | // Bind a temporary if necessary. | ||||
19478 | return S.MaybeBindToTemporary(E); | ||||
19479 | } | ||||
19480 | |||||
19481 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||
19482 | // Verify that this is a legal result type of a call. | ||||
19483 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
19484 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||
19485 | << DestType->isFunctionType() << DestType; | ||||
19486 | return ExprError(); | ||||
19487 | } | ||||
19488 | |||||
19489 | // Rewrite the method result type if available. | ||||
19490 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||
19491 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)(static_cast <bool> (Method->getReturnType() == S.Context .UnknownAnyTy) ? void (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19491, __extension__ __PRETTY_FUNCTION__)); | ||||
19492 | Method->setReturnType(DestType); | ||||
19493 | } | ||||
19494 | |||||
19495 | // Change the type of the message. | ||||
19496 | E->setType(DestType.getNonReferenceType()); | ||||
19497 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
19498 | |||||
19499 | return S.MaybeBindToTemporary(E); | ||||
19500 | } | ||||
19501 | |||||
19502 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
19503 | // The only case we should ever see here is a function-to-pointer decay. | ||||
19504 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||
19505 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19505, __extension__ __PRETTY_FUNCTION__)); | ||||
19506 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19506, __extension__ __PRETTY_FUNCTION__)); | ||||
19507 | |||||
19508 | E->setType(DestType); | ||||
19509 | |||||
19510 | // Rebuild the sub-expression as the pointee (function) type. | ||||
19511 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||
19512 | |||||
19513 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19514 | if (!Result.isUsable()) return ExprError(); | ||||
19515 | |||||
19516 | E->setSubExpr(Result.get()); | ||||
19517 | return E; | ||||
19518 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||
19519 | assert(E->isPRValue())(static_cast <bool> (E->isPRValue()) ? void (0) : __assert_fail ("E->isPRValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19519, __extension__ __PRETTY_FUNCTION__)); | ||||
19520 | assert(E->getObjectKind() == OK_Ordinary)(static_cast <bool> (E->getObjectKind() == OK_Ordinary ) ? void (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19520, __extension__ __PRETTY_FUNCTION__)); | ||||
19521 | |||||
19522 | assert(isa<BlockPointerType>(E->getType()))(static_cast <bool> (isa<BlockPointerType>(E-> getType())) ? void (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19522, __extension__ __PRETTY_FUNCTION__)); | ||||
19523 | |||||
19524 | E->setType(DestType); | ||||
19525 | |||||
19526 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||
19527 | DestType = S.Context.getLValueReferenceType(DestType); | ||||
19528 | |||||
19529 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19530 | if (!Result.isUsable()) return ExprError(); | ||||
19531 | |||||
19532 | E->setSubExpr(Result.get()); | ||||
19533 | return E; | ||||
19534 | } else { | ||||
19535 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19535); | ||||
19536 | } | ||||
19537 | } | ||||
19538 | |||||
19539 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||
19540 | ExprValueKind ValueKind = VK_LValue; | ||||
19541 | QualType Type = DestType; | ||||
19542 | |||||
19543 | // We know how to make this work for certain kinds of decls: | ||||
19544 | |||||
19545 | // - functions | ||||
19546 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||
19547 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||
19548 | DestType = Ptr->getPointeeType(); | ||||
19549 | ExprResult Result = resolveDecl(E, VD); | ||||
19550 | if (Result.isInvalid()) return ExprError(); | ||||
19551 | return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, | ||||
19552 | VK_PRValue); | ||||
19553 | } | ||||
19554 | |||||
19555 | if (!Type->isFunctionType()) { | ||||
19556 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||
19557 | << VD << E->getSourceRange(); | ||||
19558 | return ExprError(); | ||||
19559 | } | ||||
19560 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||
19561 | // We must match the FunctionDecl's type to the hack introduced in | ||||
19562 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||
19563 | // type. See the lengthy commentary in that routine. | ||||
19564 | QualType FDT = FD->getType(); | ||||
19565 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||
19566 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||
19567 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
19568 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||
19569 | SourceLocation Loc = FD->getLocation(); | ||||
19570 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||
19571 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||
19572 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||
19573 | SC_None, S.getCurFPFeatures().isFPConstrained(), | ||||
19574 | false /*isInlineSpecified*/, FD->hasPrototype(), | ||||
19575 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | ||||
19576 | |||||
19577 | if (FD->getQualifier()) | ||||
19578 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||
19579 | |||||
19580 | SmallVector<ParmVarDecl*, 16> Params; | ||||
19581 | for (const auto &AI : FT->param_types()) { | ||||
19582 | ParmVarDecl *Param = | ||||
19583 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||
19584 | Param->setScopeInfo(0, Params.size()); | ||||
19585 | Params.push_back(Param); | ||||
19586 | } | ||||
19587 | NewFD->setParams(Params); | ||||
19588 | DRE->setDecl(NewFD); | ||||
19589 | VD = DRE->getDecl(); | ||||
19590 | } | ||||
19591 | } | ||||
19592 | |||||
19593 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||
19594 | if (MD->isInstance()) { | ||||
19595 | ValueKind = VK_PRValue; | ||||
19596 | Type = S.Context.BoundMemberTy; | ||||
19597 | } | ||||
19598 | |||||
19599 | // Function references aren't l-values in C. | ||||
19600 | if (!S.getLangOpts().CPlusPlus) | ||||
19601 | ValueKind = VK_PRValue; | ||||
19602 | |||||
19603 | // - variables | ||||
19604 | } else if (isa<VarDecl>(VD)) { | ||||
19605 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||
19606 | Type = RefTy->getPointeeType(); | ||||
19607 | } else if (Type->isFunctionType()) { | ||||
19608 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||
19609 | << VD << E->getSourceRange(); | ||||
19610 | return ExprError(); | ||||
19611 | } | ||||
19612 | |||||
19613 | // - nothing else | ||||
19614 | } else { | ||||
19615 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||
19616 | << VD << E->getSourceRange(); | ||||
19617 | return ExprError(); | ||||
19618 | } | ||||
19619 | |||||
19620 | // Modifying the declaration like this is friendly to IR-gen but | ||||
19621 | // also really dangerous. | ||||
19622 | VD->setType(DestType); | ||||
19623 | E->setType(Type); | ||||
19624 | E->setValueKind(ValueKind); | ||||
19625 | return E; | ||||
19626 | } | ||||
19627 | |||||
19628 | /// Check a cast of an unknown-any type. We intentionally only | ||||
19629 | /// trigger this for C-style casts. | ||||
19630 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||
19631 | Expr *CastExpr, CastKind &CastKind, | ||||
19632 | ExprValueKind &VK, CXXCastPath &Path) { | ||||
19633 | // The type we're casting to must be either void or complete. | ||||
19634 | if (!CastType->isVoidType() && | ||||
19635 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||
19636 | diag::err_typecheck_cast_to_incomplete)) | ||||
19637 | return ExprError(); | ||||
19638 | |||||
19639 | // Rewrite the casted expression from scratch. | ||||
19640 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||
19641 | if (!result.isUsable()) return ExprError(); | ||||
19642 | |||||
19643 | CastExpr = result.get(); | ||||
19644 | VK = CastExpr->getValueKind(); | ||||
19645 | CastKind = CK_NoOp; | ||||
19646 | |||||
19647 | return CastExpr; | ||||
19648 | } | ||||
19649 | |||||
19650 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||
19651 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||
19652 | } | ||||
19653 | |||||
19654 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||
19655 | Expr *arg, QualType ¶mType) { | ||||
19656 | // If the syntactic form of the argument is not an explicit cast of | ||||
19657 | // any sort, just do default argument promotion. | ||||
19658 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||
19659 | if (!castArg) { | ||||
19660 | ExprResult result = DefaultArgumentPromotion(arg); | ||||
19661 | if (result.isInvalid()) return ExprError(); | ||||
19662 | paramType = result.get()->getType(); | ||||
19663 | return result; | ||||
19664 | } | ||||
19665 | |||||
19666 | // Otherwise, use the type that was written in the explicit cast. | ||||
19667 | assert(!arg->hasPlaceholderType())(static_cast <bool> (!arg->hasPlaceholderType()) ? void (0) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19667, __extension__ __PRETTY_FUNCTION__)); | ||||
19668 | paramType = castArg->getTypeAsWritten(); | ||||
19669 | |||||
19670 | // Copy-initialize a parameter of that type. | ||||
19671 | InitializedEntity entity = | ||||
19672 | InitializedEntity::InitializeParameter(Context, paramType, | ||||
19673 | /*consumed*/ false); | ||||
19674 | return PerformCopyInitialization(entity, callLoc, arg); | ||||
19675 | } | ||||
19676 | |||||
19677 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||
19678 | Expr *orig = E; | ||||
19679 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||
19680 | while (true) { | ||||
19681 | E = E->IgnoreParenImpCasts(); | ||||
19682 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||
19683 | E = call->getCallee(); | ||||
19684 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19685 | } else { | ||||
19686 | break; | ||||
19687 | } | ||||
19688 | } | ||||
19689 | |||||
19690 | SourceLocation loc; | ||||
19691 | NamedDecl *d; | ||||
19692 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||
19693 | loc = ref->getLocation(); | ||||
19694 | d = ref->getDecl(); | ||||
19695 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||
19696 | loc = mem->getMemberLoc(); | ||||
19697 | d = mem->getMemberDecl(); | ||||
19698 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||
19699 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19700 | loc = msg->getSelectorStartLoc(); | ||||
19701 | d = msg->getMethodDecl(); | ||||
19702 | if (!d) { | ||||
19703 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||
19704 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||
19705 | << orig->getSourceRange(); | ||||
19706 | return ExprError(); | ||||
19707 | } | ||||
19708 | } else { | ||||
19709 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
19710 | << E->getSourceRange(); | ||||
19711 | return ExprError(); | ||||
19712 | } | ||||
19713 | |||||
19714 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||
19715 | |||||
19716 | // Never recoverable. | ||||
19717 | return ExprError(); | ||||
19718 | } | ||||
19719 | |||||
19720 | /// Check for operands with placeholder types and complain if found. | ||||
19721 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||
19722 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||
19723 | if (!Context.isDependenceAllowed()) { | ||||
19724 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
19725 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
19726 | // been dealt with before checking the operands. | ||||
19727 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||
19728 | if (!Result.isUsable()) return ExprError(); | ||||
19729 | E = Result.get(); | ||||
19730 | } | ||||
19731 | |||||
19732 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||
19733 | if (!placeholderType) return E; | ||||
19734 | |||||
19735 | switch (placeholderType->getKind()) { | ||||
19736 | |||||
19737 | // Overloaded expressions. | ||||
19738 | case BuiltinType::Overload: { | ||||
19739 | // Try to resolve a single function template specialization. | ||||
19740 | // This is obligatory. | ||||
19741 | ExprResult Result = E; | ||||
19742 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||
19743 | return Result; | ||||
19744 | |||||
19745 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
19746 | // leaves Result unchanged on failure. | ||||
19747 | Result = E; | ||||
19748 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||
19749 | return Result; | ||||
19750 | |||||
19751 | // If that failed, try to recover with a call. | ||||
19752 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||
19753 | /*complain*/ true); | ||||
19754 | return Result; | ||||
19755 | } | ||||
19756 | |||||
19757 | // Bound member functions. | ||||
19758 | case BuiltinType::BoundMember: { | ||||
19759 | ExprResult result = E; | ||||
19760 | const Expr *BME = E->IgnoreParens(); | ||||
19761 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||
19762 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||
19763 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||
19764 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||
19765 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||
19766 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||
19767 | DeclarationName::CXXDestructorName) | ||||
19768 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||
19769 | } | ||||
19770 | tryToRecoverWithCall(result, PD, | ||||
19771 | /*complain*/ true); | ||||
19772 | return result; | ||||
19773 | } | ||||
19774 | |||||
19775 | // ARC unbridged casts. | ||||
19776 | case BuiltinType::ARCUnbridgedCast: { | ||||
19777 | Expr *realCast = stripARCUnbridgedCast(E); | ||||
19778 | diagnoseARCUnbridgedCast(realCast); | ||||
19779 | return realCast; | ||||
19780 | } | ||||
19781 | |||||
19782 | // Expressions of unknown type. | ||||
19783 | case BuiltinType::UnknownAny: | ||||
19784 | return diagnoseUnknownAnyExpr(*this, E); | ||||
19785 | |||||
19786 | // Pseudo-objects. | ||||
19787 | case BuiltinType::PseudoObject: | ||||
19788 | return checkPseudoObjectRValue(E); | ||||
19789 | |||||
19790 | case BuiltinType::BuiltinFn: { | ||||
19791 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||
19792 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||
19793 | if (DRE) { | ||||
19794 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||
19795 | if (FD->getBuiltinID() == Builtin::BI__noop) { | ||||
19796 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||
19797 | CK_BuiltinFnToFnPtr) | ||||
19798 | .get(); | ||||
19799 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||
19800 | VK_PRValue, SourceLocation(), | ||||
19801 | FPOptionsOverride()); | ||||
19802 | } | ||||
19803 | } | ||||
19804 | |||||
19805 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||
19806 | return ExprError(); | ||||
19807 | } | ||||
19808 | |||||
19809 | case BuiltinType::IncompleteMatrixIdx: | ||||
19810 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||
19811 | ->getRowIdx() | ||||
19812 | ->getBeginLoc(), | ||||
19813 | diag::err_matrix_incomplete_index); | ||||
19814 | return ExprError(); | ||||
19815 | |||||
19816 | // Expressions of unknown type. | ||||
19817 | case BuiltinType::OMPArraySection: | ||||
19818 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||
19819 | return ExprError(); | ||||
19820 | |||||
19821 | // Expressions of unknown type. | ||||
19822 | case BuiltinType::OMPArrayShaping: | ||||
19823 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||
19824 | |||||
19825 | case BuiltinType::OMPIterator: | ||||
19826 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||
19827 | |||||
19828 | // Everything else should be impossible. | ||||
19829 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
19830 | case BuiltinType::Id: | ||||
19831 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
19832 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
19833 | case BuiltinType::Id: | ||||
19834 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
19835 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
19836 | case BuiltinType::Id: | ||||
19837 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
19838 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
19839 | case BuiltinType::Id: | ||||
19840 | #include "clang/Basic/PPCTypes.def" | ||||
19841 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
19842 | #include "clang/Basic/RISCVVTypes.def" | ||||
19843 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||
19844 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||
19845 | #include "clang/AST/BuiltinTypes.def" | ||||
19846 | break; | ||||
19847 | } | ||||
19848 | |||||
19849 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19849); | ||||
19850 | } | ||||
19851 | |||||
19852 | bool Sema::CheckCaseExpression(Expr *E) { | ||||
19853 | if (E->isTypeDependent()) | ||||
19854 | return true; | ||||
19855 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||
19856 | return E->getType()->isIntegralOrEnumerationType(); | ||||
19857 | return false; | ||||
19858 | } | ||||
19859 | |||||
19860 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||
19861 | ExprResult | ||||
19862 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||
19863 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19864, __extension__ __PRETTY_FUNCTION__)) | ||||
19864 | "Unknown Objective-C Boolean value!")(static_cast <bool> ((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!" ) ? void (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaExpr.cpp" , 19864, __extension__ __PRETTY_FUNCTION__)); | ||||
19865 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||
19866 | if (!Context.getBOOLDecl()) { | ||||
19867 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||
19868 | Sema::LookupOrdinaryName); | ||||
19869 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||
19870 | NamedDecl *ND = Result.getFoundDecl(); | ||||
19871 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||
19872 | Context.setBOOLDecl(TD); | ||||
19873 | } | ||||
19874 | } | ||||
19875 | if (Context.getBOOLDecl()) | ||||
19876 | BoolT = Context.getBOOLType(); | ||||
19877 | return new (Context) | ||||
19878 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||
19879 | } | ||||
19880 | |||||
19881 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||
19882 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||
19883 | SourceLocation RParen) { | ||||
19884 | auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { | ||||
19885 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
19886 | return Spec.getPlatform() == Platform; | ||||
19887 | }); | ||||
19888 | // Transcribe the "ios" availability check to "maccatalyst" when compiling | ||||
19889 | // for "maccatalyst" if "maccatalyst" is not specified. | ||||
19890 | if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { | ||||
19891 | Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
19892 | return Spec.getPlatform() == "ios"; | ||||
19893 | }); | ||||
19894 | } | ||||
19895 | if (Spec == AvailSpecs.end()) | ||||
19896 | return None; | ||||
19897 | return Spec->getVersion(); | ||||
19898 | }; | ||||
19899 | |||||
19900 | VersionTuple Version; | ||||
19901 | if (auto MaybeVersion = | ||||
19902 | FindSpecVersion(Context.getTargetInfo().getPlatformName())) | ||||
19903 | Version = *MaybeVersion; | ||||
19904 | |||||
19905 | // The use of `@available` in the enclosing context should be analyzed to | ||||
19906 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||
19907 | if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) | ||||
19908 | Context->HasPotentialAvailabilityViolations = true; | ||||
19909 | |||||
19910 | return new (Context) | ||||
19911 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||
19912 | } | ||||
19913 | |||||
19914 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||
19915 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||
19916 | if (!Context.getLangOpts().RecoveryAST) | ||||
19917 | return ExprError(); | ||||
19918 | |||||
19919 | if (isSFINAEContext()) | ||||
19920 | return ExprError(); | ||||
19921 | |||||
19922 | if (T.isNull() || T->isUndeducedType() || | ||||
19923 | !Context.getLangOpts().RecoveryASTType) | ||||
19924 | // We don't know the concrete type, fallback to dependent type. | ||||
19925 | T = Context.DependentTy; | ||||
19926 | |||||
19927 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||
19928 | } |
1 | //===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | /// \file |
10 | /// Defines the clang::ASTContext interface. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_AST_ASTCONTEXT_H |
15 | #define LLVM_CLANG_AST_ASTCONTEXT_H |
16 | |
17 | #include "clang/AST/ASTContextAllocate.h" |
18 | #include "clang/AST/ASTFwd.h" |
19 | #include "clang/AST/CanonicalType.h" |
20 | #include "clang/AST/CommentCommandTraits.h" |
21 | #include "clang/AST/ComparisonCategories.h" |
22 | #include "clang/AST/Decl.h" |
23 | #include "clang/AST/DeclBase.h" |
24 | #include "clang/AST/DeclarationName.h" |
25 | #include "clang/AST/ExternalASTSource.h" |
26 | #include "clang/AST/NestedNameSpecifier.h" |
27 | #include "clang/AST/PrettyPrinter.h" |
28 | #include "clang/AST/RawCommentList.h" |
29 | #include "clang/AST/TemplateName.h" |
30 | #include "clang/AST/Type.h" |
31 | #include "clang/Basic/AddressSpaces.h" |
32 | #include "clang/Basic/AttrKinds.h" |
33 | #include "clang/Basic/IdentifierTable.h" |
34 | #include "clang/Basic/LLVM.h" |
35 | #include "clang/Basic/LangOptions.h" |
36 | #include "clang/Basic/Linkage.h" |
37 | #include "clang/Basic/NoSanitizeList.h" |
38 | #include "clang/Basic/OperatorKinds.h" |
39 | #include "clang/Basic/PartialDiagnostic.h" |
40 | #include "clang/Basic/ProfileList.h" |
41 | #include "clang/Basic/SourceLocation.h" |
42 | #include "clang/Basic/Specifiers.h" |
43 | #include "clang/Basic/TargetCXXABI.h" |
44 | #include "clang/Basic/XRayLists.h" |
45 | #include "llvm/ADT/APSInt.h" |
46 | #include "llvm/ADT/ArrayRef.h" |
47 | #include "llvm/ADT/DenseMap.h" |
48 | #include "llvm/ADT/DenseSet.h" |
49 | #include "llvm/ADT/FoldingSet.h" |
50 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
51 | #include "llvm/ADT/MapVector.h" |
52 | #include "llvm/ADT/None.h" |
53 | #include "llvm/ADT/Optional.h" |
54 | #include "llvm/ADT/PointerIntPair.h" |
55 | #include "llvm/ADT/PointerUnion.h" |
56 | #include "llvm/ADT/SmallVector.h" |
57 | #include "llvm/ADT/StringMap.h" |
58 | #include "llvm/ADT/StringRef.h" |
59 | #include "llvm/ADT/TinyPtrVector.h" |
60 | #include "llvm/ADT/Triple.h" |
61 | #include "llvm/ADT/iterator_range.h" |
62 | #include "llvm/Support/AlignOf.h" |
63 | #include "llvm/Support/Allocator.h" |
64 | #include "llvm/Support/Casting.h" |
65 | #include "llvm/Support/Compiler.h" |
66 | #include "llvm/Support/TypeSize.h" |
67 | #include <cassert> |
68 | #include <cstddef> |
69 | #include <cstdint> |
70 | #include <iterator> |
71 | #include <memory> |
72 | #include <string> |
73 | #include <type_traits> |
74 | #include <utility> |
75 | #include <vector> |
76 | |
77 | namespace llvm { |
78 | |
79 | class APFixedPoint; |
80 | class FixedPointSemantics; |
81 | struct fltSemantics; |
82 | template <typename T, unsigned N> class SmallPtrSet; |
83 | |
84 | } // namespace llvm |
85 | |
86 | namespace clang { |
87 | |
88 | class APValue; |
89 | class ASTMutationListener; |
90 | class ASTRecordLayout; |
91 | class AtomicExpr; |
92 | class BlockExpr; |
93 | class BuiltinTemplateDecl; |
94 | class CharUnits; |
95 | class ConceptDecl; |
96 | class CXXABI; |
97 | class CXXConstructorDecl; |
98 | class CXXMethodDecl; |
99 | class CXXRecordDecl; |
100 | class DiagnosticsEngine; |
101 | class ParentMapContext; |
102 | class DynTypedNode; |
103 | class DynTypedNodeList; |
104 | class Expr; |
105 | class GlobalDecl; |
106 | class ItaniumMangleContext; |
107 | class MangleContext; |
108 | class MangleNumberingContext; |
109 | class MaterializeTemporaryExpr; |
110 | class MemberSpecializationInfo; |
111 | class Module; |
112 | struct MSGuidDeclParts; |
113 | class ObjCCategoryDecl; |
114 | class ObjCCategoryImplDecl; |
115 | class ObjCContainerDecl; |
116 | class ObjCImplDecl; |
117 | class ObjCImplementationDecl; |
118 | class ObjCInterfaceDecl; |
119 | class ObjCIvarDecl; |
120 | class ObjCMethodDecl; |
121 | class ObjCPropertyDecl; |
122 | class ObjCPropertyImplDecl; |
123 | class ObjCProtocolDecl; |
124 | class ObjCTypeParamDecl; |
125 | class OMPTraitInfo; |
126 | struct ParsedTargetAttr; |
127 | class Preprocessor; |
128 | class Stmt; |
129 | class StoredDeclsMap; |
130 | class TargetAttr; |
131 | class TargetInfo; |
132 | class TemplateDecl; |
133 | class TemplateParameterList; |
134 | class TemplateTemplateParmDecl; |
135 | class TemplateTypeParmDecl; |
136 | class UnresolvedSetIterator; |
137 | class UsingShadowDecl; |
138 | class VarTemplateDecl; |
139 | class VTableContextBase; |
140 | struct BlockVarCopyInit; |
141 | |
142 | namespace Builtin { |
143 | |
144 | class Context; |
145 | |
146 | } // namespace Builtin |
147 | |
148 | enum BuiltinTemplateKind : int; |
149 | enum OpenCLTypeKind : uint8_t; |
150 | |
151 | namespace comments { |
152 | |
153 | class FullComment; |
154 | |
155 | } // namespace comments |
156 | |
157 | namespace interp { |
158 | |
159 | class Context; |
160 | |
161 | } // namespace interp |
162 | |
163 | namespace serialization { |
164 | template <class> class AbstractTypeReader; |
165 | } // namespace serialization |
166 | |
167 | struct TypeInfo { |
168 | uint64_t Width = 0; |
169 | unsigned Align = 0; |
170 | bool AlignIsRequired : 1; |
171 | |
172 | TypeInfo() : AlignIsRequired(false) {} |
173 | TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired) |
174 | : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {} |
175 | }; |
176 | |
177 | struct TypeInfoChars { |
178 | CharUnits Width; |
179 | CharUnits Align; |
180 | bool AlignIsRequired : 1; |
181 | |
182 | TypeInfoChars() : AlignIsRequired(false) {} |
183 | TypeInfoChars(CharUnits Width, CharUnits Align, bool AlignIsRequired) |
184 | : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {} |
185 | }; |
186 | |
187 | /// Holds long-lived AST nodes (such as types and decls) that can be |
188 | /// referred to throughout the semantic analysis of a file. |
189 | class ASTContext : public RefCountedBase<ASTContext> { |
190 | friend class NestedNameSpecifier; |
191 | |
192 | mutable SmallVector<Type *, 0> Types; |
193 | mutable llvm::FoldingSet<ExtQuals> ExtQualNodes; |
194 | mutable llvm::FoldingSet<ComplexType> ComplexTypes; |
195 | mutable llvm::FoldingSet<PointerType> PointerTypes; |
196 | mutable llvm::FoldingSet<AdjustedType> AdjustedTypes; |
197 | mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes; |
198 | mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes; |
199 | mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes; |
200 | mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes; |
201 | mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &> |
202 | ConstantArrayTypes; |
203 | mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes; |
204 | mutable std::vector<VariableArrayType*> VariableArrayTypes; |
205 | mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes; |
206 | mutable llvm::FoldingSet<DependentSizedExtVectorType> |
207 | DependentSizedExtVectorTypes; |
208 | mutable llvm::FoldingSet<DependentAddressSpaceType> |
209 | DependentAddressSpaceTypes; |
210 | mutable llvm::FoldingSet<VectorType> VectorTypes; |
211 | mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes; |
212 | mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes; |
213 | mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes; |
214 | mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes; |
215 | mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&> |
216 | FunctionProtoTypes; |
217 | mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes; |
218 | mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes; |
219 | mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes; |
220 | mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes; |
221 | mutable llvm::FoldingSet<SubstTemplateTypeParmType> |
222 | SubstTemplateTypeParmTypes; |
223 | mutable llvm::FoldingSet<SubstTemplateTypeParmPackType> |
224 | SubstTemplateTypeParmPackTypes; |
225 | mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&> |
226 | TemplateSpecializationTypes; |
227 | mutable llvm::FoldingSet<ParenType> ParenTypes; |
228 | mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes; |
229 | mutable llvm::FoldingSet<DependentNameType> DependentNameTypes; |
230 | mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType, |
231 | ASTContext&> |
232 | DependentTemplateSpecializationTypes; |
233 | llvm::FoldingSet<PackExpansionType> PackExpansionTypes; |
234 | mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes; |
235 | mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes; |
236 | mutable llvm::FoldingSet<DependentUnaryTransformType> |
237 | DependentUnaryTransformTypes; |
238 | mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes; |
239 | mutable llvm::FoldingSet<DeducedTemplateSpecializationType> |
240 | DeducedTemplateSpecializationTypes; |
241 | mutable llvm::FoldingSet<AtomicType> AtomicTypes; |
242 | llvm::FoldingSet<AttributedType> AttributedTypes; |
243 | mutable llvm::FoldingSet<PipeType> PipeTypes; |
244 | mutable llvm::FoldingSet<ExtIntType> ExtIntTypes; |
245 | mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes; |
246 | |
247 | mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames; |
248 | mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames; |
249 | mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> |
250 | SubstTemplateTemplateParms; |
251 | mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage, |
252 | ASTContext&> |
253 | SubstTemplateTemplateParmPacks; |
254 | |
255 | /// The set of nested name specifiers. |
256 | /// |
257 | /// This set is managed by the NestedNameSpecifier class. |
258 | mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers; |
259 | mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr; |
260 | |
261 | /// A cache mapping from RecordDecls to ASTRecordLayouts. |
262 | /// |
263 | /// This is lazily created. This is intentionally not serialized. |
264 | mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> |
265 | ASTRecordLayouts; |
266 | mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> |
267 | ObjCLayouts; |
268 | |
269 | /// A cache from types to size and alignment information. |
270 | using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; |
271 | mutable TypeInfoMap MemoizedTypeInfo; |
272 | |
273 | /// A cache from types to unadjusted alignment information. Only ARM and |
274 | /// AArch64 targets need this information, keeping it separate prevents |
275 | /// imposing overhead on TypeInfo size. |
276 | using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>; |
277 | mutable UnadjustedAlignMap MemoizedUnadjustedAlign; |
278 | |
279 | /// A cache mapping from CXXRecordDecls to key functions. |
280 | llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; |
281 | |
282 | /// Mapping from ObjCContainers to their ObjCImplementations. |
283 | llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls; |
284 | |
285 | /// Mapping from ObjCMethod to its duplicate declaration in the same |
286 | /// interface. |
287 | llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls; |
288 | |
289 | /// Mapping from __block VarDecls to BlockVarCopyInit. |
290 | llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits; |
291 | |
292 | /// Mapping from GUIDs to the corresponding MSGuidDecl. |
293 | mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls; |
294 | |
295 | /// Mapping from APValues to the corresponding TemplateParamObjects. |
296 | mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls; |
297 | |
298 | /// A cache mapping a string value to a StringLiteral object with the same |
299 | /// value. |
300 | /// |
301 | /// This is lazily created. This is intentionally not serialized. |
302 | mutable llvm::StringMap<StringLiteral *> StringLiteralCache; |
303 | |
304 | /// MD5 hash of CUID. It is calculated when first used and cached by this |
305 | /// data member. |
306 | mutable std::string CUIDHash; |
307 | |
308 | /// Representation of a "canonical" template template parameter that |
309 | /// is used in canonical template names. |
310 | class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { |
311 | TemplateTemplateParmDecl *Parm; |
312 | |
313 | public: |
314 | CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) |
315 | : Parm(Parm) {} |
316 | |
317 | TemplateTemplateParmDecl *getParam() const { return Parm; } |
318 | |
319 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) { |
320 | Profile(ID, C, Parm); |
321 | } |
322 | |
323 | static void Profile(llvm::FoldingSetNodeID &ID, |
324 | const ASTContext &C, |
325 | TemplateTemplateParmDecl *Parm); |
326 | }; |
327 | mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm, |
328 | const ASTContext&> |
329 | CanonTemplateTemplateParms; |
330 | |
331 | TemplateTemplateParmDecl * |
332 | getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; |
333 | |
334 | /// The typedef for the __int128_t type. |
335 | mutable TypedefDecl *Int128Decl = nullptr; |
336 | |
337 | /// The typedef for the __uint128_t type. |
338 | mutable TypedefDecl *UInt128Decl = nullptr; |
339 | |
340 | /// The typedef for the target specific predefined |
341 | /// __builtin_va_list type. |
342 | mutable TypedefDecl *BuiltinVaListDecl = nullptr; |
343 | |
344 | /// The typedef for the predefined \c __builtin_ms_va_list type. |
345 | mutable TypedefDecl *BuiltinMSVaListDecl = nullptr; |
346 | |
347 | /// The typedef for the predefined \c id type. |
348 | mutable TypedefDecl *ObjCIdDecl = nullptr; |
349 | |
350 | /// The typedef for the predefined \c SEL type. |
351 | mutable TypedefDecl *ObjCSelDecl = nullptr; |
352 | |
353 | /// The typedef for the predefined \c Class type. |
354 | mutable TypedefDecl *ObjCClassDecl = nullptr; |
355 | |
356 | /// The typedef for the predefined \c Protocol class in Objective-C. |
357 | mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr; |
358 | |
359 | /// The typedef for the predefined 'BOOL' type. |
360 | mutable TypedefDecl *BOOLDecl = nullptr; |
361 | |
362 | // Typedefs which may be provided defining the structure of Objective-C |
363 | // pseudo-builtins |
364 | QualType ObjCIdRedefinitionType; |
365 | QualType ObjCClassRedefinitionType; |
366 | QualType ObjCSelRedefinitionType; |
367 | |
368 | /// The identifier 'bool'. |
369 | mutable IdentifierInfo *BoolName = nullptr; |
370 | |
371 | /// The identifier 'NSObject'. |
372 | mutable IdentifierInfo *NSObjectName = nullptr; |
373 | |
374 | /// The identifier 'NSCopying'. |
375 | IdentifierInfo *NSCopyingName = nullptr; |
376 | |
377 | /// The identifier '__make_integer_seq'. |
378 | mutable IdentifierInfo *MakeIntegerSeqName = nullptr; |
379 | |
380 | /// The identifier '__type_pack_element'. |
381 | mutable IdentifierInfo *TypePackElementName = nullptr; |
382 | |
383 | QualType ObjCConstantStringType; |
384 | mutable RecordDecl *CFConstantStringTagDecl = nullptr; |
385 | mutable TypedefDecl *CFConstantStringTypeDecl = nullptr; |
386 | |
387 | mutable QualType ObjCSuperType; |
388 | |
389 | QualType ObjCNSStringType; |
390 | |
391 | /// The typedef declaration for the Objective-C "instancetype" type. |
392 | TypedefDecl *ObjCInstanceTypeDecl = nullptr; |
393 | |
394 | /// The type for the C FILE type. |
395 | TypeDecl *FILEDecl = nullptr; |
396 | |
397 | /// The type for the C jmp_buf type. |
398 | TypeDecl *jmp_bufDecl = nullptr; |
399 | |
400 | /// The type for the C sigjmp_buf type. |
401 | TypeDecl *sigjmp_bufDecl = nullptr; |
402 | |
403 | /// The type for the C ucontext_t type. |
404 | TypeDecl *ucontext_tDecl = nullptr; |
405 | |
406 | /// Type for the Block descriptor for Blocks CodeGen. |
407 | /// |
408 | /// Since this is only used for generation of debug info, it is not |
409 | /// serialized. |
410 | mutable RecordDecl *BlockDescriptorType = nullptr; |
411 | |
412 | /// Type for the Block descriptor for Blocks CodeGen. |
413 | /// |
414 | /// Since this is only used for generation of debug info, it is not |
415 | /// serialized. |
416 | mutable RecordDecl *BlockDescriptorExtendedType = nullptr; |
417 | |
418 | /// Declaration for the CUDA cudaConfigureCall function. |
419 | FunctionDecl *cudaConfigureCallDecl = nullptr; |
420 | |
421 | /// Keeps track of all declaration attributes. |
422 | /// |
423 | /// Since so few decls have attrs, we keep them in a hash map instead of |
424 | /// wasting space in the Decl class. |
425 | llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs; |
426 | |
427 | /// A mapping from non-redeclarable declarations in modules that were |
428 | /// merged with other declarations to the canonical declaration that they were |
429 | /// merged into. |
430 | llvm::DenseMap<Decl*, Decl*> MergedDecls; |
431 | |
432 | /// A mapping from a defining declaration to a list of modules (other |
433 | /// than the owning module of the declaration) that contain merged |
434 | /// definitions of that entity. |
435 | llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules; |
436 | |
437 | /// Initializers for a module, in order. Each Decl will be either |
438 | /// something that has a semantic effect on startup (such as a variable with |
439 | /// a non-constant initializer), or an ImportDecl (which recursively triggers |
440 | /// initialization of another module). |
441 | struct PerModuleInitializers { |
442 | llvm::SmallVector<Decl*, 4> Initializers; |
443 | llvm::SmallVector<uint32_t, 4> LazyInitializers; |
444 | |
445 | void resolve(ASTContext &Ctx); |
446 | }; |
447 | llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers; |
448 | |
449 | ASTContext &this_() { return *this; } |
450 | |
451 | public: |
452 | /// A type synonym for the TemplateOrInstantiation mapping. |
453 | using TemplateOrSpecializationInfo = |
454 | llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>; |
455 | |
456 | private: |
457 | friend class ASTDeclReader; |
458 | friend class ASTReader; |
459 | friend class ASTWriter; |
460 | template <class> friend class serialization::AbstractTypeReader; |
461 | friend class CXXRecordDecl; |
462 | friend class IncrementalParser; |
463 | |
464 | /// A mapping to contain the template or declaration that |
465 | /// a variable declaration describes or was instantiated from, |
466 | /// respectively. |
467 | /// |
468 | /// For non-templates, this value will be NULL. For variable |
469 | /// declarations that describe a variable template, this will be a |
470 | /// pointer to a VarTemplateDecl. For static data members |
471 | /// of class template specializations, this will be the |
472 | /// MemberSpecializationInfo referring to the member variable that was |
473 | /// instantiated or specialized. Thus, the mapping will keep track of |
474 | /// the static data member templates from which static data members of |
475 | /// class template specializations were instantiated. |
476 | /// |
477 | /// Given the following example: |
478 | /// |
479 | /// \code |
480 | /// template<typename T> |
481 | /// struct X { |
482 | /// static T value; |
483 | /// }; |
484 | /// |
485 | /// template<typename T> |
486 | /// T X<T>::value = T(17); |
487 | /// |
488 | /// int *x = &X<int>::value; |
489 | /// \endcode |
490 | /// |
491 | /// This mapping will contain an entry that maps from the VarDecl for |
492 | /// X<int>::value to the corresponding VarDecl for X<T>::value (within the |
493 | /// class template X) and will be marked TSK_ImplicitInstantiation. |
494 | llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo> |
495 | TemplateOrInstantiation; |
496 | |
497 | /// Keeps track of the declaration from which a using declaration was |
498 | /// created during instantiation. |
499 | /// |
500 | /// The source and target declarations are always a UsingDecl, an |
501 | /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl. |
502 | /// |
503 | /// For example: |
504 | /// \code |
505 | /// template<typename T> |
506 | /// struct A { |
507 | /// void f(); |
508 | /// }; |
509 | /// |
510 | /// template<typename T> |
511 | /// struct B : A<T> { |
512 | /// using A<T>::f; |
513 | /// }; |
514 | /// |
515 | /// template struct B<int>; |
516 | /// \endcode |
517 | /// |
518 | /// This mapping will contain an entry that maps from the UsingDecl in |
519 | /// B<int> to the UnresolvedUsingDecl in B<T>. |
520 | llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl; |
521 | |
522 | /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps |
523 | /// from the instantiated using-enum to the templated decl from whence it |
524 | /// came. |
525 | /// Note that using-enum-declarations cannot be dependent and |
526 | /// thus will never be instantiated from an "unresolved" |
527 | /// version thereof (as with using-declarations), so each mapping is from |
528 | /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl. |
529 | llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *> |
530 | InstantiatedFromUsingEnumDecl; |
531 | |
532 | /// Simlarly maps instantiated UsingShadowDecls to their origin. |
533 | llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*> |
534 | InstantiatedFromUsingShadowDecl; |
535 | |
536 | llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl; |
537 | |
538 | /// Mapping that stores the methods overridden by a given C++ |
539 | /// member function. |
540 | /// |
541 | /// Since most C++ member functions aren't virtual and therefore |
542 | /// don't override anything, we store the overridden functions in |
543 | /// this map on the side rather than within the CXXMethodDecl structure. |
544 | using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>; |
545 | llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods; |
546 | |
547 | /// Mapping from each declaration context to its corresponding |
548 | /// mangling numbering context (used for constructs like lambdas which |
549 | /// need to be consistently numbered for the mangler). |
550 | llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>> |
551 | MangleNumberingContexts; |
552 | llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>> |
553 | ExtraMangleNumberingContexts; |
554 | |
555 | /// Side-table of mangling numbers for declarations which rarely |
556 | /// need them (like static local vars). |
557 | llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers; |
558 | llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers; |
559 | /// Mapping the associated device lambda mangling number if present. |
560 | mutable llvm::DenseMap<const CXXRecordDecl *, unsigned> |
561 | DeviceLambdaManglingNumbers; |
562 | |
563 | /// Mapping that stores parameterIndex values for ParmVarDecls when |
564 | /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex. |
565 | using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>; |
566 | ParameterIndexTable ParamIndices; |
567 | |
568 | ImportDecl *FirstLocalImport = nullptr; |
569 | ImportDecl *LastLocalImport = nullptr; |
570 | |
571 | TranslationUnitDecl *TUDecl = nullptr; |
572 | mutable ExternCContextDecl *ExternCContext = nullptr; |
573 | mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr; |
574 | mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr; |
575 | |
576 | /// The associated SourceManager object. |
577 | SourceManager &SourceMgr; |
578 | |
579 | /// The language options used to create the AST associated with |
580 | /// this ASTContext object. |
581 | LangOptions &LangOpts; |
582 | |
583 | /// NoSanitizeList object that is used by sanitizers to decide which |
584 | /// entities should not be instrumented. |
585 | std::unique_ptr<NoSanitizeList> NoSanitizeL; |
586 | |
587 | /// Function filtering mechanism to determine whether a given function |
588 | /// should be imbued with the XRay "always" or "never" attributes. |
589 | std::unique_ptr<XRayFunctionFilter> XRayFilter; |
590 | |
591 | /// ProfileList object that is used by the profile instrumentation |
592 | /// to decide which entities should be instrumented. |
593 | std::unique_ptr<ProfileList> ProfList; |
594 | |
595 | /// The allocator used to create AST objects. |
596 | /// |
597 | /// AST objects are never destructed; rather, all memory associated with the |
598 | /// AST objects will be released when the ASTContext itself is destroyed. |
599 | mutable llvm::BumpPtrAllocator BumpAlloc; |
600 | |
601 | /// Allocator for partial diagnostics. |
602 | PartialDiagnostic::DiagStorageAllocator DiagAllocator; |
603 | |
604 | /// The current C++ ABI. |
605 | std::unique_ptr<CXXABI> ABI; |
606 | CXXABI *createCXXABI(const TargetInfo &T); |
607 | |
608 | /// The logical -> physical address space map. |
609 | const LangASMap *AddrSpaceMap = nullptr; |
610 | |
611 | /// Address space map mangling must be used with language specific |
612 | /// address spaces (e.g. OpenCL/CUDA) |
613 | bool AddrSpaceMapMangling; |
614 | |
615 | const TargetInfo *Target = nullptr; |
616 | const TargetInfo *AuxTarget = nullptr; |
617 | clang::PrintingPolicy PrintingPolicy; |
618 | std::unique_ptr<interp::Context> InterpContext; |
619 | std::unique_ptr<ParentMapContext> ParentMapCtx; |
620 | |
621 | /// Keeps track of the deallocated DeclListNodes for future reuse. |
622 | DeclListNode *ListNodeFreeList = nullptr; |
623 | |
624 | public: |
625 | IdentifierTable &Idents; |
626 | SelectorTable &Selectors; |
627 | Builtin::Context &BuiltinInfo; |
628 | const TranslationUnitKind TUKind; |
629 | mutable DeclarationNameTable DeclarationNames; |
630 | IntrusiveRefCntPtr<ExternalASTSource> ExternalSource; |
631 | ASTMutationListener *Listener = nullptr; |
632 | |
633 | /// Returns the clang bytecode interpreter context. |
634 | interp::Context &getInterpContext(); |
635 | |
636 | /// Returns the dynamic AST node parent map context. |
637 | ParentMapContext &getParentMapContext(); |
638 | |
639 | // A traversal scope limits the parts of the AST visible to certain analyses. |
640 | // RecursiveASTVisitor only visits specified children of TranslationUnitDecl. |
641 | // getParents() will only observe reachable parent edges. |
642 | // |
643 | // The scope is defined by a set of "top-level" declarations which will be |
644 | // visible under the TranslationUnitDecl. |
645 | // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}. |
646 | // |
647 | // After setTraversalScope({foo, bar}), the exposed AST looks like: |
648 | // TranslationUnitDecl |
649 | // - foo |
650 | // - ... |
651 | // - bar |
652 | // - ... |
653 | // All other siblings of foo and bar are pruned from the tree. |
654 | // (However they are still accessible via TranslationUnitDecl->decls()) |
655 | // |
656 | // Changing the scope clears the parent cache, which is expensive to rebuild. |
657 | std::vector<Decl *> getTraversalScope() const { return TraversalScope; } |
658 | void setTraversalScope(const std::vector<Decl *> &); |
659 | |
660 | /// Forwards to get node parents from the ParentMapContext. New callers should |
661 | /// use ParentMapContext::getParents() directly. |
662 | template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node); |
663 | |
664 | const clang::PrintingPolicy &getPrintingPolicy() const { |
665 | return PrintingPolicy; |
666 | } |
667 | |
668 | void setPrintingPolicy(const clang::PrintingPolicy &Policy) { |
669 | PrintingPolicy = Policy; |
670 | } |
671 | |
672 | SourceManager& getSourceManager() { return SourceMgr; } |
673 | const SourceManager& getSourceManager() const { return SourceMgr; } |
674 | |
675 | llvm::BumpPtrAllocator &getAllocator() const { |
676 | return BumpAlloc; |
677 | } |
678 | |
679 | void *Allocate(size_t Size, unsigned Align = 8) const { |
680 | return BumpAlloc.Allocate(Size, Align); |
681 | } |
682 | template <typename T> T *Allocate(size_t Num = 1) const { |
683 | return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T))); |
684 | } |
685 | void Deallocate(void *Ptr) const {} |
686 | |
687 | /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList |
688 | /// pool. |
689 | DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) { |
690 | if (DeclListNode *Alloc = ListNodeFreeList) { |
691 | ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>(); |
692 | Alloc->D = ND; |
693 | Alloc->Rest = nullptr; |
694 | return Alloc; |
695 | } |
696 | return new (*this) DeclListNode(ND); |
697 | } |
698 | /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList |
699 | /// pool. |
700 | void DeallocateDeclListNode(DeclListNode *N) { |
701 | N->Rest = ListNodeFreeList; |
702 | ListNodeFreeList = N; |
703 | } |
704 | |
705 | /// Return the total amount of physical memory allocated for representing |
706 | /// AST nodes and type information. |
707 | size_t getASTAllocatedMemory() const { |
708 | return BumpAlloc.getTotalMemory(); |
709 | } |
710 | |
711 | /// Return the total memory used for various side tables. |
712 | size_t getSideTableAllocatedMemory() const; |
713 | |
714 | PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() { |
715 | return DiagAllocator; |
716 | } |
717 | |
718 | const TargetInfo &getTargetInfo() const { return *Target; } |
719 | const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } |
720 | |
721 | /// getIntTypeForBitwidth - |
722 | /// sets integer QualTy according to specified details: |
723 | /// bitwidth, signed/unsigned. |
724 | /// Returns empty type if there is no appropriate target types. |
725 | QualType getIntTypeForBitwidth(unsigned DestWidth, |
726 | unsigned Signed) const; |
727 | |
728 | /// getRealTypeForBitwidth - |
729 | /// sets floating point QualTy according to specified bitwidth. |
730 | /// Returns empty type if there is no appropriate target types. |
731 | QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const; |
732 | |
733 | bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const; |
734 | |
735 | const LangOptions& getLangOpts() const { return LangOpts; } |
736 | |
737 | // If this condition is false, typo correction must be performed eagerly |
738 | // rather than delayed in many places, as it makes use of dependent types. |
739 | // the condition is false for clang's C-only codepath, as it doesn't support |
740 | // dependent types yet. |
741 | bool isDependenceAllowed() const { |
742 | return LangOpts.CPlusPlus || LangOpts.RecoveryAST; |
743 | } |
744 | |
745 | const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; } |
746 | |
747 | const XRayFunctionFilter &getXRayFilter() const { |
748 | return *XRayFilter; |
749 | } |
750 | |
751 | const ProfileList &getProfileList() const { return *ProfList; } |
752 | |
753 | DiagnosticsEngine &getDiagnostics() const; |
754 | |
755 | FullSourceLoc getFullLoc(SourceLocation Loc) const { |
756 | return FullSourceLoc(Loc,SourceMgr); |
757 | } |
758 | |
759 | /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden |
760 | /// at compile time with `-fc++-abi=`. If this is not provided, we instead use |
761 | /// the default ABI set by the target. |
762 | TargetCXXABI::Kind getCXXABIKind() const; |
763 | |
764 | /// All comments in this translation unit. |
765 | RawCommentList Comments; |
766 | |
767 | /// True if comments are already loaded from ExternalASTSource. |
768 | mutable bool CommentsLoaded = false; |
769 | |
770 | /// Mapping from declaration to directly attached comment. |
771 | /// |
772 | /// Raw comments are owned by Comments list. This mapping is populated |
773 | /// lazily. |
774 | mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments; |
775 | |
776 | /// Mapping from canonical declaration to the first redeclaration in chain |
777 | /// that has a comment attached. |
778 | /// |
779 | /// Raw comments are owned by Comments list. This mapping is populated |
780 | /// lazily. |
781 | mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments; |
782 | |
783 | /// Keeps track of redeclaration chains that don't have any comment attached. |
784 | /// Mapping from canonical declaration to redeclaration chain that has no |
785 | /// comments attached to any redeclaration. Specifically it's mapping to |
786 | /// the last redeclaration we've checked. |
787 | /// |
788 | /// Shall not contain declarations that have comments attached to any |
789 | /// redeclaration in their chain. |
790 | mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains; |
791 | |
792 | /// Mapping from declarations to parsed comments attached to any |
793 | /// redeclaration. |
794 | mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments; |
795 | |
796 | /// Attaches \p Comment to \p OriginalD and to its redeclaration chain |
797 | /// and removes the redeclaration chain from the set of commentless chains. |
798 | /// |
799 | /// Don't do anything if a comment has already been attached to \p OriginalD |
800 | /// or its redeclaration chain. |
801 | void cacheRawCommentForDecl(const Decl &OriginalD, |
802 | const RawComment &Comment) const; |
803 | |
804 | /// \returns searches \p CommentsInFile for doc comment for \p D. |
805 | /// |
806 | /// \p RepresentativeLocForDecl is used as a location for searching doc |
807 | /// comments. \p CommentsInFile is a mapping offset -> comment of files in the |
808 | /// same file where \p RepresentativeLocForDecl is. |
809 | RawComment *getRawCommentForDeclNoCacheImpl( |
810 | const Decl *D, const SourceLocation RepresentativeLocForDecl, |
811 | const std::map<unsigned, RawComment *> &CommentsInFile) const; |
812 | |
813 | /// Return the documentation comment attached to a given declaration, |
814 | /// without looking into cache. |
815 | RawComment *getRawCommentForDeclNoCache(const Decl *D) const; |
816 | |
817 | public: |
818 | void addComment(const RawComment &RC); |
819 | |
820 | /// Return the documentation comment attached to a given declaration. |
821 | /// Returns nullptr if no comment is attached. |
822 | /// |
823 | /// \param OriginalDecl if not nullptr, is set to declaration AST node that |
824 | /// had the comment, if the comment we found comes from a redeclaration. |
825 | const RawComment * |
826 | getRawCommentForAnyRedecl(const Decl *D, |
827 | const Decl **OriginalDecl = nullptr) const; |
828 | |
829 | /// Searches existing comments for doc comments that should be attached to \p |
830 | /// Decls. If any doc comment is found, it is parsed. |
831 | /// |
832 | /// Requirement: All \p Decls are in the same file. |
833 | /// |
834 | /// If the last comment in the file is already attached we assume |
835 | /// there are not comments left to be attached to \p Decls. |
836 | void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, |
837 | const Preprocessor *PP); |
838 | |
839 | /// Return parsed documentation comment attached to a given declaration. |
840 | /// Returns nullptr if no comment is attached. |
841 | /// |
842 | /// \param PP the Preprocessor used with this TU. Could be nullptr if |
843 | /// preprocessor is not available. |
844 | comments::FullComment *getCommentForDecl(const Decl *D, |
845 | const Preprocessor *PP) const; |
846 | |
847 | /// Return parsed documentation comment attached to a given declaration. |
848 | /// Returns nullptr if no comment is attached. Does not look at any |
849 | /// redeclarations of the declaration. |
850 | comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const; |
851 | |
852 | comments::FullComment *cloneFullComment(comments::FullComment *FC, |
853 | const Decl *D) const; |
854 | |
855 | private: |
856 | mutable comments::CommandTraits CommentCommandTraits; |
857 | |
858 | /// Iterator that visits import declarations. |
859 | class import_iterator { |
860 | ImportDecl *Import = nullptr; |
861 | |
862 | public: |
863 | using value_type = ImportDecl *; |
864 | using reference = ImportDecl *; |
865 | using pointer = ImportDecl *; |
866 | using difference_type = int; |
867 | using iterator_category = std::forward_iterator_tag; |
868 | |
869 | import_iterator() = default; |
870 | explicit import_iterator(ImportDecl *Import) : Import(Import) {} |
871 | |
872 | reference operator*() const { return Import; } |
873 | pointer operator->() const { return Import; } |
874 | |
875 | import_iterator &operator++() { |
876 | Import = ASTContext::getNextLocalImport(Import); |
877 | return *this; |
878 | } |
879 | |
880 | import_iterator operator++(int) { |
881 | import_iterator Other(*this); |
882 | ++(*this); |
883 | return Other; |
884 | } |
885 | |
886 | friend bool operator==(import_iterator X, import_iterator Y) { |
887 | return X.Import == Y.Import; |
888 | } |
889 | |
890 | friend bool operator!=(import_iterator X, import_iterator Y) { |
891 | return X.Import != Y.Import; |
892 | } |
893 | }; |
894 | |
895 | public: |
896 | comments::CommandTraits &getCommentCommandTraits() const { |
897 | return CommentCommandTraits; |
898 | } |
899 | |
900 | /// Retrieve the attributes for the given declaration. |
901 | AttrVec& getDeclAttrs(const Decl *D); |
902 | |
903 | /// Erase the attributes corresponding to the given declaration. |
904 | void eraseDeclAttrs(const Decl *D); |
905 | |
906 | /// If this variable is an instantiated static data member of a |
907 | /// class template specialization, returns the templated static data member |
908 | /// from which it was instantiated. |
909 | // FIXME: Remove ? |
910 | MemberSpecializationInfo *getInstantiatedFromStaticDataMember( |
911 | const VarDecl *Var); |
912 | |
913 | /// Note that the static data member \p Inst is an instantiation of |
914 | /// the static data member template \p Tmpl of a class template. |
915 | void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, |
916 | TemplateSpecializationKind TSK, |
917 | SourceLocation PointOfInstantiation = SourceLocation()); |
918 | |
919 | TemplateOrSpecializationInfo |
920 | getTemplateOrSpecializationInfo(const VarDecl *Var); |
921 | |
922 | void setTemplateOrSpecializationInfo(VarDecl *Inst, |
923 | TemplateOrSpecializationInfo TSI); |
924 | |
925 | /// If the given using decl \p Inst is an instantiation of |
926 | /// another (possibly unresolved) using decl, return it. |
927 | NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst); |
928 | |
929 | /// Remember that the using decl \p Inst is an instantiation |
930 | /// of the using decl \p Pattern of a class template. |
931 | void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern); |
932 | |
933 | /// If the given using-enum decl \p Inst is an instantiation of |
934 | /// another using-enum decl, return it. |
935 | UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst); |
936 | |
937 | /// Remember that the using enum decl \p Inst is an instantiation |
938 | /// of the using enum decl \p Pattern of a class template. |
939 | void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, |
940 | UsingEnumDecl *Pattern); |
941 | |
942 | UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); |
943 | void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, |
944 | UsingShadowDecl *Pattern); |
945 | |
946 | FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); |
947 | |
948 | void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); |
949 | |
950 | // Access to the set of methods overridden by the given C++ method. |
951 | using overridden_cxx_method_iterator = CXXMethodVector::const_iterator; |
952 | overridden_cxx_method_iterator |
953 | overridden_methods_begin(const CXXMethodDecl *Method) const; |
954 | |
955 | overridden_cxx_method_iterator |
956 | overridden_methods_end(const CXXMethodDecl *Method) const; |
957 | |
958 | unsigned overridden_methods_size(const CXXMethodDecl *Method) const; |
959 | |
960 | using overridden_method_range = |
961 | llvm::iterator_range<overridden_cxx_method_iterator>; |
962 | |
963 | overridden_method_range overridden_methods(const CXXMethodDecl *Method) const; |
964 | |
965 | /// Note that the given C++ \p Method overrides the given \p |
966 | /// Overridden method. |
967 | void addOverriddenMethod(const CXXMethodDecl *Method, |
968 | const CXXMethodDecl *Overridden); |
969 | |
970 | /// Return C++ or ObjC overridden methods for the given \p Method. |
971 | /// |
972 | /// An ObjC method is considered to override any method in the class's |
973 | /// base classes, its protocols, or its categories' protocols, that has |
974 | /// the same selector and is of the same kind (class or instance). |
975 | /// A method in an implementation is not considered as overriding the same |
976 | /// method in the interface or its categories. |
977 | void getOverriddenMethods( |
978 | const NamedDecl *Method, |
979 | SmallVectorImpl<const NamedDecl *> &Overridden) const; |
980 | |
981 | /// Notify the AST context that a new import declaration has been |
982 | /// parsed or implicitly created within this translation unit. |
983 | void addedLocalImportDecl(ImportDecl *Import); |
984 | |
985 | static ImportDecl *getNextLocalImport(ImportDecl *Import) { |
986 | return Import->getNextLocalImport(); |
987 | } |
988 | |
989 | using import_range = llvm::iterator_range<import_iterator>; |
990 | |
991 | import_range local_imports() const { |
992 | return import_range(import_iterator(FirstLocalImport), import_iterator()); |
993 | } |
994 | |
995 | Decl *getPrimaryMergedDecl(Decl *D) { |
996 | Decl *Result = MergedDecls.lookup(D); |
997 | return Result ? Result : D; |
998 | } |
999 | void setPrimaryMergedDecl(Decl *D, Decl *Primary) { |
1000 | MergedDecls[D] = Primary; |
1001 | } |
1002 | |
1003 | /// Note that the definition \p ND has been merged into module \p M, |
1004 | /// and should be visible whenever \p M is visible. |
1005 | void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, |
1006 | bool NotifyListeners = true); |
1007 | |
1008 | /// Clean up the merged definition list. Call this if you might have |
1009 | /// added duplicates into the list. |
1010 | void deduplicateMergedDefinitonsFor(NamedDecl *ND); |
1011 | |
1012 | /// Get the additional modules in which the definition \p Def has |
1013 | /// been merged. |
1014 | ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def); |
1015 | |
1016 | /// Add a declaration to the list of declarations that are initialized |
1017 | /// for a module. This will typically be a global variable (with internal |
1018 | /// linkage) that runs module initializers, such as the iostream initializer, |
1019 | /// or an ImportDecl nominating another module that has initializers. |
1020 | void addModuleInitializer(Module *M, Decl *Init); |
1021 | |
1022 | void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs); |
1023 | |
1024 | /// Get the initializations to perform when importing a module, if any. |
1025 | ArrayRef<Decl*> getModuleInitializers(Module *M); |
1026 | |
1027 | TranslationUnitDecl *getTranslationUnitDecl() const { |
1028 | return TUDecl->getMostRecentDecl(); |
1029 | } |
1030 | void addTranslationUnitDecl() { |
1031 | assert(!TUDecl || TUKind == TU_Incremental)(static_cast <bool> (!TUDecl || TUKind == TU_Incremental ) ? void (0) : __assert_fail ("!TUDecl || TUKind == TU_Incremental" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 1031, __extension__ __PRETTY_FUNCTION__)); |
1032 | TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this); |
1033 | if (TraversalScope.empty() || TraversalScope.back() == TUDecl) |
1034 | TraversalScope = {NewTUDecl}; |
1035 | if (TUDecl) |
1036 | NewTUDecl->setPreviousDecl(TUDecl); |
1037 | TUDecl = NewTUDecl; |
1038 | } |
1039 | |
1040 | ExternCContextDecl *getExternCContextDecl() const; |
1041 | BuiltinTemplateDecl *getMakeIntegerSeqDecl() const; |
1042 | BuiltinTemplateDecl *getTypePackElementDecl() const; |
1043 | |
1044 | // Builtin Types. |
1045 | CanQualType VoidTy; |
1046 | CanQualType BoolTy; |
1047 | CanQualType CharTy; |
1048 | CanQualType WCharTy; // [C++ 3.9.1p5]. |
1049 | CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99. |
1050 | CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. |
1051 | CanQualType Char8Ty; // [C++20 proposal] |
1052 | CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. |
1053 | CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. |
1054 | CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; |
1055 | CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; |
1056 | CanQualType UnsignedLongLongTy, UnsignedInt128Ty; |
1057 | CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty; |
1058 | CanQualType ShortAccumTy, AccumTy, |
1059 | LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension |
1060 | CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy; |
1061 | CanQualType ShortFractTy, FractTy, LongFractTy; |
1062 | CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy; |
1063 | CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy; |
1064 | CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy, |
1065 | SatUnsignedLongAccumTy; |
1066 | CanQualType SatShortFractTy, SatFractTy, SatLongFractTy; |
1067 | CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy, |
1068 | SatUnsignedLongFractTy; |
1069 | CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON |
1070 | CanQualType BFloat16Ty; |
1071 | CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 |
1072 | CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy; |
1073 | CanQualType Float128ComplexTy; |
1074 | CanQualType VoidPtrTy, NullPtrTy; |
1075 | CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; |
1076 | CanQualType BuiltinFnTy; |
1077 | CanQualType PseudoObjectTy, ARCUnbridgedCastTy; |
1078 | CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; |
1079 | CanQualType ObjCBuiltinBoolTy; |
1080 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
1081 | CanQualType SingletonId; |
1082 | #include "clang/Basic/OpenCLImageTypes.def" |
1083 | CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy; |
1084 | CanQualType OCLQueueTy, OCLReserveIDTy; |
1085 | CanQualType IncompleteMatrixIdxTy; |
1086 | CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy; |
1087 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
1088 | CanQualType Id##Ty; |
1089 | #include "clang/Basic/OpenCLExtensionTypes.def" |
1090 | #define SVE_TYPE(Name, Id, SingletonId) \ |
1091 | CanQualType SingletonId; |
1092 | #include "clang/Basic/AArch64SVEACLETypes.def" |
1093 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
1094 | CanQualType Id##Ty; |
1095 | #include "clang/Basic/PPCTypes.def" |
1096 | #define RVV_TYPE(Name, Id, SingletonId) \ |
1097 | CanQualType SingletonId; |
1098 | #include "clang/Basic/RISCVVTypes.def" |
1099 | |
1100 | // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. |
1101 | mutable QualType AutoDeductTy; // Deduction against 'auto'. |
1102 | mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. |
1103 | |
1104 | // Decl used to help define __builtin_va_list for some targets. |
1105 | // The decl is built when constructing 'BuiltinVaListDecl'. |
1106 | mutable Decl *VaListTagDecl = nullptr; |
1107 | |
1108 | // Implicitly-declared type 'struct _GUID'. |
1109 | mutable TagDecl *MSGuidTagDecl = nullptr; |
1110 | |
1111 | /// Keep track of CUDA/HIP device-side variables ODR-used by host code. |
1112 | llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost; |
1113 | |
1114 | ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, |
1115 | SelectorTable &sels, Builtin::Context &builtins, |
1116 | TranslationUnitKind TUKind); |
1117 | ASTContext(const ASTContext &) = delete; |
1118 | ASTContext &operator=(const ASTContext &) = delete; |
1119 | ~ASTContext(); |
1120 | |
1121 | /// Attach an external AST source to the AST context. |
1122 | /// |
1123 | /// The external AST source provides the ability to load parts of |
1124 | /// the abstract syntax tree as needed from some external storage, |
1125 | /// e.g., a precompiled header. |
1126 | void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source); |
1127 | |
1128 | /// Retrieve a pointer to the external AST source associated |
1129 | /// with this AST context, if any. |
1130 | ExternalASTSource *getExternalSource() const { |
1131 | return ExternalSource.get(); |
1132 | } |
1133 | |
1134 | /// Attach an AST mutation listener to the AST context. |
1135 | /// |
1136 | /// The AST mutation listener provides the ability to track modifications to |
1137 | /// the abstract syntax tree entities committed after they were initially |
1138 | /// created. |
1139 | void setASTMutationListener(ASTMutationListener *Listener) { |
1140 | this->Listener = Listener; |
1141 | } |
1142 | |
1143 | /// Retrieve a pointer to the AST mutation listener associated |
1144 | /// with this AST context, if any. |
1145 | ASTMutationListener *getASTMutationListener() const { return Listener; } |
1146 | |
1147 | void PrintStats() const; |
1148 | const SmallVectorImpl<Type *>& getTypes() const { return Types; } |
1149 | |
1150 | BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, |
1151 | const IdentifierInfo *II) const; |
1152 | |
1153 | /// Create a new implicit TU-level CXXRecordDecl or RecordDecl |
1154 | /// declaration. |
1155 | RecordDecl *buildImplicitRecord(StringRef Name, |
1156 | RecordDecl::TagKind TK = TTK_Struct) const; |
1157 | |
1158 | /// Create a new implicit TU-level typedef declaration. |
1159 | TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const; |
1160 | |
1161 | /// Retrieve the declaration for the 128-bit signed integer type. |
1162 | TypedefDecl *getInt128Decl() const; |
1163 | |
1164 | /// Retrieve the declaration for the 128-bit unsigned integer type. |
1165 | TypedefDecl *getUInt128Decl() const; |
1166 | |
1167 | //===--------------------------------------------------------------------===// |
1168 | // Type Constructors |
1169 | //===--------------------------------------------------------------------===// |
1170 | |
1171 | private: |
1172 | /// Return a type with extended qualifiers. |
1173 | QualType getExtQualType(const Type *Base, Qualifiers Quals) const; |
1174 | |
1175 | QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; |
1176 | |
1177 | QualType getPipeType(QualType T, bool ReadOnly) const; |
1178 | |
1179 | public: |
1180 | /// Return the uniqued reference to the type for an address space |
1181 | /// qualified type with the specified type and address space. |
1182 | /// |
1183 | /// The resulting type has a union of the qualifiers from T and the address |
1184 | /// space. If T already has an address space specifier, it is silently |
1185 | /// replaced. |
1186 | QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const; |
1187 | |
1188 | /// Remove any existing address space on the type and returns the type |
1189 | /// with qualifiers intact (or that's the idea anyway) |
1190 | /// |
1191 | /// The return type should be T with all prior qualifiers minus the address |
1192 | /// space. |
1193 | QualType removeAddrSpaceQualType(QualType T) const; |
1194 | |
1195 | /// Apply Objective-C protocol qualifiers to the given type. |
1196 | /// \param allowOnPointerType specifies if we can apply protocol |
1197 | /// qualifiers on ObjCObjectPointerType. It can be set to true when |
1198 | /// constructing the canonical type of a Objective-C type parameter. |
1199 | QualType applyObjCProtocolQualifiers(QualType type, |
1200 | ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, |
1201 | bool allowOnPointerType = false) const; |
1202 | |
1203 | /// Return the uniqued reference to the type for an Objective-C |
1204 | /// gc-qualified type. |
1205 | /// |
1206 | /// The resulting type has a union of the qualifiers from T and the gc |
1207 | /// attribute. |
1208 | QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; |
1209 | |
1210 | /// Remove the existing address space on the type if it is a pointer size |
1211 | /// address space and return the type with qualifiers intact. |
1212 | QualType removePtrSizeAddrSpace(QualType T) const; |
1213 | |
1214 | /// Return the uniqued reference to the type for a \c restrict |
1215 | /// qualified type. |
1216 | /// |
1217 | /// The resulting type has a union of the qualifiers from \p T and |
1218 | /// \c restrict. |
1219 | QualType getRestrictType(QualType T) const { |
1220 | return T.withFastQualifiers(Qualifiers::Restrict); |
1221 | } |
1222 | |
1223 | /// Return the uniqued reference to the type for a \c volatile |
1224 | /// qualified type. |
1225 | /// |
1226 | /// The resulting type has a union of the qualifiers from \p T and |
1227 | /// \c volatile. |
1228 | QualType getVolatileType(QualType T) const { |
1229 | return T.withFastQualifiers(Qualifiers::Volatile); |
1230 | } |
1231 | |
1232 | /// Return the uniqued reference to the type for a \c const |
1233 | /// qualified type. |
1234 | /// |
1235 | /// The resulting type has a union of the qualifiers from \p T and \c const. |
1236 | /// |
1237 | /// It can be reasonably expected that this will always be equivalent to |
1238 | /// calling T.withConst(). |
1239 | QualType getConstType(QualType T) const { return T.withConst(); } |
1240 | |
1241 | /// Change the ExtInfo on a function type. |
1242 | const FunctionType *adjustFunctionType(const FunctionType *Fn, |
1243 | FunctionType::ExtInfo EInfo); |
1244 | |
1245 | /// Adjust the given function result type. |
1246 | CanQualType getCanonicalFunctionResultType(QualType ResultType) const; |
1247 | |
1248 | /// Change the result type of a function type once it is deduced. |
1249 | void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType); |
1250 | |
1251 | /// Get a function type and produce the equivalent function type with the |
1252 | /// specified exception specification. Type sugar that can be present on a |
1253 | /// declaration of a function with an exception specification is permitted |
1254 | /// and preserved. Other type sugar (for instance, typedefs) is not. |
1255 | QualType getFunctionTypeWithExceptionSpec( |
1256 | QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI); |
1257 | |
1258 | /// Determine whether two function types are the same, ignoring |
1259 | /// exception specifications in cases where they're part of the type. |
1260 | bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U); |
1261 | |
1262 | /// Change the exception specification on a function once it is |
1263 | /// delay-parsed, instantiated, or computed. |
1264 | void adjustExceptionSpec(FunctionDecl *FD, |
1265 | const FunctionProtoType::ExceptionSpecInfo &ESI, |
1266 | bool AsWritten = false); |
1267 | |
1268 | /// Get a function type and produce the equivalent function type where |
1269 | /// pointer size address spaces in the return type and parameter tyeps are |
1270 | /// replaced with the default address space. |
1271 | QualType getFunctionTypeWithoutPtrSizes(QualType T); |
1272 | |
1273 | /// Determine whether two function types are the same, ignoring pointer sizes |
1274 | /// in the return type and parameter types. |
1275 | bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U); |
1276 | |
1277 | /// Return the uniqued reference to the type for a complex |
1278 | /// number with the specified element type. |
1279 | QualType getComplexType(QualType T) const; |
1280 | CanQualType getComplexType(CanQualType T) const { |
1281 | return CanQualType::CreateUnsafe(getComplexType((QualType) T)); |
1282 | } |
1283 | |
1284 | /// Return the uniqued reference to the type for a pointer to |
1285 | /// the specified type. |
1286 | QualType getPointerType(QualType T) const; |
1287 | CanQualType getPointerType(CanQualType T) const { |
1288 | return CanQualType::CreateUnsafe(getPointerType((QualType) T)); |
1289 | } |
1290 | |
1291 | /// Return the uniqued reference to a type adjusted from the original |
1292 | /// type to a new type. |
1293 | QualType getAdjustedType(QualType Orig, QualType New) const; |
1294 | CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const { |
1295 | return CanQualType::CreateUnsafe( |
1296 | getAdjustedType((QualType)Orig, (QualType)New)); |
1297 | } |
1298 | |
1299 | /// Return the uniqued reference to the decayed version of the given |
1300 | /// type. Can only be called on array and function types which decay to |
1301 | /// pointer types. |
1302 | QualType getDecayedType(QualType T) const; |
1303 | CanQualType getDecayedType(CanQualType T) const { |
1304 | return CanQualType::CreateUnsafe(getDecayedType((QualType) T)); |
1305 | } |
1306 | |
1307 | /// Return the uniqued reference to the atomic type for the specified |
1308 | /// type. |
1309 | QualType getAtomicType(QualType T) const; |
1310 | |
1311 | /// Return the uniqued reference to the type for a block of the |
1312 | /// specified type. |
1313 | QualType getBlockPointerType(QualType T) const; |
1314 | |
1315 | /// Gets the struct used to keep track of the descriptor for pointer to |
1316 | /// blocks. |
1317 | QualType getBlockDescriptorType() const; |
1318 | |
1319 | /// Return a read_only pipe type for the specified type. |
1320 | QualType getReadPipeType(QualType T) const; |
1321 | |
1322 | /// Return a write_only pipe type for the specified type. |
1323 | QualType getWritePipeType(QualType T) const; |
1324 | |
1325 | /// Return an extended integer type with the specified signedness and bit |
1326 | /// count. |
1327 | QualType getExtIntType(bool Unsigned, unsigned NumBits) const; |
1328 | |
1329 | /// Return a dependent extended integer type with the specified signedness and |
1330 | /// bit count. |
1331 | QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const; |
1332 | |
1333 | /// Gets the struct used to keep track of the extended descriptor for |
1334 | /// pointer to blocks. |
1335 | QualType getBlockDescriptorExtendedType() const; |
1336 | |
1337 | /// Map an AST Type to an OpenCLTypeKind enum value. |
1338 | OpenCLTypeKind getOpenCLTypeKind(const Type *T) const; |
1339 | |
1340 | /// Get address space for OpenCL type. |
1341 | LangAS getOpenCLTypeAddrSpace(const Type *T) const; |
1342 | |
1343 | void setcudaConfigureCallDecl(FunctionDecl *FD) { |
1344 | cudaConfigureCallDecl = FD; |
1345 | } |
1346 | |
1347 | FunctionDecl *getcudaConfigureCallDecl() { |
1348 | return cudaConfigureCallDecl; |
1349 | } |
1350 | |
1351 | /// Returns true iff we need copy/dispose helpers for the given type. |
1352 | bool BlockRequiresCopying(QualType Ty, const VarDecl *D); |
1353 | |
1354 | /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout |
1355 | /// is set to false in this case. If HasByrefExtendedLayout returns true, |
1356 | /// byref variable has extended lifetime. |
1357 | bool getByrefLifetime(QualType Ty, |
1358 | Qualifiers::ObjCLifetime &Lifetime, |
1359 | bool &HasByrefExtendedLayout) const; |
1360 | |
1361 | /// Return the uniqued reference to the type for an lvalue reference |
1362 | /// to the specified type. |
1363 | QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) |
1364 | const; |
1365 | |
1366 | /// Return the uniqued reference to the type for an rvalue reference |
1367 | /// to the specified type. |
1368 | QualType getRValueReferenceType(QualType T) const; |
1369 | |
1370 | /// Return the uniqued reference to the type for a member pointer to |
1371 | /// the specified type in the specified class. |
1372 | /// |
1373 | /// The class \p Cls is a \c Type because it could be a dependent name. |
1374 | QualType getMemberPointerType(QualType T, const Type *Cls) const; |
1375 | |
1376 | /// Return a non-unique reference to the type for a variable array of |
1377 | /// the specified element type. |
1378 | QualType getVariableArrayType(QualType EltTy, Expr *NumElts, |
1379 | ArrayType::ArraySizeModifier ASM, |
1380 | unsigned IndexTypeQuals, |
1381 | SourceRange Brackets) const; |
1382 | |
1383 | /// Return a non-unique reference to the type for a dependently-sized |
1384 | /// array of the specified element type. |
1385 | /// |
1386 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1387 | /// point. |
1388 | QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, |
1389 | ArrayType::ArraySizeModifier ASM, |
1390 | unsigned IndexTypeQuals, |
1391 | SourceRange Brackets) const; |
1392 | |
1393 | /// Return a unique reference to the type for an incomplete array of |
1394 | /// the specified element type. |
1395 | QualType getIncompleteArrayType(QualType EltTy, |
1396 | ArrayType::ArraySizeModifier ASM, |
1397 | unsigned IndexTypeQuals) const; |
1398 | |
1399 | /// Return the unique reference to the type for a constant array of |
1400 | /// the specified element type. |
1401 | QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, |
1402 | const Expr *SizeExpr, |
1403 | ArrayType::ArraySizeModifier ASM, |
1404 | unsigned IndexTypeQuals) const; |
1405 | |
1406 | /// Return a type for a constant array for a string literal of the |
1407 | /// specified element type and length. |
1408 | QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const; |
1409 | |
1410 | /// Returns a vla type where known sizes are replaced with [*]. |
1411 | QualType getVariableArrayDecayedType(QualType Ty) const; |
1412 | |
1413 | // Convenience struct to return information about a builtin vector type. |
1414 | struct BuiltinVectorTypeInfo { |
1415 | QualType ElementType; |
1416 | llvm::ElementCount EC; |
1417 | unsigned NumVectors; |
1418 | BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC, |
1419 | unsigned NumVectors) |
1420 | : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {} |
1421 | }; |
1422 | |
1423 | /// Returns the element type, element count and number of vectors |
1424 | /// (in case of tuple) for a builtin vector type. |
1425 | BuiltinVectorTypeInfo |
1426 | getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const; |
1427 | |
1428 | /// Return the unique reference to a scalable vector type of the specified |
1429 | /// element type and scalable number of elements. |
1430 | /// |
1431 | /// \pre \p EltTy must be a built-in type. |
1432 | QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const; |
1433 | |
1434 | /// Return the unique reference to a vector type of the specified |
1435 | /// element type and size. |
1436 | /// |
1437 | /// \pre \p VectorType must be a built-in type. |
1438 | QualType getVectorType(QualType VectorType, unsigned NumElts, |
1439 | VectorType::VectorKind VecKind) const; |
1440 | /// Return the unique reference to the type for a dependently sized vector of |
1441 | /// the specified element type. |
1442 | QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, |
1443 | SourceLocation AttrLoc, |
1444 | VectorType::VectorKind VecKind) const; |
1445 | |
1446 | /// Return the unique reference to an extended vector type |
1447 | /// of the specified element type and size. |
1448 | /// |
1449 | /// \pre \p VectorType must be a built-in type. |
1450 | QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; |
1451 | |
1452 | /// \pre Return a non-unique reference to the type for a dependently-sized |
1453 | /// vector of the specified element type. |
1454 | /// |
1455 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1456 | /// point. |
1457 | QualType getDependentSizedExtVectorType(QualType VectorType, |
1458 | Expr *SizeExpr, |
1459 | SourceLocation AttrLoc) const; |
1460 | |
1461 | /// Return the unique reference to the matrix type of the specified element |
1462 | /// type and size |
1463 | /// |
1464 | /// \pre \p ElementType must be a valid matrix element type (see |
1465 | /// MatrixType::isValidElementType). |
1466 | QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, |
1467 | unsigned NumColumns) const; |
1468 | |
1469 | /// Return the unique reference to the matrix type of the specified element |
1470 | /// type and size |
1471 | QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, |
1472 | Expr *ColumnExpr, |
1473 | SourceLocation AttrLoc) const; |
1474 | |
1475 | QualType getDependentAddressSpaceType(QualType PointeeType, |
1476 | Expr *AddrSpaceExpr, |
1477 | SourceLocation AttrLoc) const; |
1478 | |
1479 | /// Return a K&R style C function type like 'int()'. |
1480 | QualType getFunctionNoProtoType(QualType ResultTy, |
1481 | const FunctionType::ExtInfo &Info) const; |
1482 | |
1483 | QualType getFunctionNoProtoType(QualType ResultTy) const { |
1484 | return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); |
1485 | } |
1486 | |
1487 | /// Return a normal function type with a typed argument list. |
1488 | QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args, |
1489 | const FunctionProtoType::ExtProtoInfo &EPI) const { |
1490 | return getFunctionTypeInternal(ResultTy, Args, EPI, false); |
1491 | } |
1492 | |
1493 | QualType adjustStringLiteralBaseType(QualType StrLTy) const; |
1494 | |
1495 | private: |
1496 | /// Return a normal function type with a typed argument list. |
1497 | QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args, |
1498 | const FunctionProtoType::ExtProtoInfo &EPI, |
1499 | bool OnlyWantCanonical) const; |
1500 | |
1501 | public: |
1502 | /// Return the unique reference to the type for the specified type |
1503 | /// declaration. |
1504 | QualType getTypeDeclType(const TypeDecl *Decl, |
1505 | const TypeDecl *PrevDecl = nullptr) const { |
1506 | assert(Decl && "Passed null for Decl param")(static_cast <bool> (Decl && "Passed null for Decl param" ) ? void (0) : __assert_fail ("Decl && \"Passed null for Decl param\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 1506, __extension__ __PRETTY_FUNCTION__)); |
1507 | if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); |
1508 | |
1509 | if (PrevDecl) { |
1510 | assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")(static_cast <bool> (PrevDecl->TypeForDecl && "previous decl has no TypeForDecl") ? void (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 1510, __extension__ __PRETTY_FUNCTION__)); |
1511 | Decl->TypeForDecl = PrevDecl->TypeForDecl; |
1512 | return QualType(PrevDecl->TypeForDecl, 0); |
1513 | } |
1514 | |
1515 | return getTypeDeclTypeSlow(Decl); |
1516 | } |
1517 | |
1518 | /// Return the unique reference to the type for the specified |
1519 | /// typedef-name decl. |
1520 | QualType getTypedefType(const TypedefNameDecl *Decl, |
1521 | QualType Underlying = QualType()) const; |
1522 | |
1523 | QualType getRecordType(const RecordDecl *Decl) const; |
1524 | |
1525 | QualType getEnumType(const EnumDecl *Decl) const; |
1526 | |
1527 | QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; |
1528 | |
1529 | QualType getAttributedType(attr::Kind attrKind, |
1530 | QualType modifiedType, |
1531 | QualType equivalentType); |
1532 | |
1533 | QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, |
1534 | QualType Replacement) const; |
1535 | QualType getSubstTemplateTypeParmPackType( |
1536 | const TemplateTypeParmType *Replaced, |
1537 | const TemplateArgument &ArgPack); |
1538 | |
1539 | QualType |
1540 | getTemplateTypeParmType(unsigned Depth, unsigned Index, |
1541 | bool ParameterPack, |
1542 | TemplateTypeParmDecl *ParmDecl = nullptr) const; |
1543 | |
1544 | QualType getTemplateSpecializationType(TemplateName T, |
1545 | ArrayRef<TemplateArgument> Args, |
1546 | QualType Canon = QualType()) const; |
1547 | |
1548 | QualType |
1549 | getCanonicalTemplateSpecializationType(TemplateName T, |
1550 | ArrayRef<TemplateArgument> Args) const; |
1551 | |
1552 | QualType getTemplateSpecializationType(TemplateName T, |
1553 | const TemplateArgumentListInfo &Args, |
1554 | QualType Canon = QualType()) const; |
1555 | |
1556 | TypeSourceInfo * |
1557 | getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, |
1558 | const TemplateArgumentListInfo &Args, |
1559 | QualType Canon = QualType()) const; |
1560 | |
1561 | QualType getParenType(QualType NamedType) const; |
1562 | |
1563 | QualType getMacroQualifiedType(QualType UnderlyingTy, |
1564 | const IdentifierInfo *MacroII) const; |
1565 | |
1566 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
1567 | NestedNameSpecifier *NNS, QualType NamedType, |
1568 | TagDecl *OwnedTagDecl = nullptr) const; |
1569 | QualType getDependentNameType(ElaboratedTypeKeyword Keyword, |
1570 | NestedNameSpecifier *NNS, |
1571 | const IdentifierInfo *Name, |
1572 | QualType Canon = QualType()) const; |
1573 | |
1574 | QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
1575 | NestedNameSpecifier *NNS, |
1576 | const IdentifierInfo *Name, |
1577 | const TemplateArgumentListInfo &Args) const; |
1578 | QualType getDependentTemplateSpecializationType( |
1579 | ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
1580 | const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const; |
1581 | |
1582 | TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl); |
1583 | |
1584 | /// Get a template argument list with one argument per template parameter |
1585 | /// in a template parameter list, such as for the injected class name of |
1586 | /// a class template. |
1587 | void getInjectedTemplateArgs(const TemplateParameterList *Params, |
1588 | SmallVectorImpl<TemplateArgument> &Args); |
1589 | |
1590 | /// Form a pack expansion type with the given pattern. |
1591 | /// \param NumExpansions The number of expansions for the pack, if known. |
1592 | /// \param ExpectPackInType If \c false, we should not expect \p Pattern to |
1593 | /// contain an unexpanded pack. This only makes sense if the pack |
1594 | /// expansion is used in a context where the arity is inferred from |
1595 | /// elsewhere, such as if the pattern contains a placeholder type or |
1596 | /// if this is the canonical type of another pack expansion type. |
1597 | QualType getPackExpansionType(QualType Pattern, |
1598 | Optional<unsigned> NumExpansions, |
1599 | bool ExpectPackInType = true); |
1600 | |
1601 | QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, |
1602 | ObjCInterfaceDecl *PrevDecl = nullptr) const; |
1603 | |
1604 | /// Legacy interface: cannot provide type arguments or __kindof. |
1605 | QualType getObjCObjectType(QualType Base, |
1606 | ObjCProtocolDecl * const *Protocols, |
1607 | unsigned NumProtocols) const; |
1608 | |
1609 | QualType getObjCObjectType(QualType Base, |
1610 | ArrayRef<QualType> typeArgs, |
1611 | ArrayRef<ObjCProtocolDecl *> protocols, |
1612 | bool isKindOf) const; |
1613 | |
1614 | QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
1615 | ArrayRef<ObjCProtocolDecl *> protocols) const; |
1616 | void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, |
1617 | ObjCTypeParamDecl *New) const; |
1618 | |
1619 | bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl); |
1620 | |
1621 | /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in |
1622 | /// QT's qualified-id protocol list adopt all protocols in IDecl's list |
1623 | /// of protocols. |
1624 | bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, |
1625 | ObjCInterfaceDecl *IDecl); |
1626 | |
1627 | /// Return a ObjCObjectPointerType type for the given ObjCObjectType. |
1628 | QualType getObjCObjectPointerType(QualType OIT) const; |
1629 | |
1630 | /// GCC extension. |
1631 | QualType getTypeOfExprType(Expr *e) const; |
1632 | QualType getTypeOfType(QualType t) const; |
1633 | |
1634 | QualType getReferenceQualifiedType(const Expr *e) const; |
1635 | |
1636 | /// C++11 decltype. |
1637 | QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; |
1638 | |
1639 | /// Unary type transforms |
1640 | QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, |
1641 | UnaryTransformType::UTTKind UKind) const; |
1642 | |
1643 | /// C++11 deduced auto type. |
1644 | QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, |
1645 | bool IsDependent, bool IsPack = false, |
1646 | ConceptDecl *TypeConstraintConcept = nullptr, |
1647 | ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const; |
1648 | |
1649 | /// C++11 deduction pattern for 'auto' type. |
1650 | QualType getAutoDeductType() const; |
1651 | |
1652 | /// C++11 deduction pattern for 'auto &&' type. |
1653 | QualType getAutoRRefDeductType() const; |
1654 | |
1655 | /// C++17 deduced class template specialization type. |
1656 | QualType getDeducedTemplateSpecializationType(TemplateName Template, |
1657 | QualType DeducedType, |
1658 | bool IsDependent) const; |
1659 | |
1660 | /// Return the unique reference to the type for the specified TagDecl |
1661 | /// (struct/union/class/enum) decl. |
1662 | QualType getTagDeclType(const TagDecl *Decl) const; |
1663 | |
1664 | /// Return the unique type for "size_t" (C99 7.17), defined in |
1665 | /// <stddef.h>. |
1666 | /// |
1667 | /// The sizeof operator requires this (C99 6.5.3.4p4). |
1668 | CanQualType getSizeType() const; |
1669 | |
1670 | /// Return the unique signed counterpart of |
1671 | /// the integer type corresponding to size_t. |
1672 | CanQualType getSignedSizeType() const; |
1673 | |
1674 | /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in |
1675 | /// <stdint.h>. |
1676 | CanQualType getIntMaxType() const; |
1677 | |
1678 | /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in |
1679 | /// <stdint.h>. |
1680 | CanQualType getUIntMaxType() const; |
1681 | |
1682 | /// Return the unique wchar_t type available in C++ (and available as |
1683 | /// __wchar_t as a Microsoft extension). |
1684 | QualType getWCharType() const { return WCharTy; } |
1685 | |
1686 | /// Return the type of wide characters. In C++, this returns the |
1687 | /// unique wchar_t type. In C99, this returns a type compatible with the type |
1688 | /// defined in <stddef.h> as defined by the target. |
1689 | QualType getWideCharType() const { return WideCharTy; } |
1690 | |
1691 | /// Return the type of "signed wchar_t". |
1692 | /// |
1693 | /// Used when in C++, as a GCC extension. |
1694 | QualType getSignedWCharType() const; |
1695 | |
1696 | /// Return the type of "unsigned wchar_t". |
1697 | /// |
1698 | /// Used when in C++, as a GCC extension. |
1699 | QualType getUnsignedWCharType() const; |
1700 | |
1701 | /// In C99, this returns a type compatible with the type |
1702 | /// defined in <stddef.h> as defined by the target. |
1703 | QualType getWIntType() const { return WIntTy; } |
1704 | |
1705 | /// Return a type compatible with "intptr_t" (C99 7.18.1.4), |
1706 | /// as defined by the target. |
1707 | QualType getIntPtrType() const; |
1708 | |
1709 | /// Return a type compatible with "uintptr_t" (C99 7.18.1.4), |
1710 | /// as defined by the target. |
1711 | QualType getUIntPtrType() const; |
1712 | |
1713 | /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in |
1714 | /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). |
1715 | QualType getPointerDiffType() const; |
1716 | |
1717 | /// Return the unique unsigned counterpart of "ptrdiff_t" |
1718 | /// integer type. The standard (C11 7.21.6.1p7) refers to this type |
1719 | /// in the definition of %tu format specifier. |
1720 | QualType getUnsignedPointerDiffType() const; |
1721 | |
1722 | /// Return the unique type for "pid_t" defined in |
1723 | /// <sys/types.h>. We need this to compute the correct type for vfork(). |
1724 | QualType getProcessIDType() const; |
1725 | |
1726 | /// Return the C structure type used to represent constant CFStrings. |
1727 | QualType getCFConstantStringType() const; |
1728 | |
1729 | /// Returns the C struct type for objc_super |
1730 | QualType getObjCSuperType() const; |
1731 | void setObjCSuperType(QualType ST) { ObjCSuperType = ST; } |
1732 | |
1733 | /// Get the structure type used to representation CFStrings, or NULL |
1734 | /// if it hasn't yet been built. |
1735 | QualType getRawCFConstantStringType() const { |
1736 | if (CFConstantStringTypeDecl) |
1737 | return getTypedefType(CFConstantStringTypeDecl); |
1738 | return QualType(); |
1739 | } |
1740 | void setCFConstantStringType(QualType T); |
1741 | TypedefDecl *getCFConstantStringDecl() const; |
1742 | RecordDecl *getCFConstantStringTagDecl() const; |
1743 | |
1744 | // This setter/getter represents the ObjC type for an NSConstantString. |
1745 | void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); |
1746 | QualType getObjCConstantStringInterface() const { |
1747 | return ObjCConstantStringType; |
1748 | } |
1749 | |
1750 | QualType getObjCNSStringType() const { |
1751 | return ObjCNSStringType; |
1752 | } |
1753 | |
1754 | void setObjCNSStringType(QualType T) { |
1755 | ObjCNSStringType = T; |
1756 | } |
1757 | |
1758 | /// Retrieve the type that \c id has been defined to, which may be |
1759 | /// different from the built-in \c id if \c id has been typedef'd. |
1760 | QualType getObjCIdRedefinitionType() const { |
1761 | if (ObjCIdRedefinitionType.isNull()) |
1762 | return getObjCIdType(); |
1763 | return ObjCIdRedefinitionType; |
1764 | } |
1765 | |
1766 | /// Set the user-written type that redefines \c id. |
1767 | void setObjCIdRedefinitionType(QualType RedefType) { |
1768 | ObjCIdRedefinitionType = RedefType; |
1769 | } |
1770 | |
1771 | /// Retrieve the type that \c Class has been defined to, which may be |
1772 | /// different from the built-in \c Class if \c Class has been typedef'd. |
1773 | QualType getObjCClassRedefinitionType() const { |
1774 | if (ObjCClassRedefinitionType.isNull()) |
1775 | return getObjCClassType(); |
1776 | return ObjCClassRedefinitionType; |
1777 | } |
1778 | |
1779 | /// Set the user-written type that redefines 'SEL'. |
1780 | void setObjCClassRedefinitionType(QualType RedefType) { |
1781 | ObjCClassRedefinitionType = RedefType; |
1782 | } |
1783 | |
1784 | /// Retrieve the type that 'SEL' has been defined to, which may be |
1785 | /// different from the built-in 'SEL' if 'SEL' has been typedef'd. |
1786 | QualType getObjCSelRedefinitionType() const { |
1787 | if (ObjCSelRedefinitionType.isNull()) |
1788 | return getObjCSelType(); |
1789 | return ObjCSelRedefinitionType; |
1790 | } |
1791 | |
1792 | /// Set the user-written type that redefines 'SEL'. |
1793 | void setObjCSelRedefinitionType(QualType RedefType) { |
1794 | ObjCSelRedefinitionType = RedefType; |
1795 | } |
1796 | |
1797 | /// Retrieve the identifier 'NSObject'. |
1798 | IdentifierInfo *getNSObjectName() const { |
1799 | if (!NSObjectName) { |
1800 | NSObjectName = &Idents.get("NSObject"); |
1801 | } |
1802 | |
1803 | return NSObjectName; |
1804 | } |
1805 | |
1806 | /// Retrieve the identifier 'NSCopying'. |
1807 | IdentifierInfo *getNSCopyingName() { |
1808 | if (!NSCopyingName) { |
1809 | NSCopyingName = &Idents.get("NSCopying"); |
1810 | } |
1811 | |
1812 | return NSCopyingName; |
1813 | } |
1814 | |
1815 | CanQualType getNSUIntegerType() const; |
1816 | |
1817 | CanQualType getNSIntegerType() const; |
1818 | |
1819 | /// Retrieve the identifier 'bool'. |
1820 | IdentifierInfo *getBoolName() const { |
1821 | if (!BoolName) |
1822 | BoolName = &Idents.get("bool"); |
1823 | return BoolName; |
1824 | } |
1825 | |
1826 | IdentifierInfo *getMakeIntegerSeqName() const { |
1827 | if (!MakeIntegerSeqName) |
1828 | MakeIntegerSeqName = &Idents.get("__make_integer_seq"); |
1829 | return MakeIntegerSeqName; |
1830 | } |
1831 | |
1832 | IdentifierInfo *getTypePackElementName() const { |
1833 | if (!TypePackElementName) |
1834 | TypePackElementName = &Idents.get("__type_pack_element"); |
1835 | return TypePackElementName; |
1836 | } |
1837 | |
1838 | /// Retrieve the Objective-C "instancetype" type, if already known; |
1839 | /// otherwise, returns a NULL type; |
1840 | QualType getObjCInstanceType() { |
1841 | return getTypeDeclType(getObjCInstanceTypeDecl()); |
1842 | } |
1843 | |
1844 | /// Retrieve the typedef declaration corresponding to the Objective-C |
1845 | /// "instancetype" type. |
1846 | TypedefDecl *getObjCInstanceTypeDecl(); |
1847 | |
1848 | /// Set the type for the C FILE type. |
1849 | void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } |
1850 | |
1851 | /// Retrieve the C FILE type. |
1852 | QualType getFILEType() const { |
1853 | if (FILEDecl) |
1854 | return getTypeDeclType(FILEDecl); |
1855 | return QualType(); |
1856 | } |
1857 | |
1858 | /// Set the type for the C jmp_buf type. |
1859 | void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { |
1860 | this->jmp_bufDecl = jmp_bufDecl; |
1861 | } |
1862 | |
1863 | /// Retrieve the C jmp_buf type. |
1864 | QualType getjmp_bufType() const { |
1865 | if (jmp_bufDecl) |
1866 | return getTypeDeclType(jmp_bufDecl); |
1867 | return QualType(); |
1868 | } |
1869 | |
1870 | /// Set the type for the C sigjmp_buf type. |
1871 | void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { |
1872 | this->sigjmp_bufDecl = sigjmp_bufDecl; |
1873 | } |
1874 | |
1875 | /// Retrieve the C sigjmp_buf type. |
1876 | QualType getsigjmp_bufType() const { |
1877 | if (sigjmp_bufDecl) |
1878 | return getTypeDeclType(sigjmp_bufDecl); |
1879 | return QualType(); |
1880 | } |
1881 | |
1882 | /// Set the type for the C ucontext_t type. |
1883 | void setucontext_tDecl(TypeDecl *ucontext_tDecl) { |
1884 | this->ucontext_tDecl = ucontext_tDecl; |
1885 | } |
1886 | |
1887 | /// Retrieve the C ucontext_t type. |
1888 | QualType getucontext_tType() const { |
1889 | if (ucontext_tDecl) |
1890 | return getTypeDeclType(ucontext_tDecl); |
1891 | return QualType(); |
1892 | } |
1893 | |
1894 | /// The result type of logical operations, '<', '>', '!=', etc. |
1895 | QualType getLogicalOperationType() const { |
1896 | return getLangOpts().CPlusPlus ? BoolTy : IntTy; |
1897 | } |
1898 | |
1899 | /// Emit the Objective-CC type encoding for the given type \p T into |
1900 | /// \p S. |
1901 | /// |
1902 | /// If \p Field is specified then record field names are also encoded. |
1903 | void getObjCEncodingForType(QualType T, std::string &S, |
1904 | const FieldDecl *Field=nullptr, |
1905 | QualType *NotEncodedT=nullptr) const; |
1906 | |
1907 | /// Emit the Objective-C property type encoding for the given |
1908 | /// type \p T into \p S. |
1909 | void getObjCEncodingForPropertyType(QualType T, std::string &S) const; |
1910 | |
1911 | void getLegacyIntegralTypeEncoding(QualType &t) const; |
1912 | |
1913 | /// Put the string version of the type qualifiers \p QT into \p S. |
1914 | void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, |
1915 | std::string &S) const; |
1916 | |
1917 | /// Emit the encoded type for the function \p Decl into \p S. |
1918 | /// |
1919 | /// This is in the same format as Objective-C method encodings. |
1920 | /// |
1921 | /// \returns true if an error occurred (e.g., because one of the parameter |
1922 | /// types is incomplete), false otherwise. |
1923 | std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const; |
1924 | |
1925 | /// Emit the encoded type for the method declaration \p Decl into |
1926 | /// \p S. |
1927 | std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, |
1928 | bool Extended = false) const; |
1929 | |
1930 | /// Return the encoded type for this block declaration. |
1931 | std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const; |
1932 | |
1933 | /// getObjCEncodingForPropertyDecl - Return the encoded type for |
1934 | /// this method declaration. If non-NULL, Container must be either |
1935 | /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should |
1936 | /// only be NULL when getting encodings for protocol properties. |
1937 | std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, |
1938 | const Decl *Container) const; |
1939 | |
1940 | bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, |
1941 | ObjCProtocolDecl *rProto) const; |
1942 | |
1943 | ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl( |
1944 | const ObjCPropertyDecl *PD, |
1945 | const Decl *Container) const; |
1946 | |
1947 | /// Return the size of type \p T for Objective-C encoding purpose, |
1948 | /// in characters. |
1949 | CharUnits getObjCEncodingTypeSize(QualType T) const; |
1950 | |
1951 | /// Retrieve the typedef corresponding to the predefined \c id type |
1952 | /// in Objective-C. |
1953 | TypedefDecl *getObjCIdDecl() const; |
1954 | |
1955 | /// Represents the Objective-CC \c id type. |
1956 | /// |
1957 | /// This is set up lazily, by Sema. \c id is always a (typedef for a) |
1958 | /// pointer type, a pointer to a struct. |
1959 | QualType getObjCIdType() const { |
1960 | return getTypeDeclType(getObjCIdDecl()); |
1961 | } |
1962 | |
1963 | /// Retrieve the typedef corresponding to the predefined 'SEL' type |
1964 | /// in Objective-C. |
1965 | TypedefDecl *getObjCSelDecl() const; |
1966 | |
1967 | /// Retrieve the type that corresponds to the predefined Objective-C |
1968 | /// 'SEL' type. |
1969 | QualType getObjCSelType() const { |
1970 | return getTypeDeclType(getObjCSelDecl()); |
1971 | } |
1972 | |
1973 | /// Retrieve the typedef declaration corresponding to the predefined |
1974 | /// Objective-C 'Class' type. |
1975 | TypedefDecl *getObjCClassDecl() const; |
1976 | |
1977 | /// Represents the Objective-C \c Class type. |
1978 | /// |
1979 | /// This is set up lazily, by Sema. \c Class is always a (typedef for a) |
1980 | /// pointer type, a pointer to a struct. |
1981 | QualType getObjCClassType() const { |
1982 | return getTypeDeclType(getObjCClassDecl()); |
1983 | } |
1984 | |
1985 | /// Retrieve the Objective-C class declaration corresponding to |
1986 | /// the predefined \c Protocol class. |
1987 | ObjCInterfaceDecl *getObjCProtocolDecl() const; |
1988 | |
1989 | /// Retrieve declaration of 'BOOL' typedef |
1990 | TypedefDecl *getBOOLDecl() const { |
1991 | return BOOLDecl; |
1992 | } |
1993 | |
1994 | /// Save declaration of 'BOOL' typedef |
1995 | void setBOOLDecl(TypedefDecl *TD) { |
1996 | BOOLDecl = TD; |
1997 | } |
1998 | |
1999 | /// type of 'BOOL' type. |
2000 | QualType getBOOLType() const { |
2001 | return getTypeDeclType(getBOOLDecl()); |
2002 | } |
2003 | |
2004 | /// Retrieve the type of the Objective-C \c Protocol class. |
2005 | QualType getObjCProtoType() const { |
2006 | return getObjCInterfaceType(getObjCProtocolDecl()); |
2007 | } |
2008 | |
2009 | /// Retrieve the C type declaration corresponding to the predefined |
2010 | /// \c __builtin_va_list type. |
2011 | TypedefDecl *getBuiltinVaListDecl() const; |
2012 | |
2013 | /// Retrieve the type of the \c __builtin_va_list type. |
2014 | QualType getBuiltinVaListType() const { |
2015 | return getTypeDeclType(getBuiltinVaListDecl()); |
2016 | } |
2017 | |
2018 | /// Retrieve the C type declaration corresponding to the predefined |
2019 | /// \c __va_list_tag type used to help define the \c __builtin_va_list type |
2020 | /// for some targets. |
2021 | Decl *getVaListTagDecl() const; |
2022 | |
2023 | /// Retrieve the C type declaration corresponding to the predefined |
2024 | /// \c __builtin_ms_va_list type. |
2025 | TypedefDecl *getBuiltinMSVaListDecl() const; |
2026 | |
2027 | /// Retrieve the type of the \c __builtin_ms_va_list type. |
2028 | QualType getBuiltinMSVaListType() const { |
2029 | return getTypeDeclType(getBuiltinMSVaListDecl()); |
2030 | } |
2031 | |
2032 | /// Retrieve the implicitly-predeclared 'struct _GUID' declaration. |
2033 | TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; } |
2034 | |
2035 | /// Retrieve the implicitly-predeclared 'struct _GUID' type. |
2036 | QualType getMSGuidType() const { |
2037 | assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled")(static_cast <bool> (MSGuidTagDecl && "asked for GUID type but MS extensions disabled" ) ? void (0) : __assert_fail ("MSGuidTagDecl && \"asked for GUID type but MS extensions disabled\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 2037, __extension__ __PRETTY_FUNCTION__)); |
2038 | return getTagDeclType(MSGuidTagDecl); |
2039 | } |
2040 | |
2041 | /// Return whether a declaration to a builtin is allowed to be |
2042 | /// overloaded/redeclared. |
2043 | bool canBuiltinBeRedeclared(const FunctionDecl *) const; |
2044 | |
2045 | /// Return a type with additional \c const, \c volatile, or |
2046 | /// \c restrict qualifiers. |
2047 | QualType getCVRQualifiedType(QualType T, unsigned CVR) const { |
2048 | return getQualifiedType(T, Qualifiers::fromCVRMask(CVR)); |
2049 | } |
2050 | |
2051 | /// Un-split a SplitQualType. |
2052 | QualType getQualifiedType(SplitQualType split) const { |
2053 | return getQualifiedType(split.Ty, split.Quals); |
2054 | } |
2055 | |
2056 | /// Return a type with additional qualifiers. |
2057 | QualType getQualifiedType(QualType T, Qualifiers Qs) const { |
2058 | if (!Qs.hasNonFastQualifiers()) |
2059 | return T.withFastQualifiers(Qs.getFastQualifiers()); |
2060 | QualifierCollector Qc(Qs); |
2061 | const Type *Ptr = Qc.strip(T); |
2062 | return getExtQualType(Ptr, Qc); |
2063 | } |
2064 | |
2065 | /// Return a type with additional qualifiers. |
2066 | QualType getQualifiedType(const Type *T, Qualifiers Qs) const { |
2067 | if (!Qs.hasNonFastQualifiers()) |
2068 | return QualType(T, Qs.getFastQualifiers()); |
2069 | return getExtQualType(T, Qs); |
2070 | } |
2071 | |
2072 | /// Return a type with the given lifetime qualifier. |
2073 | /// |
2074 | /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None. |
2075 | QualType getLifetimeQualifiedType(QualType type, |
2076 | Qualifiers::ObjCLifetime lifetime) { |
2077 | assert(type.getObjCLifetime() == Qualifiers::OCL_None)(static_cast <bool> (type.getObjCLifetime() == Qualifiers ::OCL_None) ? void (0) : __assert_fail ("type.getObjCLifetime() == Qualifiers::OCL_None" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 2077, __extension__ __PRETTY_FUNCTION__)); |
2078 | assert(lifetime != Qualifiers::OCL_None)(static_cast <bool> (lifetime != Qualifiers::OCL_None) ? void (0) : __assert_fail ("lifetime != Qualifiers::OCL_None" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/ASTContext.h" , 2078, __extension__ __PRETTY_FUNCTION__)); |
2079 | |
2080 | Qualifiers qs; |
2081 | qs.addObjCLifetime(lifetime); |
2082 | return getQualifiedType(type, qs); |
2083 | } |
2084 | |
2085 | /// getUnqualifiedObjCPointerType - Returns version of |
2086 | /// Objective-C pointer type with lifetime qualifier removed. |
2087 | QualType getUnqualifiedObjCPointerType(QualType type) const { |
2088 | if (!type.getTypePtr()->isObjCObjectPointerType() || |
2089 | !type.getQualifiers().hasObjCLifetime()) |
2090 | return type; |
2091 | Qualifiers Qs = type.getQualifiers(); |
2092 | Qs.removeObjCLifetime(); |
2093 | return getQualifiedType(type.getUnqualifiedType(), Qs); |
2094 | } |
2095 | |
2096 | unsigned char getFixedPointScale(QualType Ty) const; |
2097 | unsigned char getFixedPointIBits(QualType Ty) const; |
2098 | llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const; |
2099 | llvm::APFixedPoint getFixedPointMax(QualType Ty) const; |
2100 | llvm::APFixedPoint getFixedPointMin(QualType Ty) const; |
2101 | |
2102 | DeclarationNameInfo getNameForTemplate(TemplateName Name, |
2103 | SourceLocation NameLoc) const; |
2104 | |
2105 | TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, |
2106 | UnresolvedSetIterator End) const; |
2107 | TemplateName getAssumedTemplateName(DeclarationName Name) const; |
2108 | |
2109 | TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, |
2110 | bool TemplateKeyword, |
2111 | TemplateDecl *Template) const; |
2112 | |
2113 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
2114 | const IdentifierInfo *Name) const; |
2115 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
2116 | OverloadedOperatorKind Operator) const; |
2117 | TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, |
2118 | TemplateName replacement) const; |
2119 | TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, |
2120 | const TemplateArgument &ArgPack) const; |
2121 | |
2122 | enum GetBuiltinTypeError { |
2123 | /// No error |
2124 | GE_None, |
2125 | |
2126 | /// Missing a type |
2127 | GE_Missing_type, |
2128 | |
2129 | /// Missing a type from <stdio.h> |
2130 | GE_Missing_stdio, |
2131 | |
2132 | /// Missing a type from <setjmp.h> |
2133 | GE_Missing_setjmp, |
2134 | |
2135 | /// Missing a type from <ucontext.h> |
2136 | GE_Missing_ucontext |
2137 | }; |
2138 | |
2139 | QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, |
2140 | ASTContext::GetBuiltinTypeError &Error, |
2141 | bool &RequireICE, bool AllowTypeModifiers) const; |
2142 | |
2143 | /// Return the type for the specified builtin. |
2144 | /// |
2145 | /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of |
2146 | /// arguments to the builtin that are required to be integer constant |
2147 | /// expressions. |
2148 | QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, |
2149 | unsigned *IntegerConstantArgs = nullptr) const; |
2150 | |
2151 | /// Types and expressions required to build C++2a three-way comparisons |
2152 | /// using operator<=>, including the values return by builtin <=> operators. |
2153 | ComparisonCategories CompCategories; |
2154 | |
2155 | private: |
2156 | CanQualType getFromTargetType(unsigned Type) const; |
2157 | TypeInfo getTypeInfoImpl(const Type *T) const; |
2158 | |
2159 | //===--------------------------------------------------------------------===// |
2160 | // Type Predicates. |
2161 | //===--------------------------------------------------------------------===// |
2162 | |
2163 | public: |
2164 | /// Return one of the GCNone, Weak or Strong Objective-C garbage |
2165 | /// collection attributes. |
2166 | Qualifiers::GC getObjCGCAttrKind(QualType Ty) const; |
2167 | |
2168 | /// Return true if the given vector types are of the same unqualified |
2169 | /// type or if they are equivalent to the same GCC vector type. |
2170 | /// |
2171 | /// \note This ignores whether they are target-specific (AltiVec or Neon) |
2172 | /// types. |
2173 | bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); |
2174 | |
2175 | /// Return true if the given types are an SVE builtin and a VectorType that |
2176 | /// is a fixed-length representation of the SVE builtin for a specific |
2177 | /// vector-length. |
2178 | bool areCompatibleSveTypes(QualType FirstType, QualType SecondType); |
2179 | |
2180 | /// Return true if the given vector types are lax-compatible SVE vector types, |
2181 | /// false otherwise. |
2182 | bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType); |
2183 | |
2184 | /// Return true if the type has been explicitly qualified with ObjC ownership. |
2185 | /// A type may be implicitly qualified with ownership under ObjC ARC, and in |
2186 | /// some cases the compiler treats these differently. |
2187 | bool hasDirectOwnershipQualifier(QualType Ty) const; |
2188 | |
2189 | /// Return true if this is an \c NSObject object with its \c NSObject |
2190 | /// attribute set. |
2191 | static bool isObjCNSObjectType(QualType Ty) { |
2192 | return Ty->isObjCNSObjectType(); |
2193 | } |
2194 | |
2195 | //===--------------------------------------------------------------------===// |
2196 | // Type Sizing and Analysis |
2197 | //===--------------------------------------------------------------------===// |
2198 | |
2199 | /// Return the APFloat 'semantics' for the specified scalar floating |
2200 | /// point type. |
2201 | const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; |
2202 | |
2203 | /// Get the size and alignment of the specified complete type in bits. |
2204 | TypeInfo getTypeInfo(const Type *T) const; |
2205 | TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); } |
2206 | |
2207 | /// Get default simd alignment of the specified complete type in bits. |
2208 | unsigned getOpenMPDefaultSimdAlign(QualType T) const; |
2209 | |
2210 | /// Return the size of the specified (complete) type \p T, in bits. |
2211 | uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; } |
2212 | uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; } |
2213 | |
2214 | /// Return the size of the character type, in bits. |
2215 | uint64_t getCharWidth() const { |
2216 | return getTypeSize(CharTy); |
2217 | } |
2218 | |
2219 | /// Convert a size in bits to a size in characters. |
2220 | CharUnits toCharUnitsFromBits(int64_t BitSize) const; |
2221 | |
2222 | /// Convert a size in characters to a size in bits. |
2223 | int64_t toBits(CharUnits CharSize) const; |
2224 | |
2225 | /// Return the size of the specified (complete) type \p T, in |
2226 | /// characters. |
2227 | CharUnits getTypeSizeInChars(QualType T) const; |
2228 | CharUnits getTypeSizeInChars(const Type *T) const; |
2229 | |
2230 | Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { |
2231 | if (Ty->isIncompleteType() || Ty->isDependentType()) |
2232 | return None; |
2233 | return getTypeSizeInChars(Ty); |
2234 | } |
2235 | |
2236 | Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { |
2237 | return getTypeSizeInCharsIfKnown(QualType(Ty, 0)); |
2238 | } |
2239 | |
2240 | /// Return the ABI-specified alignment of a (complete) type \p T, in |
2241 | /// bits. |
2242 | unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; } |
2243 | unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; } |
2244 | |
2245 | /// Return the ABI-specified natural alignment of a (complete) type \p T, |
2246 | /// before alignment adjustments, in bits. |
2247 | /// |
2248 | /// This alignment is curently used only by ARM and AArch64 when passing |
2249 | /// arguments of a composite type. |
2250 | unsigned getTypeUnadjustedAlign(QualType T) const { |
2251 | return getTypeUnadjustedAlign(T.getTypePtr()); |
2252 | } |
2253 | unsigned getTypeUnadjustedAlign(const Type *T) const; |
2254 | |
2255 | /// Return the alignment of a type, in bits, or 0 if |
2256 | /// the type is incomplete and we cannot determine the alignment (for |
2257 | /// example, from alignment attributes). The returned alignment is the |
2258 | /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the |
2259 | /// ABI alignment. |
2260 | unsigned getTypeAlignIfKnown(QualType T, |
2261 | bool NeedsPreferredAlignment = false) const; |
2262 | |
2263 | /// Return the ABI-specified alignment of a (complete) type \p T, in |
2264 | /// characters. |
2265 | CharUnits getTypeAlignInChars(QualType T) const; |
2266 | CharUnits getTypeAlignInChars(const Type *T) const; |
2267 | |
2268 | /// Return the PreferredAlignment of a (complete) type \p T, in |
2269 | /// characters. |
2270 | CharUnits getPreferredTypeAlignInChars(QualType T) const { |
2271 | return toCharUnitsFromBits(getPreferredTypeAlign(T)); |
2272 | } |
2273 | |
2274 | /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, |
2275 | /// in characters, before alignment adjustments. This method does not work on |
2276 | /// incomplete types. |
2277 | CharUnits getTypeUnadjustedAlignInChars(QualType T) const; |
2278 | CharUnits getTypeUnadjustedAlignInChars(const Type *T) const; |
2279 | |
2280 | // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the |
2281 | // type is a record, its data size is returned. |
2282 | TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const; |
2283 | |
2284 | TypeInfoChars getTypeInfoInChars(const Type *T) const; |
2285 | TypeInfoChars getTypeInfoInChars(QualType T) const; |
2286 | |
2287 | /// Determine if the alignment the type has was required using an |
2288 | /// alignment attribute. |
2289 | bool isAlignmentRequired(const Type *T) const; |
2290 | bool isAlignmentRequired(QualType T) const; |
2291 | |
2292 | /// Return the "preferred" alignment of the specified type \p T for |
2293 | /// the current target, in bits. |
2294 | /// |
2295 | /// This can be different than the ABI alignment in cases where it is |
2296 | /// beneficial for performance or backwards compatibility preserving to |
2297 | /// overalign a data type. (Note: despite the name, the preferred alignment |
2298 | /// is ABI-impacting, and not an optimization.) |
2299 | unsigned getPreferredTypeAlign(QualType T) const { |
2300 | return getPreferredTypeAlign(T.getTypePtr()); |
2301 | } |
2302 | unsigned getPreferredTypeAlign(const Type *T) const; |
2303 | |
2304 | /// Return the default alignment for __attribute__((aligned)) on |
2305 | /// this target, to be used if no alignment value is specified. |
2306 | unsigned getTargetDefaultAlignForAttributeAligned() const; |
2307 | |
2308 | /// Return the alignment in bits that should be given to a |
2309 | /// global variable with type \p T. |
2310 | unsigned getAlignOfGlobalVar(QualType T) const; |
2311 | |
2312 | /// Return the alignment in characters that should be given to a |
2313 | /// global variable with type \p T. |
2314 | CharUnits getAlignOfGlobalVarInChars(QualType T) const; |
2315 | |
2316 | /// Return a conservative estimate of the alignment of the specified |
2317 | /// decl \p D. |
2318 | /// |
2319 | /// \pre \p D must not be a bitfield type, as bitfields do not have a valid |
2320 | /// alignment. |
2321 | /// |
2322 | /// If \p ForAlignof, references are treated like their underlying type |
2323 | /// and large arrays don't get any special treatment. If not \p ForAlignof |
2324 | /// it computes the value expected by CodeGen: references are treated like |
2325 | /// pointers and large arrays get extra alignment. |
2326 | CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const; |
2327 | |
2328 | /// Return the alignment (in bytes) of the thrown exception object. This is |
2329 | /// only meaningful for targets that allocate C++ exceptions in a system |
2330 | /// runtime, such as those using the Itanium C++ ABI. |
2331 | CharUnits getExnObjectAlignment() const; |
2332 | |
2333 | /// Get or compute information about the layout of the specified |
2334 | /// record (struct/union/class) \p D, which indicates its size and field |
2335 | /// position information. |
2336 | const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const; |
2337 | |
2338 | /// Get or compute information about the layout of the specified |
2339 | /// Objective-C interface. |
2340 | const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) |
2341 | const; |
2342 | |
2343 | void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, |
2344 | bool Simple = false) const; |
2345 | |
2346 | /// Get or compute information about the layout of the specified |
2347 | /// Objective-C implementation. |
2348 | /// |
2349 | /// This may differ from the interface if synthesized ivars are present. |
2350 | const ASTRecordLayout & |
2351 | getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const; |
2352 | |
2353 | /// Get our current best idea for the key function of the |
2354 | /// given record decl, or nullptr if there isn't one. |
2355 | /// |
2356 | /// The key function is, according to the Itanium C++ ABI section 5.2.3: |
2357 | /// ...the first non-pure virtual function that is not inline at the |
2358 | /// point of class definition. |
2359 | /// |
2360 | /// Other ABIs use the same idea. However, the ARM C++ ABI ignores |
2361 | /// virtual functions that are defined 'inline', which means that |
2362 | /// the result of this computation can change. |
2363 | const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD); |
2364 | |
2365 | /// Observe that the given method cannot be a key function. |
2366 | /// Checks the key-function cache for the method's class and clears it |
2367 | /// if matches the given declaration. |
2368 | /// |
2369 | /// This is used in ABIs where out-of-line definitions marked |
2370 | /// inline are not considered to be key functions. |
2371 | /// |
2372 | /// \param method should be the declaration from the class definition |
2373 | void setNonKeyFunction(const CXXMethodDecl *method); |
2374 | |
2375 | /// Loading virtual member pointers using the virtual inheritance model |
2376 | /// always results in an adjustment using the vbtable even if the index is |
2377 | /// zero. |
2378 | /// |
2379 | /// This is usually OK because the first slot in the vbtable points |
2380 | /// backwards to the top of the MDC. However, the MDC might be reusing a |
2381 | /// vbptr from an nv-base. In this case, the first slot in the vbtable |
2382 | /// points to the start of the nv-base which introduced the vbptr and *not* |
2383 | /// the MDC. Modify the NonVirtualBaseAdjustment to account for this. |
2384 | CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const; |
2385 | |
2386 | /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. |
2387 | uint64_t getFieldOffset(const ValueDecl *FD) const; |
2388 | |
2389 | /// Get the offset of an ObjCIvarDecl in bits. |
2390 | uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, |
2391 | const ObjCImplementationDecl *ID, |
2392 | const ObjCIvarDecl *Ivar) const; |
2393 | |
2394 | /// Find the 'this' offset for the member path in a pointer-to-member |
2395 | /// APValue. |
2396 | CharUnits getMemberPointerPathAdjustment(const APValue &MP) const; |
2397 | |
2398 | bool isNearlyEmpty(const CXXRecordDecl *RD) const; |
2399 | |
2400 | VTableContextBase *getVTableContext(); |
2401 | |
2402 | /// If \p T is null pointer, assume the target in ASTContext. |
2403 | MangleContext *createMangleContext(const TargetInfo *T = nullptr); |
2404 | |
2405 | /// Creates a device mangle context to correctly mangle lambdas in a mixed |
2406 | /// architecture compile by setting the lambda mangling number source to the |
2407 | /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo |
2408 | /// (from the AuxTargetInfo) is a an itanium target. |
2409 | MangleContext *createDeviceMangleContext(const TargetInfo &T); |
2410 | |
2411 | void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, |
2412 | SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const; |
2413 | |
2414 | unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const; |
2415 | void CollectInheritedProtocols(const Decl *CDecl, |
2416 | llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols); |
2417 | |
2418 | /// Return true if the specified type has unique object representations |
2419 | /// according to (C++17 [meta.unary.prop]p9) |
2420 | bool hasUniqueObjectRepresentations(QualType Ty) const; |
2421 | |
2422 | //===--------------------------------------------------------------------===// |
2423 | // Type Operators |
2424 | //===--------------------------------------------------------------------===// |
2425 | |
2426 | /// Return the canonical (structural) type corresponding to the |
2427 | /// specified potentially non-canonical type \p T. |
2428 | /// |
2429 | /// The non-canonical version of a type may have many "decorated" versions of |
2430 | /// types. Decorators can include typedefs, 'typeof' operators, etc. The |
2431 | /// returned type is guaranteed to be free of any of these, allowing two |
2432 | /// canonical types to be compared for exact equality with a simple pointer |
2433 | /// comparison. |
2434 | CanQualType getCanonicalType(QualType T) const { |
2435 | return CanQualType::CreateUnsafe(T.getCanonicalType()); |
2436 | } |
2437 | |
2438 | const Type *getCanonicalType(const Type *T) const { |
2439 | return T->getCanonicalTypeInternal().getTypePtr(); |
2440 | } |
2441 | |
2442 | /// Return the canonical parameter type corresponding to the specific |
2443 | /// potentially non-canonical one. |
2444 | /// |
2445 | /// Qualifiers are stripped off, functions are turned into function |
2446 | /// pointers, and arrays decay one level into pointers. |
2447 | CanQualType getCanonicalParamType(QualType T) const; |
2448 | |
2449 | /// Determine whether the given types \p T1 and \p T2 are equivalent. |
2450 | bool hasSameType(QualType T1, QualType T2) const { |
2451 | return getCanonicalType(T1) == getCanonicalType(T2); |
2452 | } |
2453 | bool hasSameType(const Type *T1, const Type *T2) const { |
2454 | return getCanonicalType(T1) == getCanonicalType(T2); |
2455 | } |
2456 | |
2457 | /// Return this type as a completely-unqualified array type, |
2458 | /// capturing the qualifiers in \p Quals. |
2459 | /// |
2460 | /// This will remove the minimal amount of sugaring from the types, similar |
2461 | /// to the behavior of QualType::getUnqualifiedType(). |
2462 | /// |
2463 | /// \param T is the qualified type, which may be an ArrayType |
2464 | /// |
2465 | /// \param Quals will receive the full set of qualifiers that were |
2466 | /// applied to the array. |
2467 | /// |
2468 | /// \returns if this is an array type, the completely unqualified array type |
2469 | /// that corresponds to it. Otherwise, returns T.getUnqualifiedType(). |
2470 | QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals); |
2471 | |
2472 | /// Determine whether the given types are equivalent after |
2473 | /// cvr-qualifiers have been removed. |
2474 | bool hasSameUnqualifiedType(QualType T1, QualType T2) const { |
2475 | return getCanonicalType(T1).getTypePtr() == |
2476 | getCanonicalType(T2).getTypePtr(); |
2477 | } |
2478 | |
2479 | bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT, |
2480 | bool IsParam) const { |
2481 | auto SubTnullability = SubT->getNullability(*this); |
2482 | auto SuperTnullability = SuperT->getNullability(*this); |
2483 | if (SubTnullability.hasValue() == SuperTnullability.hasValue()) { |
2484 | // Neither has nullability; return true |
2485 | if (!SubTnullability) |
2486 | return true; |
2487 | // Both have nullability qualifier. |
2488 | if (*SubTnullability == *SuperTnullability || |
2489 | *SubTnullability == NullabilityKind::Unspecified || |
2490 | *SuperTnullability == NullabilityKind::Unspecified) |
2491 | return true; |
2492 | |
2493 | if (IsParam) { |
2494 | // Ok for the superclass method parameter to be "nonnull" and the subclass |
2495 | // method parameter to be "nullable" |
2496 | return (*SuperTnullability == NullabilityKind::NonNull && |
2497 | *SubTnullability == NullabilityKind::Nullable); |
2498 | } |
2499 | // For the return type, it's okay for the superclass method to specify |
2500 | // "nullable" and the subclass method specify "nonnull" |
2501 | return (*SuperTnullability == NullabilityKind::Nullable && |
2502 | *SubTnullability == NullabilityKind::NonNull); |
2503 | } |
2504 | return true; |
2505 | } |
2506 | |
2507 | bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, |
2508 | const ObjCMethodDecl *MethodImp); |
2509 | |
2510 | bool UnwrapSimilarTypes(QualType &T1, QualType &T2); |
2511 | void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2); |
2512 | |
2513 | /// Determine if two types are similar, according to the C++ rules. That is, |
2514 | /// determine if they are the same other than qualifiers on the initial |
2515 | /// sequence of pointer / pointer-to-member / array (and in Clang, object |
2516 | /// pointer) types and their element types. |
2517 | /// |
2518 | /// Clang offers a number of qualifiers in addition to the C++ qualifiers; |
2519 | /// those qualifiers are also ignored in the 'similarity' check. |
2520 | bool hasSimilarType(QualType T1, QualType T2); |
2521 | |
2522 | /// Determine if two types are similar, ignoring only CVR qualifiers. |
2523 | bool hasCvrSimilarType(QualType T1, QualType T2); |
2524 | |
2525 | /// Retrieves the "canonical" nested name specifier for a |
2526 | /// given nested name specifier. |
2527 | /// |
2528 | /// The canonical nested name specifier is a nested name specifier |
2529 | /// that uniquely identifies a type or namespace within the type |
2530 | /// system. For example, given: |
2531 | /// |
2532 | /// \code |
2533 | /// namespace N { |
2534 | /// struct S { |
2535 | /// template<typename T> struct X { typename T* type; }; |
2536 | /// }; |
2537 | /// } |
2538 | /// |
2539 | /// template<typename T> struct Y { |
2540 | /// typename N::S::X<T>::type member; |
2541 | /// }; |
2542 | /// \endcode |
2543 | /// |
2544 | /// Here, the nested-name-specifier for N::S::X<T>:: will be |
2545 | /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined |
2546 | /// by declarations in the type system and the canonical type for |
2547 | /// the template type parameter 'T' is template-param-0-0. |
2548 | NestedNameSpecifier * |
2549 | getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const; |
2550 | |
2551 | /// Retrieves the default calling convention for the current target. |
2552 | CallingConv getDefaultCallingConvention(bool IsVariadic, |
2553 | bool IsCXXMethod, |
2554 | bool IsBuiltin = false) const; |
2555 | |
2556 | /// Retrieves the "canonical" template name that refers to a |
2557 | /// given template. |
2558 | /// |
2559 | /// The canonical template name is the simplest expression that can |
2560 | /// be used to refer to a given template. For most templates, this |
2561 | /// expression is just the template declaration itself. For example, |
2562 | /// the template std::vector can be referred to via a variety of |
2563 | /// names---std::vector, \::std::vector, vector (if vector is in |
2564 | /// scope), etc.---but all of these names map down to the same |
2565 | /// TemplateDecl, which is used to form the canonical template name. |
2566 | /// |
2567 | /// Dependent template names are more interesting. Here, the |
2568 | /// template name could be something like T::template apply or |
2569 | /// std::allocator<T>::template rebind, where the nested name |
2570 | /// specifier itself is dependent. In this case, the canonical |
2571 | /// template name uses the shortest form of the dependent |
2572 | /// nested-name-specifier, which itself contains all canonical |
2573 | /// types, values, and templates. |
2574 | TemplateName getCanonicalTemplateName(TemplateName Name) const; |
2575 | |
2576 | /// Determine whether the given template names refer to the same |
2577 | /// template. |
2578 | bool hasSameTemplateName(TemplateName X, TemplateName Y); |
2579 | |
2580 | /// Retrieve the "canonical" template argument. |
2581 | /// |
2582 | /// The canonical template argument is the simplest template argument |
2583 | /// (which may be a type, value, expression, or declaration) that |
2584 | /// expresses the value of the argument. |
2585 | TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) |
2586 | const; |
2587 | |
2588 | /// Type Query functions. If the type is an instance of the specified class, |
2589 | /// return the Type pointer for the underlying maximally pretty type. This |
2590 | /// is a member of ASTContext because this may need to do some amount of |
2591 | /// canonicalization, e.g. to move type qualifiers into the element type. |
2592 | const ArrayType *getAsArrayType(QualType T) const; |
2593 | const ConstantArrayType *getAsConstantArrayType(QualType T) const { |
2594 | return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T)); |
2595 | } |
2596 | const VariableArrayType *getAsVariableArrayType(QualType T) const { |
2597 | return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T)); |
2598 | } |
2599 | const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { |
2600 | return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T)); |
2601 | } |
2602 | const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) |
2603 | const { |
2604 | return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T)); |
2605 | } |
2606 | |
2607 | /// Return the innermost element type of an array type. |
2608 | /// |
2609 | /// For example, will return "int" for int[m][n] |
2610 | QualType getBaseElementType(const ArrayType *VAT) const; |
2611 | |
2612 | /// Return the innermost element type of a type (which needn't |
2613 | /// actually be an array type). |
2614 | QualType getBaseElementType(QualType QT) const; |
2615 | |
2616 | /// Return number of constant array elements. |
2617 | uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; |
2618 | |
2619 | /// Perform adjustment on the parameter type of a function. |
2620 | /// |
2621 | /// This routine adjusts the given parameter type @p T to the actual |
2622 | /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], |
2623 | /// C++ [dcl.fct]p3). The adjusted parameter type is returned. |
2624 | QualType getAdjustedParameterType(QualType T) const; |
2625 | |
2626 | /// Retrieve the parameter type as adjusted for use in the signature |
2627 | /// of a function, decaying array and function types and removing top-level |
2628 | /// cv-qualifiers. |
2629 | QualType getSignatureParameterType(QualType T) const; |
2630 | |
2631 | QualType getExceptionObjectType(QualType T) const; |
2632 | |
2633 | /// Return the properly qualified result of decaying the specified |
2634 | /// array type to a pointer. |
2635 | /// |
2636 | /// This operation is non-trivial when handling typedefs etc. The canonical |
2637 | /// type of \p T must be an array type, this returns a pointer to a properly |
2638 | /// qualified element of the array. |
2639 | /// |
2640 | /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. |
2641 | QualType getArrayDecayedType(QualType T) const; |
2642 | |
2643 | /// Return the type that \p PromotableType will promote to: C99 |
2644 | /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type. |
2645 | QualType getPromotedIntegerType(QualType PromotableType) const; |
2646 | |
2647 | /// Recurses in pointer/array types until it finds an Objective-C |
2648 | /// retainable type and returns its ownership. |
2649 | Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; |
2650 | |
2651 | /// Whether this is a promotable bitfield reference according |
2652 | /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). |
2653 | /// |
2654 | /// \returns the type this bit-field will promote to, or NULL if no |
2655 | /// promotion occurs. |
2656 | QualType isPromotableBitField(Expr *E) const; |
2657 | |
2658 | /// Return the highest ranked integer type, see C99 6.3.1.8p1. |
2659 | /// |
2660 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2661 | /// \p LHS < \p RHS, return -1. |
2662 | int getIntegerTypeOrder(QualType LHS, QualType RHS) const; |
2663 | |
2664 | /// Compare the rank of the two specified floating point types, |
2665 | /// ignoring the domain of the type (i.e. 'double' == '_Complex double'). |
2666 | /// |
2667 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2668 | /// \p LHS < \p RHS, return -1. |
2669 | int getFloatingTypeOrder(QualType LHS, QualType RHS) const; |
2670 | |
2671 | /// Compare the rank of two floating point types as above, but compare equal |
2672 | /// if both types have the same floating-point semantics on the target (i.e. |
2673 | /// long double and double on AArch64 will return 0). |
2674 | int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const; |
2675 | |
2676 | /// Return a real floating point or a complex type (based on |
2677 | /// \p typeDomain/\p typeSize). |
2678 | /// |
2679 | /// \param typeDomain a real floating point or complex type. |
2680 | /// \param typeSize a real floating point or complex type. |
2681 | QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, |
2682 | QualType typeDomain) const; |
2683 | |
2684 | unsigned getTargetAddressSpace(QualType T) const { |
2685 | return getTargetAddressSpace(T.getQualifiers()); |
2686 | } |
2687 | |
2688 | unsigned getTargetAddressSpace(Qualifiers Q) const { |
2689 | return getTargetAddressSpace(Q.getAddressSpace()); |
2690 | } |
2691 | |
2692 | unsigned getTargetAddressSpace(LangAS AS) const; |
2693 | |
2694 | LangAS getLangASForBuiltinAddressSpace(unsigned AS) const; |
2695 | |
2696 | /// Get target-dependent integer value for null pointer which is used for |
2697 | /// constant folding. |
2698 | uint64_t getTargetNullPointerValue(QualType QT) const; |
2699 | |
2700 | bool addressSpaceMapManglingFor(LangAS AS) const { |
2701 | return AddrSpaceMapMangling || isTargetAddressSpace(AS); |
2702 | } |
2703 | |
2704 | private: |
2705 | // Helper for integer ordering |
2706 | unsigned getIntegerRank(const Type *T) const; |
2707 | |
2708 | public: |
2709 | //===--------------------------------------------------------------------===// |
2710 | // Type Compatibility Predicates |
2711 | //===--------------------------------------------------------------------===// |
2712 | |
2713 | /// Compatibility predicates used to check assignment expressions. |
2714 | bool typesAreCompatible(QualType T1, QualType T2, |
2715 | bool CompareUnqualified = false); // C99 6.2.7p1 |
2716 | |
2717 | bool propertyTypesAreCompatible(QualType, QualType); |
2718 | bool typesAreBlockPointerCompatible(QualType, QualType); |
2719 | |
2720 | bool isObjCIdType(QualType T) const { |
2721 | return T == getObjCIdType(); |
2722 | } |
2723 | |
2724 | bool isObjCClassType(QualType T) const { |
2725 | return T == getObjCClassType(); |
2726 | } |
2727 | |
2728 | bool isObjCSelType(QualType T) const { |
2729 | return T == getObjCSelType(); |
2730 | } |
2731 | |
2732 | bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, |
2733 | const ObjCObjectPointerType *RHS, |
2734 | bool ForCompare); |
2735 | |
2736 | bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, |
2737 | const ObjCObjectPointerType *RHS); |
2738 | |
2739 | // Check the safety of assignment from LHS to RHS |
2740 | bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, |
2741 | const ObjCObjectPointerType *RHSOPT); |
2742 | bool canAssignObjCInterfaces(const ObjCObjectType *LHS, |
2743 | const ObjCObjectType *RHS); |
2744 | bool canAssignObjCInterfacesInBlockPointer( |
2745 | const ObjCObjectPointerType *LHSOPT, |
2746 | const ObjCObjectPointerType *RHSOPT, |
2747 | bool BlockReturnType); |
2748 | bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); |
2749 | QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, |
2750 | const ObjCObjectPointerType *RHSOPT); |
2751 | bool canBindObjCObjectType(QualType To, QualType From); |
2752 | |
2753 | // Functions for calculating composite types |
2754 | QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, |
2755 | bool Unqualified = false, bool BlockReturnType = false); |
2756 | QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, |
2757 | bool Unqualified = false, bool AllowCXX = false); |
2758 | QualType mergeFunctionParameterTypes(QualType, QualType, |
2759 | bool OfBlockPointer = false, |
2760 | bool Unqualified = false); |
2761 | QualType mergeTransparentUnionType(QualType, QualType, |
2762 | bool OfBlockPointer=false, |
2763 | bool Unqualified = false); |
2764 | |
2765 | QualType mergeObjCGCQualifiers(QualType, QualType); |
2766 | |
2767 | /// This function merges the ExtParameterInfo lists of two functions. It |
2768 | /// returns true if the lists are compatible. The merged list is returned in |
2769 | /// NewParamInfos. |
2770 | /// |
2771 | /// \param FirstFnType The type of the first function. |
2772 | /// |
2773 | /// \param SecondFnType The type of the second function. |
2774 | /// |
2775 | /// \param CanUseFirst This flag is set to true if the first function's |
2776 | /// ExtParameterInfo list can be used as the composite list of |
2777 | /// ExtParameterInfo. |
2778 | /// |
2779 | /// \param CanUseSecond This flag is set to true if the second function's |
2780 | /// ExtParameterInfo list can be used as the composite list of |
2781 | /// ExtParameterInfo. |
2782 | /// |
2783 | /// \param NewParamInfos The composite list of ExtParameterInfo. The list is |
2784 | /// empty if none of the flags are set. |
2785 | /// |
2786 | bool mergeExtParameterInfo( |
2787 | const FunctionProtoType *FirstFnType, |
2788 | const FunctionProtoType *SecondFnType, |
2789 | bool &CanUseFirst, bool &CanUseSecond, |
2790 | SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos); |
2791 | |
2792 | void ResetObjCLayout(const ObjCContainerDecl *CD); |
2793 | |
2794 | //===--------------------------------------------------------------------===// |
2795 | // Integer Predicates |
2796 | //===--------------------------------------------------------------------===// |
2797 | |
2798 | // The width of an integer, as defined in C99 6.2.6.2. This is the number |
2799 | // of bits in an integer type excluding any padding bits. |
2800 | unsigned getIntWidth(QualType T) const; |
2801 | |
2802 | // Per C99 6.2.5p6, for every signed integer type, there is a corresponding |
2803 | // unsigned integer type. This method takes a signed type, and returns the |
2804 | // corresponding unsigned integer type. |
2805 | // With the introduction of fixed point types in ISO N1169, this method also |
2806 | // accepts fixed point types and returns the corresponding unsigned type for |
2807 | // a given fixed point type. |
2808 | QualType getCorrespondingUnsignedType(QualType T) const; |
2809 | |
2810 | // Per C99 6.2.5p6, for every signed integer type, there is a corresponding |
2811 | // unsigned integer type. This method takes an unsigned type, and returns the |
2812 | // corresponding signed integer type. |
2813 | // With the introduction of fixed point types in ISO N1169, this method also |
2814 | // accepts fixed point types and returns the corresponding signed type for |
2815 | // a given fixed point type. |
2816 | QualType getCorrespondingSignedType(QualType T) const; |
2817 | |
2818 | // Per ISO N1169, this method accepts fixed point types and returns the |
2819 | // corresponding saturated type for a given fixed point type. |
2820 | QualType getCorrespondingSaturatedType(QualType Ty) const; |
2821 | |
2822 | // This method accepts fixed point types and returns the corresponding signed |
2823 | // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned |
2824 | // fixed point types because there are unsigned integer types like bool and |
2825 | // char8_t that don't have signed equivalents. |
2826 | QualType getCorrespondingSignedFixedPointType(QualType Ty) const; |
2827 | |
2828 | //===--------------------------------------------------------------------===// |
2829 | // Integer Values |
2830 | //===--------------------------------------------------------------------===// |
2831 | |
2832 | /// Make an APSInt of the appropriate width and signedness for the |
2833 | /// given \p Value and integer \p Type. |
2834 | llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { |
2835 | // If Type is a signed integer type larger than 64 bits, we need to be sure |
2836 | // to sign extend Res appropriately. |
2837 | llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType()); |
2838 | Res = Value; |
2839 | unsigned Width = getIntWidth(Type); |
2840 | if (Width != Res.getBitWidth()) |
2841 | return Res.extOrTrunc(Width); |
2842 | return Res; |
2843 | } |
2844 | |
2845 | bool isSentinelNullExpr(const Expr *E); |
2846 | |
2847 | /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if |
2848 | /// none exists. |
2849 | ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); |
2850 | |
2851 | /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if |
2852 | /// none exists. |
2853 | ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); |
2854 | |
2855 | /// Return true if there is at least one \@implementation in the TU. |
2856 | bool AnyObjCImplementation() { |
2857 | return !ObjCImpls.empty(); |
2858 | } |
2859 | |
2860 | /// Set the implementation of ObjCInterfaceDecl. |
2861 | void setObjCImplementation(ObjCInterfaceDecl *IFaceD, |
2862 | ObjCImplementationDecl *ImplD); |
2863 | |
2864 | /// Set the implementation of ObjCCategoryDecl. |
2865 | void setObjCImplementation(ObjCCategoryDecl *CatD, |
2866 | ObjCCategoryImplDecl *ImplD); |
2867 | |
2868 | /// Get the duplicate declaration of a ObjCMethod in the same |
2869 | /// interface, or null if none exists. |
2870 | const ObjCMethodDecl * |
2871 | getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const; |
2872 | |
2873 | void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, |
2874 | const ObjCMethodDecl *Redecl); |
2875 | |
2876 | /// Returns the Objective-C interface that \p ND belongs to if it is |
2877 | /// an Objective-C method/property/ivar etc. that is part of an interface, |
2878 | /// otherwise returns null. |
2879 | const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const; |
2880 | |
2881 | /// Set the copy initialization expression of a block var decl. \p CanThrow |
2882 | /// indicates whether the copy expression can throw or not. |
2883 | void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow); |
2884 | |
2885 | /// Get the copy initialization expression of the VarDecl \p VD, or |
2886 | /// nullptr if none exists. |
2887 | BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const; |
2888 | |
2889 | /// Allocate an uninitialized TypeSourceInfo. |
2890 | /// |
2891 | /// The caller should initialize the memory held by TypeSourceInfo using |
2892 | /// the TypeLoc wrappers. |
2893 | /// |
2894 | /// \param T the type that will be the basis for type source info. This type |
2895 | /// should refer to how the declarator was written in source code, not to |
2896 | /// what type semantic analysis resolved the declarator to. |
2897 | /// |
2898 | /// \param Size the size of the type info to create, or 0 if the size |
2899 | /// should be calculated based on the type. |
2900 | TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; |
2901 | |
2902 | /// Allocate a TypeSourceInfo where all locations have been |
2903 | /// initialized to a given location, which defaults to the empty |
2904 | /// location. |
2905 | TypeSourceInfo * |
2906 | getTrivialTypeSourceInfo(QualType T, |
2907 | SourceLocation Loc = SourceLocation()) const; |
2908 | |
2909 | /// Add a deallocation callback that will be invoked when the |
2910 | /// ASTContext is destroyed. |
2911 | /// |
2912 | /// \param Callback A callback function that will be invoked on destruction. |
2913 | /// |
2914 | /// \param Data Pointer data that will be provided to the callback function |
2915 | /// when it is called. |
2916 | void AddDeallocation(void (*Callback)(void *), void *Data) const; |
2917 | |
2918 | /// If T isn't trivially destructible, calls AddDeallocation to register it |
2919 | /// for destruction. |
2920 | template <typename T> void addDestruction(T *Ptr) const { |
2921 | if (!std::is_trivially_destructible<T>::value) { |
2922 | auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); }; |
2923 | AddDeallocation(DestroyPtr, Ptr); |
2924 | } |
2925 | } |
2926 | |
2927 | GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const; |
2928 | GVALinkage GetGVALinkageForVariable(const VarDecl *VD); |
2929 | |
2930 | /// Determines if the decl can be CodeGen'ed or deserialized from PCH |
2931 | /// lazily, only when used; this is only relevant for function or file scoped |
2932 | /// var definitions. |
2933 | /// |
2934 | /// \returns true if the function/var must be CodeGen'ed/deserialized even if |
2935 | /// it is not used. |
2936 | bool DeclMustBeEmitted(const Decl *D); |
2937 | |
2938 | /// Visits all versions of a multiversioned function with the passed |
2939 | /// predicate. |
2940 | void forEachMultiversionedFunctionVersion( |
2941 | const FunctionDecl *FD, |
2942 | llvm::function_ref<void(FunctionDecl *)> Pred) const; |
2943 | |
2944 | const CXXConstructorDecl * |
2945 | getCopyConstructorForExceptionObject(CXXRecordDecl *RD); |
2946 | |
2947 | void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, |
2948 | CXXConstructorDecl *CD); |
2949 | |
2950 | void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND); |
2951 | |
2952 | TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD); |
2953 | |
2954 | void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD); |
2955 | |
2956 | DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD); |
2957 | |
2958 | void setManglingNumber(const NamedDecl *ND, unsigned Number); |
2959 | unsigned getManglingNumber(const NamedDecl *ND) const; |
2960 | |
2961 | void setStaticLocalNumber(const VarDecl *VD, unsigned Number); |
2962 | unsigned getStaticLocalNumber(const VarDecl *VD) const; |
2963 | |
2964 | /// Retrieve the context for computing mangling numbers in the given |
2965 | /// DeclContext. |
2966 | MangleNumberingContext &getManglingNumberContext(const DeclContext *DC); |
2967 | enum NeedExtraManglingDecl_t { NeedExtraManglingDecl }; |
2968 | MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t, |
2969 | const Decl *D); |
2970 | |
2971 | std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const; |
2972 | |
2973 | /// Used by ParmVarDecl to store on the side the |
2974 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2975 | void setParameterIndex(const ParmVarDecl *D, unsigned index); |
2976 | |
2977 | /// Used by ParmVarDecl to retrieve on the side the |
2978 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2979 | unsigned getParameterIndex(const ParmVarDecl *D) const; |
2980 | |
2981 | /// Return a string representing the human readable name for the specified |
2982 | /// function declaration or file name. Used by SourceLocExpr and |
2983 | /// PredefinedExpr to cache evaluated results. |
2984 | StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const; |
2985 | |
2986 | /// Return a declaration for the global GUID object representing the given |
2987 | /// GUID value. |
2988 | MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const; |
2989 | |
2990 | /// Return the template parameter object of the given type with the given |
2991 | /// value. |
2992 | TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T, |
2993 | const APValue &V) const; |
2994 | |
2995 | /// Parses the target attributes passed in, and returns only the ones that are |
2996 | /// valid feature names. |
2997 | ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const; |
2998 | |
2999 | void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, |
3000 | const FunctionDecl *) const; |
3001 | void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, |
3002 | GlobalDecl GD) const; |
3003 | |
3004 | //===--------------------------------------------------------------------===// |
3005 | // Statistics |
3006 | //===--------------------------------------------------------------------===// |
3007 | |
3008 | /// The number of implicitly-declared default constructors. |
3009 | unsigned NumImplicitDefaultConstructors = 0; |
3010 | |
3011 | /// The number of implicitly-declared default constructors for |
3012 | /// which declarations were built. |
3013 | unsigned NumImplicitDefaultConstructorsDeclared = 0; |
3014 | |
3015 | /// The number of implicitly-declared copy constructors. |
3016 | unsigned NumImplicitCopyConstructors = 0; |
3017 | |
3018 | /// The number of implicitly-declared copy constructors for |
3019 | /// which declarations were built. |
3020 | unsigned NumImplicitCopyConstructorsDeclared = 0; |
3021 | |
3022 | /// The number of implicitly-declared move constructors. |
3023 | unsigned NumImplicitMoveConstructors = 0; |
3024 | |
3025 | /// The number of implicitly-declared move constructors for |
3026 | /// which declarations were built. |
3027 | unsigned NumImplicitMoveConstructorsDeclared = 0; |
3028 | |
3029 | /// The number of implicitly-declared copy assignment operators. |
3030 | unsigned NumImplicitCopyAssignmentOperators = 0; |
3031 | |
3032 | /// The number of implicitly-declared copy assignment operators for |
3033 | /// which declarations were built. |
3034 | unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0; |
3035 | |
3036 | /// The number of implicitly-declared move assignment operators. |
3037 | unsigned NumImplicitMoveAssignmentOperators = 0; |
3038 | |
3039 | /// The number of implicitly-declared move assignment operators for |
3040 | /// which declarations were built. |
3041 | unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0; |
3042 | |
3043 | /// The number of implicitly-declared destructors. |
3044 | unsigned NumImplicitDestructors = 0; |
3045 | |
3046 | /// The number of implicitly-declared destructors for which |
3047 | /// declarations were built. |
3048 | unsigned NumImplicitDestructorsDeclared = 0; |
3049 | |
3050 | public: |
3051 | /// Initialize built-in types. |
3052 | /// |
3053 | /// This routine may only be invoked once for a given ASTContext object. |
3054 | /// It is normally invoked after ASTContext construction. |
3055 | /// |
3056 | /// \param Target The target |
3057 | void InitBuiltinTypes(const TargetInfo &Target, |
3058 | const TargetInfo *AuxTarget = nullptr); |
3059 | |
3060 | private: |
3061 | void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); |
3062 | |
3063 | class ObjCEncOptions { |
3064 | unsigned Bits; |
3065 | |
3066 | ObjCEncOptions(unsigned Bits) : Bits(Bits) {} |
3067 | |
3068 | public: |
3069 | ObjCEncOptions() : Bits(0) {} |
3070 | ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {} |
3071 | |
3072 | #define OPT_LIST(V) \ |
3073 | V(ExpandPointedToStructures, 0) \ |
3074 | V(ExpandStructures, 1) \ |
3075 | V(IsOutermostType, 2) \ |
3076 | V(EncodingProperty, 3) \ |
3077 | V(IsStructField, 4) \ |
3078 | V(EncodeBlockParameters, 5) \ |
3079 | V(EncodeClassNames, 6) \ |
3080 | |
3081 | #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; } |
3082 | OPT_LIST(V) |
3083 | #undef V |
3084 | |
3085 | #define V(N,I) bool N() const { return Bits & 1 << I; } |
3086 | OPT_LIST(V) |
3087 | #undef V |
3088 | |
3089 | #undef OPT_LIST |
3090 | |
3091 | LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const { |
3092 | return Bits & Mask.Bits; |
3093 | } |
3094 | |
3095 | LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions forComponentType() const { |
3096 | ObjCEncOptions Mask = ObjCEncOptions() |
3097 | .setIsOutermostType() |
3098 | .setIsStructField(); |
3099 | return Bits & ~Mask.Bits; |
3100 | } |
3101 | }; |
3102 | |
3103 | // Return the Objective-C type encoding for a given type. |
3104 | void getObjCEncodingForTypeImpl(QualType t, std::string &S, |
3105 | ObjCEncOptions Options, |
3106 | const FieldDecl *Field, |
3107 | QualType *NotEncodedT = nullptr) const; |
3108 | |
3109 | // Adds the encoding of the structure's members. |
3110 | void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, |
3111 | const FieldDecl *Field, |
3112 | bool includeVBases = true, |
3113 | QualType *NotEncodedT=nullptr) const; |
3114 | |
3115 | public: |
3116 | // Adds the encoding of a method parameter or return type. |
3117 | void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, |
3118 | QualType T, std::string& S, |
3119 | bool Extended) const; |
3120 | |
3121 | /// Returns true if this is an inline-initialized static data member |
3122 | /// which is treated as a definition for MSVC compatibility. |
3123 | bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const; |
3124 | |
3125 | enum class InlineVariableDefinitionKind { |
3126 | /// Not an inline variable. |
3127 | None, |
3128 | |
3129 | /// Weak definition of inline variable. |
3130 | Weak, |
3131 | |
3132 | /// Weak for now, might become strong later in this TU. |
3133 | WeakUnknown, |
3134 | |
3135 | /// Strong definition. |
3136 | Strong |
3137 | }; |
3138 | |
3139 | /// Determine whether a definition of this inline variable should |
3140 | /// be treated as a weak or strong definition. For compatibility with |
3141 | /// C++14 and before, for a constexpr static data member, if there is an |
3142 | /// out-of-line declaration of the member, we may promote it from weak to |
3143 | /// strong. |
3144 | InlineVariableDefinitionKind |
3145 | getInlineVariableDefinitionKind(const VarDecl *VD) const; |
3146 | |
3147 | private: |
3148 | friend class DeclarationNameTable; |
3149 | friend class DeclContext; |
3150 | |
3151 | const ASTRecordLayout & |
3152 | getObjCLayout(const ObjCInterfaceDecl *D, |
3153 | const ObjCImplementationDecl *Impl) const; |
3154 | |
3155 | /// A set of deallocations that should be performed when the |
3156 | /// ASTContext is destroyed. |
3157 | // FIXME: We really should have a better mechanism in the ASTContext to |
3158 | // manage running destructors for types which do variable sized allocation |
3159 | // within the AST. In some places we thread the AST bump pointer allocator |
3160 | // into the datastructures which avoids this mess during deallocation but is |
3161 | // wasteful of memory, and here we require a lot of error prone book keeping |
3162 | // in order to track and run destructors while we're tearing things down. |
3163 | using DeallocationFunctionsAndArguments = |
3164 | llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>; |
3165 | mutable DeallocationFunctionsAndArguments Deallocations; |
3166 | |
3167 | // FIXME: This currently contains the set of StoredDeclMaps used |
3168 | // by DeclContext objects. This probably should not be in ASTContext, |
3169 | // but we include it here so that ASTContext can quickly deallocate them. |
3170 | llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM; |
3171 | |
3172 | std::vector<Decl *> TraversalScope; |
3173 | |
3174 | std::unique_ptr<VTableContextBase> VTContext; |
3175 | |
3176 | void ReleaseDeclContextMaps(); |
3177 | |
3178 | public: |
3179 | enum PragmaSectionFlag : unsigned { |
3180 | PSF_None = 0, |
3181 | PSF_Read = 0x1, |
3182 | PSF_Write = 0x2, |
3183 | PSF_Execute = 0x4, |
3184 | PSF_Implicit = 0x8, |
3185 | PSF_ZeroInit = 0x10, |
3186 | PSF_Invalid = 0x80000000U, |
3187 | }; |
3188 | |
3189 | struct SectionInfo { |
3190 | NamedDecl *Decl; |
3191 | SourceLocation PragmaSectionLocation; |
3192 | int SectionFlags; |
3193 | |
3194 | SectionInfo() = default; |
3195 | SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation, |
3196 | int SectionFlags) |
3197 | : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation), |
3198 | SectionFlags(SectionFlags) {} |
3199 | }; |
3200 | |
3201 | llvm::StringMap<SectionInfo> SectionInfos; |
3202 | |
3203 | /// Return a new OMPTraitInfo object owned by this context. |
3204 | OMPTraitInfo &getNewOMPTraitInfo(); |
3205 | |
3206 | /// Whether a C++ static variable may be externalized. |
3207 | bool mayExternalizeStaticVar(const Decl *D) const; |
3208 | |
3209 | /// Whether a C++ static variable should be externalized. |
3210 | bool shouldExternalizeStaticVar(const Decl *D) const; |
3211 | |
3212 | StringRef getCUIDHash() const; |
3213 | |
3214 | void AddSYCLKernelNamingDecl(const CXXRecordDecl *RD); |
3215 | bool IsSYCLKernelNamingDecl(const NamedDecl *RD) const; |
3216 | unsigned GetSYCLKernelNamingIndex(const NamedDecl *RD); |
3217 | /// A SourceLocation to store whether we have evaluated a kernel name already, |
3218 | /// and where it happened. If so, we need to diagnose an illegal use of the |
3219 | /// builtin. |
3220 | llvm::MapVector<const SYCLUniqueStableNameExpr *, std::string> |
3221 | SYCLUniqueStableNameEvaluatedValues; |
3222 | |
3223 | private: |
3224 | /// All OMPTraitInfo objects live in this collection, one per |
3225 | /// `pragma omp [begin] declare variant` directive. |
3226 | SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector; |
3227 | |
3228 | /// A list of the (right now just lambda decls) declarations required to |
3229 | /// name all the SYCL kernels in the translation unit, so that we can get the |
3230 | /// correct kernel name, as well as implement |
3231 | /// __builtin_sycl_unique_stable_name. |
3232 | llvm::DenseMap<const DeclContext *, |
3233 | llvm::SmallPtrSet<const CXXRecordDecl *, 4>> |
3234 | SYCLKernelNamingTypes; |
3235 | std::unique_ptr<ItaniumMangleContext> SYCLKernelFilterContext; |
3236 | void FilterSYCLKernelNamingDecls( |
3237 | const CXXRecordDecl *RD, |
3238 | llvm::SmallVectorImpl<const CXXRecordDecl *> &Decls); |
3239 | }; |
3240 | |
3241 | /// Insertion operator for diagnostics. |
3242 | const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, |
3243 | const ASTContext::SectionInfo &Section); |
3244 | |
3245 | /// Utility function for constructing a nullary selector. |
3246 | inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) { |
3247 | IdentifierInfo* II = &Ctx.Idents.get(name); |
3248 | return Ctx.Selectors.getSelector(0, &II); |
3249 | } |
3250 | |
3251 | /// Utility function for constructing an unary selector. |
3252 | inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) { |
3253 | IdentifierInfo* II = &Ctx.Idents.get(name); |
3254 | return Ctx.Selectors.getSelector(1, &II); |
3255 | } |
3256 | |
3257 | } // namespace clang |
3258 | |
3259 | // operator new and delete aren't allowed inside namespaces. |
3260 | |
3261 | /// Placement new for using the ASTContext's allocator. |
3262 | /// |
3263 | /// This placement form of operator new uses the ASTContext's allocator for |
3264 | /// obtaining memory. |
3265 | /// |
3266 | /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h! |
3267 | /// Any changes here need to also be made there. |
3268 | /// |
3269 | /// We intentionally avoid using a nothrow specification here so that the calls |
3270 | /// to this operator will not perform a null check on the result -- the |
3271 | /// underlying allocator never returns null pointers. |
3272 | /// |
3273 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
3274 | /// @code |
3275 | /// // Default alignment (8) |
3276 | /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); |
3277 | /// // Specific alignment |
3278 | /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); |
3279 | /// @endcode |
3280 | /// Memory allocated through this placement new operator does not need to be |
3281 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
3282 | /// destroyed. Please note that you cannot use delete on the pointer. |
3283 | /// |
3284 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
3285 | /// @param C The ASTContext that provides the allocator. |
3286 | /// @param Alignment The alignment of the allocated memory (if the underlying |
3287 | /// allocator supports it). |
3288 | /// @return The allocated memory. Could be nullptr. |
3289 | inline void *operator new(size_t Bytes, const clang::ASTContext &C, |
3290 | size_t Alignment /* = 8 */) { |
3291 | return C.Allocate(Bytes, Alignment); |
3292 | } |
3293 | |
3294 | /// Placement delete companion to the new above. |
3295 | /// |
3296 | /// This operator is just a companion to the new above. There is no way of |
3297 | /// invoking it directly; see the new operator for more details. This operator |
3298 | /// is called implicitly by the compiler if a placement new expression using |
3299 | /// the ASTContext throws in the object constructor. |
3300 | inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { |
3301 | C.Deallocate(Ptr); |
3302 | } |
3303 | |
3304 | /// This placement form of operator new[] uses the ASTContext's allocator for |
3305 | /// obtaining memory. |
3306 | /// |
3307 | /// We intentionally avoid using a nothrow specification here so that the calls |
3308 | /// to this operator will not perform a null check on the result -- the |
3309 | /// underlying allocator never returns null pointers. |
3310 | /// |
3311 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
3312 | /// @code |
3313 | /// // Default alignment (8) |
3314 | /// char *data = new (Context) char[10]; |
3315 | /// // Specific alignment |
3316 | /// char *data = new (Context, 4) char[10]; |
3317 | /// @endcode |
3318 | /// Memory allocated through this placement new[] operator does not need to be |
3319 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
3320 | /// destroyed. Please note that you cannot use delete on the pointer. |
3321 | /// |
3322 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
3323 | /// @param C The ASTContext that provides the allocator. |
3324 | /// @param Alignment The alignment of the allocated memory (if the underlying |
3325 | /// allocator supports it). |
3326 | /// @return The allocated memory. Could be nullptr. |
3327 | inline void *operator new[](size_t Bytes, const clang::ASTContext& C, |
3328 | size_t Alignment /* = 8 */) { |
3329 | return C.Allocate(Bytes, Alignment); |
3330 | } |
3331 | |
3332 | /// Placement delete[] companion to the new[] above. |
3333 | /// |
3334 | /// This operator is just a companion to the new[] above. There is no way of |
3335 | /// invoking it directly; see the new[] operator for more details. This operator |
3336 | /// is called implicitly by the compiler if a placement new[] expression using |
3337 | /// the ASTContext throws in the object constructor. |
3338 | inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { |
3339 | C.Deallocate(Ptr); |
3340 | } |
3341 | |
3342 | /// Create the representation of a LazyGenerationalUpdatePtr. |
3343 | template <typename Owner, typename T, |
3344 | void (clang::ExternalASTSource::*Update)(Owner)> |
3345 | typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType |
3346 | clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue( |
3347 | const clang::ASTContext &Ctx, T Value) { |
3348 | // Note, this is implemented here so that ExternalASTSource.h doesn't need to |
3349 | // include ASTContext.h. We explicitly instantiate it for all relevant types |
3350 | // in ASTContext.cpp. |
3351 | if (auto *Source = Ctx.getExternalSource()) |
3352 | return new (Ctx) LazyData(Source, Value); |
3353 | return Value; |
3354 | } |
3355 | |
3356 | #endif // LLVM_CLANG_AST_ASTCONTEXT_H |