File: | clang/lib/Sema/SemaExpr.cpp |
Warning: | line 6680, 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/Support/ConvertUTF.h" | ||||
50 | #include "llvm/Support/SaveAndRestore.h" | ||||
51 | using namespace clang; | ||||
52 | using namespace sema; | ||||
53 | using llvm::RoundingMode; | ||||
54 | |||||
55 | /// Determine whether the use of this declaration is valid, without | ||||
56 | /// emitting diagnostics. | ||||
57 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { | ||||
58 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
59 | if (ParsingInitForAutoVars.count(D)) | ||||
60 | return false; | ||||
61 | |||||
62 | // See if this is a deleted function. | ||||
63 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
64 | if (FD->isDeleted()) | ||||
65 | return false; | ||||
66 | |||||
67 | // If the function has a deduced return type, and we can't deduce it, | ||||
68 | // then we can't use it either. | ||||
69 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
70 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) | ||||
71 | return false; | ||||
72 | |||||
73 | // See if this is an aligned allocation/deallocation function that is | ||||
74 | // unavailable. | ||||
75 | if (TreatUnavailableAsInvalid && | ||||
76 | isUnavailableAlignedAllocationFunction(*FD)) | ||||
77 | return false; | ||||
78 | } | ||||
79 | |||||
80 | // See if this function is unavailable. | ||||
81 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && | ||||
82 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) | ||||
83 | return false; | ||||
84 | |||||
85 | return true; | ||||
86 | } | ||||
87 | |||||
88 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { | ||||
89 | // Warn if this is used but marked unused. | ||||
90 | if (const auto *A = D->getAttr<UnusedAttr>()) { | ||||
91 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) | ||||
92 | // should diagnose them. | ||||
93 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && | ||||
94 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { | ||||
95 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); | ||||
96 | if (DC && !DC->hasAttr<UnusedAttr>()) | ||||
97 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D; | ||||
98 | } | ||||
99 | } | ||||
100 | } | ||||
101 | |||||
102 | /// Emit a note explaining that this function is deleted. | ||||
103 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { | ||||
104 | assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void > (0) : __assert_fail ("Decl && Decl->isDeleted()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 104, __PRETTY_FUNCTION__)); | ||||
105 | |||||
106 | if (Decl->isDefaulted()) { | ||||
107 | // If the method was explicitly defaulted, point at that declaration. | ||||
108 | if (!Decl->isImplicit()) | ||||
109 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); | ||||
110 | |||||
111 | // Try to diagnose why this special member function was implicitly | ||||
112 | // deleted. This might fail, if that reason no longer applies. | ||||
113 | DiagnoseDeletedDefaultedFunction(Decl); | ||||
114 | return; | ||||
115 | } | ||||
116 | |||||
117 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); | ||||
118 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
119 | return NoteDeletedInheritingConstructor(Ctor); | ||||
120 | |||||
121 | Diag(Decl->getLocation(), diag::note_availability_specified_here) | ||||
122 | << Decl << 1; | ||||
123 | } | ||||
124 | |||||
125 | /// Determine whether a FunctionDecl was ever declared with an | ||||
126 | /// explicit storage class. | ||||
127 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { | ||||
128 | for (auto I : D->redecls()) { | ||||
129 | if (I->getStorageClass() != SC_None) | ||||
130 | return true; | ||||
131 | } | ||||
132 | return false; | ||||
133 | } | ||||
134 | |||||
135 | /// Check whether we're in an extern inline function and referring to a | ||||
136 | /// variable or function with internal linkage (C11 6.7.4p3). | ||||
137 | /// | ||||
138 | /// This is only a warning because we used to silently accept this code, but | ||||
139 | /// in many cases it will not behave correctly. This is not enabled in C++ mode | ||||
140 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) | ||||
141 | /// and so while there may still be user mistakes, most of the time we can't | ||||
142 | /// prove that there are errors. | ||||
143 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, | ||||
144 | const NamedDecl *D, | ||||
145 | SourceLocation Loc) { | ||||
146 | // This is disabled under C++; there are too many ways for this to fire in | ||||
147 | // contexts where the warning is a false positive, or where it is technically | ||||
148 | // correct but benign. | ||||
149 | if (S.getLangOpts().CPlusPlus) | ||||
150 | return; | ||||
151 | |||||
152 | // Check if this is an inlined function or method. | ||||
153 | FunctionDecl *Current = S.getCurFunctionDecl(); | ||||
154 | if (!Current) | ||||
155 | return; | ||||
156 | if (!Current->isInlined()) | ||||
157 | return; | ||||
158 | if (!Current->isExternallyVisible()) | ||||
159 | return; | ||||
160 | |||||
161 | // Check if the decl has internal linkage. | ||||
162 | if (D->getFormalLinkage() != InternalLinkage) | ||||
163 | return; | ||||
164 | |||||
165 | // Downgrade from ExtWarn to Extension if | ||||
166 | // (1) the supposedly external inline function is in the main file, | ||||
167 | // and probably won't be included anywhere else. | ||||
168 | // (2) the thing we're referencing is a pure function. | ||||
169 | // (3) the thing we're referencing is another inline function. | ||||
170 | // This last can give us false negatives, but it's better than warning on | ||||
171 | // wrappers for simple C library functions. | ||||
172 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); | ||||
173 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); | ||||
174 | if (!DowngradeWarning && UsedFn) | ||||
175 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); | ||||
176 | |||||
177 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet | ||||
178 | : diag::ext_internal_in_extern_inline) | ||||
179 | << /*IsVar=*/!UsedFn << D; | ||||
180 | |||||
181 | S.MaybeSuggestAddingStaticToDecl(Current); | ||||
182 | |||||
183 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) | ||||
184 | << D; | ||||
185 | } | ||||
186 | |||||
187 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { | ||||
188 | const FunctionDecl *First = Cur->getFirstDecl(); | ||||
189 | |||||
190 | // Suggest "static" on the function, if possible. | ||||
191 | if (!hasAnyExplicitStorageClass(First)) { | ||||
192 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); | ||||
193 | Diag(DeclBegin, diag::note_convert_inline_to_static) | ||||
194 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); | ||||
195 | } | ||||
196 | } | ||||
197 | |||||
198 | /// Determine whether the use of this declaration is valid, and | ||||
199 | /// emit any corresponding diagnostics. | ||||
200 | /// | ||||
201 | /// This routine diagnoses various problems with referencing | ||||
202 | /// declarations that can occur when using a declaration. For example, | ||||
203 | /// it might warn if a deprecated or unavailable declaration is being | ||||
204 | /// used, or produce an error (and return true) if a C++0x deleted | ||||
205 | /// function is being used. | ||||
206 | /// | ||||
207 | /// \returns true if there was an error (this declaration cannot be | ||||
208 | /// referenced), false otherwise. | ||||
209 | /// | ||||
210 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | ||||
211 | const ObjCInterfaceDecl *UnknownObjCClass, | ||||
212 | bool ObjCPropertyAccess, | ||||
213 | bool AvoidPartialAvailabilityChecks, | ||||
214 | ObjCInterfaceDecl *ClassReceiver) { | ||||
215 | SourceLocation Loc = Locs.front(); | ||||
216 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { | ||||
217 | // If there were any diagnostics suppressed by template argument deduction, | ||||
218 | // emit them now. | ||||
219 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); | ||||
220 | if (Pos != SuppressedDiagnostics.end()) { | ||||
221 | for (const PartialDiagnosticAt &Suppressed : Pos->second) | ||||
222 | Diag(Suppressed.first, Suppressed.second); | ||||
223 | |||||
224 | // Clear out the list of suppressed diagnostics, so that we don't emit | ||||
225 | // them again for this specialization. However, we don't obsolete this | ||||
226 | // entry from the table, because we want to avoid ever emitting these | ||||
227 | // diagnostics again. | ||||
228 | Pos->second.clear(); | ||||
229 | } | ||||
230 | |||||
231 | // C++ [basic.start.main]p3: | ||||
232 | // The function 'main' shall not be used within a program. | ||||
233 | if (cast<FunctionDecl>(D)->isMain()) | ||||
234 | Diag(Loc, diag::ext_main_used); | ||||
235 | |||||
236 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); | ||||
237 | } | ||||
238 | |||||
239 | // See if this is an auto-typed variable whose initializer we are parsing. | ||||
240 | if (ParsingInitForAutoVars.count(D)) { | ||||
241 | if (isa<BindingDecl>(D)) { | ||||
242 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) | ||||
243 | << D->getDeclName(); | ||||
244 | } else { | ||||
245 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) | ||||
246 | << D->getDeclName() << cast<VarDecl>(D)->getType(); | ||||
247 | } | ||||
248 | return true; | ||||
249 | } | ||||
250 | |||||
251 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
252 | // See if this is a deleted function. | ||||
253 | if (FD->isDeleted()) { | ||||
254 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); | ||||
255 | if (Ctor && Ctor->isInheritingConstructor()) | ||||
256 | Diag(Loc, diag::err_deleted_inherited_ctor_use) | ||||
257 | << Ctor->getParent() | ||||
258 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); | ||||
259 | else | ||||
260 | Diag(Loc, diag::err_deleted_function_use); | ||||
261 | NoteDeletedFunction(FD); | ||||
262 | return true; | ||||
263 | } | ||||
264 | |||||
265 | // [expr.prim.id]p4 | ||||
266 | // A program that refers explicitly or implicitly to a function with a | ||||
267 | // trailing requires-clause whose constraint-expression is not satisfied, | ||||
268 | // other than to declare it, is ill-formed. [...] | ||||
269 | // | ||||
270 | // See if this is a function with constraints that need to be satisfied. | ||||
271 | // Check this before deducing the return type, as it might instantiate the | ||||
272 | // definition. | ||||
273 | if (FD->getTrailingRequiresClause()) { | ||||
274 | ConstraintSatisfaction Satisfaction; | ||||
275 | if (CheckFunctionConstraints(FD, Satisfaction, Loc)) | ||||
276 | // A diagnostic will have already been generated (non-constant | ||||
277 | // constraint expression, for example) | ||||
278 | return true; | ||||
279 | if (!Satisfaction.IsSatisfied) { | ||||
280 | Diag(Loc, | ||||
281 | diag::err_reference_to_function_with_unsatisfied_constraints) | ||||
282 | << D; | ||||
283 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
284 | return true; | ||||
285 | } | ||||
286 | } | ||||
287 | |||||
288 | // If the function has a deduced return type, and we can't deduce it, | ||||
289 | // then we can't use it either. | ||||
290 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | ||||
291 | DeduceReturnType(FD, Loc)) | ||||
292 | return true; | ||||
293 | |||||
294 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) | ||||
295 | return true; | ||||
296 | |||||
297 | if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) | ||||
298 | return true; | ||||
299 | } | ||||
300 | |||||
301 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
302 | // Lambdas are only default-constructible or assignable in C++2a onwards. | ||||
303 | if (MD->getParent()->isLambda() && | ||||
304 | ((isa<CXXConstructorDecl>(MD) && | ||||
305 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || | ||||
306 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { | ||||
307 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) | ||||
308 | << !isa<CXXConstructorDecl>(MD); | ||||
309 | } | ||||
310 | } | ||||
311 | |||||
312 | auto getReferencedObjCProp = [](const NamedDecl *D) -> | ||||
313 | const ObjCPropertyDecl * { | ||||
314 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) | ||||
315 | return MD->findPropertyDecl(); | ||||
316 | return nullptr; | ||||
317 | }; | ||||
318 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { | ||||
319 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) | ||||
320 | return true; | ||||
321 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { | ||||
322 | return true; | ||||
323 | } | ||||
324 | |||||
325 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions | ||||
326 | // Only the variables omp_in and omp_out are allowed in the combiner. | ||||
327 | // Only the variables omp_priv and omp_orig are allowed in the | ||||
328 | // initializer-clause. | ||||
329 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); | ||||
330 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && | ||||
331 | isa<VarDecl>(D)) { | ||||
332 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) | ||||
333 | << getCurFunction()->HasOMPDeclareReductionCombiner; | ||||
334 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
335 | return true; | ||||
336 | } | ||||
337 | |||||
338 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions | ||||
339 | // List-items in map clauses on this construct may only refer to the declared | ||||
340 | // variable var and entities that could be referenced by a procedure defined | ||||
341 | // at the same location | ||||
342 | if (LangOpts.OpenMP && isa<VarDecl>(D) && | ||||
343 | !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { | ||||
344 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) | ||||
345 | << getOpenMPDeclareMapperVarName(); | ||||
346 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
347 | return true; | ||||
348 | } | ||||
349 | |||||
350 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, | ||||
351 | AvoidPartialAvailabilityChecks, ClassReceiver); | ||||
352 | |||||
353 | DiagnoseUnusedOfDecl(*this, D, Loc); | ||||
354 | |||||
355 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); | ||||
356 | |||||
357 | // CUDA/HIP: Diagnose invalid references of host global variables in device | ||||
358 | // functions. Reference of device global variables in host functions is | ||||
359 | // allowed through shadow variables therefore it is not diagnosed. | ||||
360 | if (LangOpts.CUDAIsDevice) { | ||||
361 | auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); | ||||
362 | auto Target = IdentifyCUDATarget(FD); | ||||
363 | if (FD && Target != CFT_Host) { | ||||
364 | const auto *VD = dyn_cast<VarDecl>(D); | ||||
365 | if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && | ||||
366 | !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && | ||||
367 | !VD->getType()->isCUDADeviceBuiltinSurfaceType() && | ||||
368 | !VD->getType()->isCUDADeviceBuiltinTextureType() && | ||||
369 | !VD->isConstexpr() && !VD->getType().isConstQualified()) | ||||
370 | targetDiag(*Locs.begin(), diag::err_ref_bad_target) | ||||
371 | << /*host*/ 2 << /*variable*/ 1 << VD << Target; | ||||
372 | } | ||||
373 | } | ||||
374 | |||||
375 | if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { | ||||
376 | if (auto *VD = dyn_cast<ValueDecl>(D)) | ||||
377 | checkDeviceDecl(VD, Loc); | ||||
378 | |||||
379 | if (!Context.getTargetInfo().isTLSSupported()) | ||||
380 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
381 | if (VD->getTLSKind() != VarDecl::TLS_None) | ||||
382 | targetDiag(*Locs.begin(), diag::err_thread_unsupported); | ||||
383 | } | ||||
384 | |||||
385 | if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && | ||||
386 | !isUnevaluatedContext()) { | ||||
387 | // C++ [expr.prim.req.nested] p3 | ||||
388 | // A local parameter shall only appear as an unevaluated operand | ||||
389 | // (Clause 8) within the constraint-expression. | ||||
390 | Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) | ||||
391 | << D; | ||||
392 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; | ||||
393 | return true; | ||||
394 | } | ||||
395 | |||||
396 | return false; | ||||
397 | } | ||||
398 | |||||
399 | /// DiagnoseSentinelCalls - This routine checks whether a call or | ||||
400 | /// message-send is to a declaration with the sentinel attribute, and | ||||
401 | /// if so, it checks that the requirements of the sentinel are | ||||
402 | /// satisfied. | ||||
403 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | ||||
404 | ArrayRef<Expr *> Args) { | ||||
405 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); | ||||
406 | if (!attr) | ||||
407 | return; | ||||
408 | |||||
409 | // The number of formal parameters of the declaration. | ||||
410 | unsigned numFormalParams; | ||||
411 | |||||
412 | // The kind of declaration. This is also an index into a %select in | ||||
413 | // the diagnostic. | ||||
414 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; | ||||
415 | |||||
416 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { | ||||
417 | numFormalParams = MD->param_size(); | ||||
418 | calleeType = CT_Method; | ||||
419 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
420 | numFormalParams = FD->param_size(); | ||||
421 | calleeType = CT_Function; | ||||
422 | } else if (isa<VarDecl>(D)) { | ||||
423 | QualType type = cast<ValueDecl>(D)->getType(); | ||||
424 | const FunctionType *fn = nullptr; | ||||
425 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
426 | fn = ptr->getPointeeType()->getAs<FunctionType>(); | ||||
427 | if (!fn) return; | ||||
428 | calleeType = CT_Function; | ||||
429 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { | ||||
430 | fn = ptr->getPointeeType()->castAs<FunctionType>(); | ||||
431 | calleeType = CT_Block; | ||||
432 | } else { | ||||
433 | return; | ||||
434 | } | ||||
435 | |||||
436 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { | ||||
437 | numFormalParams = proto->getNumParams(); | ||||
438 | } else { | ||||
439 | numFormalParams = 0; | ||||
440 | } | ||||
441 | } else { | ||||
442 | return; | ||||
443 | } | ||||
444 | |||||
445 | // "nullPos" is the number of formal parameters at the end which | ||||
446 | // effectively count as part of the variadic arguments. This is | ||||
447 | // useful if you would prefer to not have *any* formal parameters, | ||||
448 | // but the language forces you to have at least one. | ||||
449 | unsigned nullPos = attr->getNullPos(); | ||||
450 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 450, __PRETTY_FUNCTION__)); | ||||
451 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); | ||||
452 | |||||
453 | // The number of arguments which should follow the sentinel. | ||||
454 | unsigned numArgsAfterSentinel = attr->getSentinel(); | ||||
455 | |||||
456 | // If there aren't enough arguments for all the formal parameters, | ||||
457 | // the sentinel, and the args after the sentinel, complain. | ||||
458 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { | ||||
459 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); | ||||
460 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
461 | return; | ||||
462 | } | ||||
463 | |||||
464 | // Otherwise, find the sentinel expression. | ||||
465 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; | ||||
466 | if (!sentinelExpr) return; | ||||
467 | if (sentinelExpr->isValueDependent()) return; | ||||
468 | if (Context.isSentinelNullExpr(sentinelExpr)) return; | ||||
469 | |||||
470 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', | ||||
471 | // or 'NULL' if those are actually defined in the context. Only use | ||||
472 | // 'nil' for ObjC methods, where it's much more likely that the | ||||
473 | // variadic arguments form a list of object pointers. | ||||
474 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); | ||||
475 | std::string NullValue; | ||||
476 | if (calleeType == CT_Method && PP.isMacroDefined("nil")) | ||||
477 | NullValue = "nil"; | ||||
478 | else if (getLangOpts().CPlusPlus11) | ||||
479 | NullValue = "nullptr"; | ||||
480 | else if (PP.isMacroDefined("NULL")) | ||||
481 | NullValue = "NULL"; | ||||
482 | else | ||||
483 | NullValue = "(void*) 0"; | ||||
484 | |||||
485 | if (MissingNilLoc.isInvalid()) | ||||
486 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); | ||||
487 | else | ||||
488 | Diag(MissingNilLoc, diag::warn_missing_sentinel) | ||||
489 | << int(calleeType) | ||||
490 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); | ||||
491 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); | ||||
492 | } | ||||
493 | |||||
494 | SourceRange Sema::getExprRange(Expr *E) const { | ||||
495 | return E ? E->getSourceRange() : SourceRange(); | ||||
496 | } | ||||
497 | |||||
498 | //===----------------------------------------------------------------------===// | ||||
499 | // Standard Promotions and Conversions | ||||
500 | //===----------------------------------------------------------------------===// | ||||
501 | |||||
502 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). | ||||
503 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { | ||||
504 | // Handle any placeholder expressions which made it here. | ||||
505 | if (E->getType()->isPlaceholderType()) { | ||||
506 | ExprResult result = CheckPlaceholderExpr(E); | ||||
507 | if (result.isInvalid()) return ExprError(); | ||||
508 | E = result.get(); | ||||
509 | } | ||||
510 | |||||
511 | QualType Ty = E->getType(); | ||||
512 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 512, __PRETTY_FUNCTION__)); | ||||
513 | |||||
514 | if (Ty->isFunctionType()) { | ||||
515 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) | ||||
516 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | ||||
517 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) | ||||
518 | return ExprError(); | ||||
519 | |||||
520 | E = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
521 | CK_FunctionToPointerDecay).get(); | ||||
522 | } else if (Ty->isArrayType()) { | ||||
523 | // In C90 mode, arrays only promote to pointers if the array expression is | ||||
524 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has | ||||
525 | // type 'array of type' is converted to an expression that has type 'pointer | ||||
526 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression | ||||
527 | // that has type 'array of type' ...". The relevant change is "an lvalue" | ||||
528 | // (C90) to "an expression" (C99). | ||||
529 | // | ||||
530 | // C++ 4.2p1: | ||||
531 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of | ||||
532 | // T" can be converted to an rvalue of type "pointer to T". | ||||
533 | // | ||||
534 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) | ||||
535 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), | ||||
536 | CK_ArrayToPointerDecay).get(); | ||||
537 | } | ||||
538 | return E; | ||||
539 | } | ||||
540 | |||||
541 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { | ||||
542 | // Check to see if we are dereferencing a null pointer. If so, | ||||
543 | // and if not volatile-qualified, this is undefined behavior that the | ||||
544 | // optimizer will delete, so warn about it. People sometimes try to use this | ||||
545 | // to get a deterministic trap and are surprised by clang's behavior. This | ||||
546 | // only handles the pattern "*null", which is a very syntactic check. | ||||
547 | const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); | ||||
548 | if (UO && UO->getOpcode() == UO_Deref && | ||||
549 | UO->getSubExpr()->getType()->isPointerType()) { | ||||
550 | const LangAS AS = | ||||
551 | UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); | ||||
552 | if ((!isTargetAddressSpace(AS) || | ||||
553 | (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && | ||||
554 | UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( | ||||
555 | S.Context, Expr::NPC_ValueDependentIsNotNull) && | ||||
556 | !UO->getType().isVolatileQualified()) { | ||||
557 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
558 | S.PDiag(diag::warn_indirection_through_null) | ||||
559 | << UO->getSubExpr()->getSourceRange()); | ||||
560 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||
561 | S.PDiag(diag::note_indirection_through_null)); | ||||
562 | } | ||||
563 | } | ||||
564 | } | ||||
565 | |||||
566 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, | ||||
567 | SourceLocation AssignLoc, | ||||
568 | const Expr* RHS) { | ||||
569 | const ObjCIvarDecl *IV = OIRE->getDecl(); | ||||
570 | if (!IV) | ||||
571 | return; | ||||
572 | |||||
573 | DeclarationName MemberName = IV->getDeclName(); | ||||
574 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); | ||||
575 | if (!Member || !Member->isStr("isa")) | ||||
576 | return; | ||||
577 | |||||
578 | const Expr *Base = OIRE->getBase(); | ||||
579 | QualType BaseType = Base->getType(); | ||||
580 | if (OIRE->isArrow()) | ||||
581 | BaseType = BaseType->getPointeeType(); | ||||
582 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) | ||||
583 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { | ||||
584 | ObjCInterfaceDecl *ClassDeclared = nullptr; | ||||
585 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); | ||||
586 | if (!ClassDeclared->getSuperClass() | ||||
587 | && (*ClassDeclared->ivar_begin()) == IV) { | ||||
588 | if (RHS) { | ||||
589 | NamedDecl *ObjectSetClass = | ||||
590 | S.LookupSingleName(S.TUScope, | ||||
591 | &S.Context.Idents.get("object_setClass"), | ||||
592 | SourceLocation(), S.LookupOrdinaryName); | ||||
593 | if (ObjectSetClass) { | ||||
594 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); | ||||
595 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) | ||||
596 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
597 | "object_setClass(") | ||||
598 | << FixItHint::CreateReplacement( | ||||
599 | SourceRange(OIRE->getOpLoc(), AssignLoc), ",") | ||||
600 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
601 | } | ||||
602 | else | ||||
603 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); | ||||
604 | } else { | ||||
605 | NamedDecl *ObjectGetClass = | ||||
606 | S.LookupSingleName(S.TUScope, | ||||
607 | &S.Context.Idents.get("object_getClass"), | ||||
608 | SourceLocation(), S.LookupOrdinaryName); | ||||
609 | if (ObjectGetClass) | ||||
610 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) | ||||
611 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), | ||||
612 | "object_getClass(") | ||||
613 | << FixItHint::CreateReplacement( | ||||
614 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); | ||||
615 | else | ||||
616 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); | ||||
617 | } | ||||
618 | S.Diag(IV->getLocation(), diag::note_ivar_decl); | ||||
619 | } | ||||
620 | } | ||||
621 | } | ||||
622 | |||||
623 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { | ||||
624 | // Handle any placeholder expressions which made it here. | ||||
625 | if (E->getType()->isPlaceholderType()) { | ||||
626 | ExprResult result = CheckPlaceholderExpr(E); | ||||
627 | if (result.isInvalid()) return ExprError(); | ||||
628 | E = result.get(); | ||||
629 | } | ||||
630 | |||||
631 | // C++ [conv.lval]p1: | ||||
632 | // A glvalue of a non-function, non-array type T can be | ||||
633 | // converted to a prvalue. | ||||
634 | if (!E->isGLValue()) return E; | ||||
635 | |||||
636 | QualType T = E->getType(); | ||||
637 | assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 637, __PRETTY_FUNCTION__)); | ||||
638 | |||||
639 | // lvalue-to-rvalue conversion cannot be applied to function or array types. | ||||
640 | if (T->isFunctionType() || T->isArrayType()) | ||||
641 | return E; | ||||
642 | |||||
643 | // We don't want to throw lvalue-to-rvalue casts on top of | ||||
644 | // expressions of certain types in C++. | ||||
645 | if (getLangOpts().CPlusPlus && | ||||
646 | (E->getType() == Context.OverloadTy || | ||||
647 | T->isDependentType() || | ||||
648 | T->isRecordType())) | ||||
649 | return E; | ||||
650 | |||||
651 | // The C standard is actually really unclear on this point, and | ||||
652 | // DR106 tells us what the result should be but not why. It's | ||||
653 | // generally best to say that void types just doesn't undergo | ||||
654 | // lvalue-to-rvalue at all. Note that expressions of unqualified | ||||
655 | // 'void' type are never l-values, but qualified void can be. | ||||
656 | if (T->isVoidType()) | ||||
657 | return E; | ||||
658 | |||||
659 | // OpenCL usually rejects direct accesses to values of 'half' type. | ||||
660 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | ||||
661 | T->isHalfType()) { | ||||
662 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) | ||||
663 | << 0 << T; | ||||
664 | return ExprError(); | ||||
665 | } | ||||
666 | |||||
667 | CheckForNullPointerDereference(*this, E); | ||||
668 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { | ||||
669 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, | ||||
670 | &Context.Idents.get("object_getClass"), | ||||
671 | SourceLocation(), LookupOrdinaryName); | ||||
672 | if (ObjectGetClass) | ||||
673 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) | ||||
674 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") | ||||
675 | << FixItHint::CreateReplacement( | ||||
676 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); | ||||
677 | else | ||||
678 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); | ||||
679 | } | ||||
680 | else if (const ObjCIvarRefExpr *OIRE = | ||||
681 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) | ||||
682 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); | ||||
683 | |||||
684 | // C++ [conv.lval]p1: | ||||
685 | // [...] If T is a non-class type, the type of the prvalue is the | ||||
686 | // cv-unqualified version of T. Otherwise, the type of the | ||||
687 | // rvalue is T. | ||||
688 | // | ||||
689 | // C99 6.3.2.1p2: | ||||
690 | // If the lvalue has qualified type, the value has the unqualified | ||||
691 | // version of the type of the lvalue; otherwise, the value has the | ||||
692 | // type of the lvalue. | ||||
693 | if (T.hasQualifiers()) | ||||
694 | T = T.getUnqualifiedType(); | ||||
695 | |||||
696 | // Under the MS ABI, lock down the inheritance model now. | ||||
697 | if (T->isMemberPointerType() && | ||||
698 | Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
699 | (void)isCompleteType(E->getExprLoc(), T); | ||||
700 | |||||
701 | ExprResult Res = CheckLValueToRValueConversionOperand(E); | ||||
702 | if (Res.isInvalid()) | ||||
703 | return Res; | ||||
704 | E = Res.get(); | ||||
705 | |||||
706 | // Loading a __weak object implicitly retains the value, so we need a cleanup to | ||||
707 | // balance that. | ||||
708 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
709 | Cleanup.setExprNeedsCleanups(true); | ||||
710 | |||||
711 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
712 | Cleanup.setExprNeedsCleanups(true); | ||||
713 | |||||
714 | // C++ [conv.lval]p3: | ||||
715 | // If T is cv std::nullptr_t, the result is a null pointer constant. | ||||
716 | CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; | ||||
717 | Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, | ||||
718 | CurFPFeatureOverrides()); | ||||
719 | |||||
720 | // C11 6.3.2.1p2: | ||||
721 | // ... if the lvalue has atomic type, the value has the non-atomic version | ||||
722 | // of the type of the lvalue ... | ||||
723 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { | ||||
724 | T = Atomic->getValueType().getUnqualifiedType(); | ||||
725 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), | ||||
726 | nullptr, VK_RValue, FPOptionsOverride()); | ||||
727 | } | ||||
728 | |||||
729 | return Res; | ||||
730 | } | ||||
731 | |||||
732 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { | ||||
733 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); | ||||
734 | if (Res.isInvalid()) | ||||
735 | return ExprError(); | ||||
736 | Res = DefaultLvalueConversion(Res.get()); | ||||
737 | if (Res.isInvalid()) | ||||
738 | return ExprError(); | ||||
739 | return Res; | ||||
740 | } | ||||
741 | |||||
742 | /// CallExprUnaryConversions - a special case of an unary conversion | ||||
743 | /// performed on a function designator of a call expression. | ||||
744 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { | ||||
745 | QualType Ty = E->getType(); | ||||
746 | ExprResult Res = E; | ||||
747 | // Only do implicit cast for a function type, but not for a pointer | ||||
748 | // to function type. | ||||
749 | if (Ty->isFunctionType()) { | ||||
750 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), | ||||
751 | CK_FunctionToPointerDecay); | ||||
752 | if (Res.isInvalid()) | ||||
753 | return ExprError(); | ||||
754 | } | ||||
755 | Res = DefaultLvalueConversion(Res.get()); | ||||
756 | if (Res.isInvalid()) | ||||
757 | return ExprError(); | ||||
758 | return Res.get(); | ||||
759 | } | ||||
760 | |||||
761 | /// UsualUnaryConversions - Performs various conversions that are common to most | ||||
762 | /// operators (C99 6.3). The conversions of array and function types are | ||||
763 | /// sometimes suppressed. For example, the array->pointer conversion doesn't | ||||
764 | /// apply if the array is an argument to the sizeof or address (&) operators. | ||||
765 | /// In these instances, this routine should *not* be called. | ||||
766 | ExprResult Sema::UsualUnaryConversions(Expr *E) { | ||||
767 | // First, convert to an r-value. | ||||
768 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | ||||
769 | if (Res.isInvalid()) | ||||
770 | return ExprError(); | ||||
771 | E = Res.get(); | ||||
772 | |||||
773 | QualType Ty = E->getType(); | ||||
774 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 774, __PRETTY_FUNCTION__)); | ||||
775 | |||||
776 | // Half FP have to be promoted to float unless it is natively supported | ||||
777 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) | ||||
778 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); | ||||
779 | |||||
780 | // Try to perform integral promotions if the object has a theoretically | ||||
781 | // promotable type. | ||||
782 | if (Ty->isIntegralOrUnscopedEnumerationType()) { | ||||
783 | // C99 6.3.1.1p2: | ||||
784 | // | ||||
785 | // The following may be used in an expression wherever an int or | ||||
786 | // unsigned int may be used: | ||||
787 | // - an object or expression with an integer type whose integer | ||||
788 | // conversion rank is less than or equal to the rank of int | ||||
789 | // and unsigned int. | ||||
790 | // - A bit-field of type _Bool, int, signed int, or unsigned int. | ||||
791 | // | ||||
792 | // If an int can represent all values of the original type, the | ||||
793 | // value is converted to an int; otherwise, it is converted to an | ||||
794 | // unsigned int. These are called the integer promotions. All | ||||
795 | // other types are unchanged by the integer promotions. | ||||
796 | |||||
797 | QualType PTy = Context.isPromotableBitField(E); | ||||
798 | if (!PTy.isNull()) { | ||||
799 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); | ||||
800 | return E; | ||||
801 | } | ||||
802 | if (Ty->isPromotableIntegerType()) { | ||||
803 | QualType PT = Context.getPromotedIntegerType(Ty); | ||||
804 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); | ||||
805 | return E; | ||||
806 | } | ||||
807 | } | ||||
808 | return E; | ||||
809 | } | ||||
810 | |||||
811 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | ||||
812 | /// do not have a prototype. Arguments that have type float or __fp16 | ||||
813 | /// are promoted to double. All other argument types are converted by | ||||
814 | /// UsualUnaryConversions(). | ||||
815 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { | ||||
816 | QualType Ty = E->getType(); | ||||
817 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type" ) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 817, __PRETTY_FUNCTION__)); | ||||
818 | |||||
819 | ExprResult Res = UsualUnaryConversions(E); | ||||
820 | if (Res.isInvalid()) | ||||
821 | return ExprError(); | ||||
822 | E = Res.get(); | ||||
823 | |||||
824 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) | ||||
825 | // promote to double. | ||||
826 | // Note that default argument promotion applies only to float (and | ||||
827 | // half/fp16); it does not apply to _Float16. | ||||
828 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
829 | if (BTy && (BTy->getKind() == BuiltinType::Half || | ||||
830 | BTy->getKind() == BuiltinType::Float)) { | ||||
831 | if (getLangOpts().OpenCL && | ||||
832 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||
833 | if (BTy->getKind() == BuiltinType::Half) { | ||||
834 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); | ||||
835 | } | ||||
836 | } else { | ||||
837 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); | ||||
838 | } | ||||
839 | } | ||||
840 | |||||
841 | // C++ performs lvalue-to-rvalue conversion as a default argument | ||||
842 | // promotion, even on class types, but note: | ||||
843 | // C++11 [conv.lval]p2: | ||||
844 | // When an lvalue-to-rvalue conversion occurs in an unevaluated | ||||
845 | // operand or a subexpression thereof the value contained in the | ||||
846 | // referenced object is not accessed. Otherwise, if the glvalue | ||||
847 | // has a class type, the conversion copy-initializes a temporary | ||||
848 | // of type T from the glvalue and the result of the conversion | ||||
849 | // is a prvalue for the temporary. | ||||
850 | // FIXME: add some way to gate this entire thing for correctness in | ||||
851 | // potentially potentially evaluated contexts. | ||||
852 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { | ||||
853 | ExprResult Temp = PerformCopyInitialization( | ||||
854 | InitializedEntity::InitializeTemporary(E->getType()), | ||||
855 | E->getExprLoc(), E); | ||||
856 | if (Temp.isInvalid()) | ||||
857 | return ExprError(); | ||||
858 | E = Temp.get(); | ||||
859 | } | ||||
860 | |||||
861 | return E; | ||||
862 | } | ||||
863 | |||||
864 | /// Determine the degree of POD-ness for an expression. | ||||
865 | /// Incomplete types are considered POD, since this check can be performed | ||||
866 | /// when we're in an unevaluated context. | ||||
867 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { | ||||
868 | if (Ty->isIncompleteType()) { | ||||
869 | // C++11 [expr.call]p7: | ||||
870 | // After these conversions, if the argument does not have arithmetic, | ||||
871 | // enumeration, pointer, pointer to member, or class type, the program | ||||
872 | // is ill-formed. | ||||
873 | // | ||||
874 | // Since we've already performed array-to-pointer and function-to-pointer | ||||
875 | // decay, the only such type in C++ is cv void. This also handles | ||||
876 | // initializer lists as variadic arguments. | ||||
877 | if (Ty->isVoidType()) | ||||
878 | return VAK_Invalid; | ||||
879 | |||||
880 | if (Ty->isObjCObjectType()) | ||||
881 | return VAK_Invalid; | ||||
882 | return VAK_Valid; | ||||
883 | } | ||||
884 | |||||
885 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
886 | return VAK_Invalid; | ||||
887 | |||||
888 | if (Ty.isCXX98PODType(Context)) | ||||
889 | return VAK_Valid; | ||||
890 | |||||
891 | // C++11 [expr.call]p7: | ||||
892 | // Passing a potentially-evaluated argument of class type (Clause 9) | ||||
893 | // having a non-trivial copy constructor, a non-trivial move constructor, | ||||
894 | // or a non-trivial destructor, with no corresponding parameter, | ||||
895 | // is conditionally-supported with implementation-defined semantics. | ||||
896 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) | ||||
897 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) | ||||
898 | if (!Record->hasNonTrivialCopyConstructor() && | ||||
899 | !Record->hasNonTrivialMoveConstructor() && | ||||
900 | !Record->hasNonTrivialDestructor()) | ||||
901 | return VAK_ValidInCXX11; | ||||
902 | |||||
903 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) | ||||
904 | return VAK_Valid; | ||||
905 | |||||
906 | if (Ty->isObjCObjectType()) | ||||
907 | return VAK_Invalid; | ||||
908 | |||||
909 | if (getLangOpts().MSVCCompat) | ||||
910 | return VAK_MSVCUndefined; | ||||
911 | |||||
912 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're | ||||
913 | // permitted to reject them. We should consider doing so. | ||||
914 | return VAK_Undefined; | ||||
915 | } | ||||
916 | |||||
917 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { | ||||
918 | // Don't allow one to pass an Objective-C interface to a vararg. | ||||
919 | const QualType &Ty = E->getType(); | ||||
920 | VarArgKind VAK = isValidVarArgType(Ty); | ||||
921 | |||||
922 | // Complain about passing non-POD types through varargs. | ||||
923 | switch (VAK) { | ||||
924 | case VAK_ValidInCXX11: | ||||
925 | DiagRuntimeBehavior( | ||||
926 | E->getBeginLoc(), nullptr, | ||||
927 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); | ||||
928 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
929 | case VAK_Valid: | ||||
930 | if (Ty->isRecordType()) { | ||||
931 | // This is unlikely to be what the user intended. If the class has a | ||||
932 | // 'c_str' member function, the user probably meant to call that. | ||||
933 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
934 | PDiag(diag::warn_pass_class_arg_to_vararg) | ||||
935 | << Ty << CT << hasCStrMethod(E) << ".c_str()"); | ||||
936 | } | ||||
937 | break; | ||||
938 | |||||
939 | case VAK_Undefined: | ||||
940 | case VAK_MSVCUndefined: | ||||
941 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
942 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) | ||||
943 | << getLangOpts().CPlusPlus11 << Ty << CT); | ||||
944 | break; | ||||
945 | |||||
946 | case VAK_Invalid: | ||||
947 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
948 | Diag(E->getBeginLoc(), | ||||
949 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) | ||||
950 | << Ty << CT; | ||||
951 | else if (Ty->isObjCObjectType()) | ||||
952 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, | ||||
953 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) | ||||
954 | << Ty << CT); | ||||
955 | else | ||||
956 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) | ||||
957 | << isa<InitListExpr>(E) << Ty << CT; | ||||
958 | break; | ||||
959 | } | ||||
960 | } | ||||
961 | |||||
962 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | ||||
963 | /// will create a trap if the resulting type is not a POD type. | ||||
964 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | ||||
965 | FunctionDecl *FDecl) { | ||||
966 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { | ||||
967 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
968 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && | ||||
969 | (CT == VariadicMethod || | ||||
970 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { | ||||
971 | E = stripARCUnbridgedCast(E); | ||||
972 | |||||
973 | // Otherwise, do normal placeholder checking. | ||||
974 | } else { | ||||
975 | ExprResult ExprRes = CheckPlaceholderExpr(E); | ||||
976 | if (ExprRes.isInvalid()) | ||||
977 | return ExprError(); | ||||
978 | E = ExprRes.get(); | ||||
979 | } | ||||
980 | } | ||||
981 | |||||
982 | ExprResult ExprRes = DefaultArgumentPromotion(E); | ||||
983 | if (ExprRes.isInvalid()) | ||||
984 | return ExprError(); | ||||
985 | |||||
986 | // Copy blocks to the heap. | ||||
987 | if (ExprRes.get()->getType()->isBlockPointerType()) | ||||
988 | maybeExtendBlockObject(ExprRes); | ||||
989 | |||||
990 | E = ExprRes.get(); | ||||
991 | |||||
992 | // Diagnostics regarding non-POD argument types are | ||||
993 | // emitted along with format string checking in Sema::CheckFunctionCall(). | ||||
994 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { | ||||
995 | // Turn this into a trap. | ||||
996 | CXXScopeSpec SS; | ||||
997 | SourceLocation TemplateKWLoc; | ||||
998 | UnqualifiedId Name; | ||||
999 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), | ||||
1000 | E->getBeginLoc()); | ||||
1001 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, | ||||
1002 | /*HasTrailingLParen=*/true, | ||||
1003 | /*IsAddressOfOperand=*/false); | ||||
1004 | if (TrapFn.isInvalid()) | ||||
1005 | return ExprError(); | ||||
1006 | |||||
1007 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), | ||||
1008 | None, E->getEndLoc()); | ||||
1009 | if (Call.isInvalid()) | ||||
1010 | return ExprError(); | ||||
1011 | |||||
1012 | ExprResult Comma = | ||||
1013 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); | ||||
1014 | if (Comma.isInvalid()) | ||||
1015 | return ExprError(); | ||||
1016 | return Comma.get(); | ||||
1017 | } | ||||
1018 | |||||
1019 | if (!getLangOpts().CPlusPlus && | ||||
1020 | RequireCompleteType(E->getExprLoc(), E->getType(), | ||||
1021 | diag::err_call_incomplete_argument)) | ||||
1022 | return ExprError(); | ||||
1023 | |||||
1024 | return E; | ||||
1025 | } | ||||
1026 | |||||
1027 | /// Converts an integer to complex float type. Helper function of | ||||
1028 | /// UsualArithmeticConversions() | ||||
1029 | /// | ||||
1030 | /// \return false if the integer expression is an integer type and is | ||||
1031 | /// successfully converted to the complex type. | ||||
1032 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, | ||||
1033 | ExprResult &ComplexExpr, | ||||
1034 | QualType IntTy, | ||||
1035 | QualType ComplexTy, | ||||
1036 | bool SkipCast) { | ||||
1037 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; | ||||
1038 | if (SkipCast) return false; | ||||
1039 | if (IntTy->isIntegerType()) { | ||||
1040 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); | ||||
1041 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); | ||||
1042 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1043 | CK_FloatingRealToComplex); | ||||
1044 | } else { | ||||
1045 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1045, __PRETTY_FUNCTION__)); | ||||
1046 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, | ||||
1047 | CK_IntegralComplexToFloatingComplex); | ||||
1048 | } | ||||
1049 | return false; | ||||
1050 | } | ||||
1051 | |||||
1052 | /// Handle arithmetic conversion with complex types. Helper function of | ||||
1053 | /// UsualArithmeticConversions() | ||||
1054 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, | ||||
1055 | ExprResult &RHS, QualType LHSType, | ||||
1056 | QualType RHSType, | ||||
1057 | bool IsCompAssign) { | ||||
1058 | // if we have an integer operand, the result is the complex type. | ||||
1059 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1060 | /*skipCast*/false)) | ||||
1061 | return LHSType; | ||||
1062 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1063 | /*skipCast*/IsCompAssign)) | ||||
1064 | return RHSType; | ||||
1065 | |||||
1066 | // This handles complex/complex, complex/float, or float/complex. | ||||
1067 | // When both operands are complex, the shorter operand is converted to the | ||||
1068 | // type of the longer, and that is the type of the result. This corresponds | ||||
1069 | // to what is done when combining two real floating-point operands. | ||||
1070 | // The fun begins when size promotion occur across type domains. | ||||
1071 | // From H&S 6.3.4: When one operand is complex and the other is a real | ||||
1072 | // floating-point type, the less precise type is converted, within it's | ||||
1073 | // real or complex domain, to the precision of the other type. For example, | ||||
1074 | // when combining a "long double" with a "double _Complex", the | ||||
1075 | // "double _Complex" is promoted to "long double _Complex". | ||||
1076 | |||||
1077 | // Compute the rank of the two types, regardless of whether they are complex. | ||||
1078 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1079 | |||||
1080 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); | ||||
1081 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); | ||||
1082 | QualType LHSElementType = | ||||
1083 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; | ||||
1084 | QualType RHSElementType = | ||||
1085 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; | ||||
1086 | |||||
1087 | QualType ResultType = S.Context.getComplexType(LHSElementType); | ||||
1088 | if (Order < 0) { | ||||
1089 | // Promote the precision of the LHS if not an assignment. | ||||
1090 | ResultType = S.Context.getComplexType(RHSElementType); | ||||
1091 | if (!IsCompAssign) { | ||||
1092 | if (LHSComplexType) | ||||
1093 | LHS = | ||||
1094 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1095 | else | ||||
1096 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); | ||||
1097 | } | ||||
1098 | } else if (Order > 0) { | ||||
1099 | // Promote the precision of the RHS. | ||||
1100 | if (RHSComplexType) | ||||
1101 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); | ||||
1102 | else | ||||
1103 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); | ||||
1104 | } | ||||
1105 | return ResultType; | ||||
1106 | } | ||||
1107 | |||||
1108 | /// Handle arithmetic conversion from integer to float. Helper function | ||||
1109 | /// of UsualArithmeticConversions() | ||||
1110 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, | ||||
1111 | ExprResult &IntExpr, | ||||
1112 | QualType FloatTy, QualType IntTy, | ||||
1113 | bool ConvertFloat, bool ConvertInt) { | ||||
1114 | if (IntTy->isIntegerType()) { | ||||
1115 | if (ConvertInt) | ||||
1116 | // Convert intExpr to the lhs floating point type. | ||||
1117 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, | ||||
1118 | CK_IntegralToFloating); | ||||
1119 | return FloatTy; | ||||
1120 | } | ||||
1121 | |||||
1122 | // Convert both sides to the appropriate complex float. | ||||
1123 | assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void> (0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1123, __PRETTY_FUNCTION__)); | ||||
1124 | QualType result = S.Context.getComplexType(FloatTy); | ||||
1125 | |||||
1126 | // _Complex int -> _Complex float | ||||
1127 | if (ConvertInt) | ||||
1128 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, | ||||
1129 | CK_IntegralComplexToFloatingComplex); | ||||
1130 | |||||
1131 | // float -> _Complex float | ||||
1132 | if (ConvertFloat) | ||||
1133 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, | ||||
1134 | CK_FloatingRealToComplex); | ||||
1135 | |||||
1136 | return result; | ||||
1137 | } | ||||
1138 | |||||
1139 | /// Handle arithmethic conversion with floating point types. Helper | ||||
1140 | /// function of UsualArithmeticConversions() | ||||
1141 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, | ||||
1142 | ExprResult &RHS, QualType LHSType, | ||||
1143 | QualType RHSType, bool IsCompAssign) { | ||||
1144 | bool LHSFloat = LHSType->isRealFloatingType(); | ||||
1145 | bool RHSFloat = RHSType->isRealFloatingType(); | ||||
1146 | |||||
1147 | // N1169 4.1.4: If one of the operands has a floating type and the other | ||||
1148 | // operand has a fixed-point type, the fixed-point operand | ||||
1149 | // is converted to the floating type [...] | ||||
1150 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { | ||||
1151 | if (LHSFloat) | ||||
1152 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); | ||||
1153 | else if (!IsCompAssign) | ||||
1154 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); | ||||
1155 | return LHSFloat ? LHSType : RHSType; | ||||
1156 | } | ||||
1157 | |||||
1158 | // If we have two real floating types, convert the smaller operand | ||||
1159 | // to the bigger result. | ||||
1160 | if (LHSFloat && RHSFloat) { | ||||
1161 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); | ||||
1162 | if (order > 0) { | ||||
1163 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); | ||||
1164 | return LHSType; | ||||
1165 | } | ||||
1166 | |||||
1167 | assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast <void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1167, __PRETTY_FUNCTION__)); | ||||
1168 | if (!IsCompAssign) | ||||
1169 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); | ||||
1170 | return RHSType; | ||||
1171 | } | ||||
1172 | |||||
1173 | if (LHSFloat) { | ||||
1174 | // Half FP has to be promoted to float unless it is natively supported | ||||
1175 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) | ||||
1176 | LHSType = S.Context.FloatTy; | ||||
1177 | |||||
1178 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
1179 | /*ConvertFloat=*/!IsCompAssign, | ||||
1180 | /*ConvertInt=*/ true); | ||||
1181 | } | ||||
1182 | assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1182, __PRETTY_FUNCTION__)); | ||||
1183 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, | ||||
1184 | /*ConvertFloat=*/ true, | ||||
1185 | /*ConvertInt=*/!IsCompAssign); | ||||
1186 | } | ||||
1187 | |||||
1188 | /// Diagnose attempts to convert between __float128 and long double if | ||||
1189 | /// there is no support for such conversion. Helper function of | ||||
1190 | /// UsualArithmeticConversions(). | ||||
1191 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, | ||||
1192 | QualType RHSType) { | ||||
1193 | /* No issue converting if at least one of the types is not a floating point | ||||
1194 | type or the two types have the same rank. | ||||
1195 | */ | ||||
1196 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || | ||||
1197 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) | ||||
1198 | return false; | ||||
1199 | |||||
1200 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1201, __PRETTY_FUNCTION__)) | ||||
1201 | "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType () && "The remaining types must be floating point types." ) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1201, __PRETTY_FUNCTION__)); | ||||
1202 | |||||
1203 | auto *LHSComplex = LHSType->getAs<ComplexType>(); | ||||
1204 | auto *RHSComplex = RHSType->getAs<ComplexType>(); | ||||
1205 | |||||
1206 | QualType LHSElemType = LHSComplex ? | ||||
1207 | LHSComplex->getElementType() : LHSType; | ||||
1208 | QualType RHSElemType = RHSComplex ? | ||||
1209 | RHSComplex->getElementType() : RHSType; | ||||
1210 | |||||
1211 | // No issue if the two types have the same representation | ||||
1212 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == | ||||
1213 | &S.Context.getFloatTypeSemantics(RHSElemType)) | ||||
1214 | return false; | ||||
1215 | |||||
1216 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && | ||||
1217 | RHSElemType == S.Context.LongDoubleTy); | ||||
1218 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && | ||||
1219 | RHSElemType == S.Context.Float128Ty); | ||||
1220 | |||||
1221 | // We've handled the situation where __float128 and long double have the same | ||||
1222 | // representation. We allow all conversions for all possible long double types | ||||
1223 | // except PPC's double double. | ||||
1224 | return Float128AndLongDouble && | ||||
1225 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | ||||
1226 | &llvm::APFloat::PPCDoubleDouble()); | ||||
1227 | } | ||||
1228 | |||||
1229 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); | ||||
1230 | |||||
1231 | namespace { | ||||
1232 | /// These helper callbacks are placed in an anonymous namespace to | ||||
1233 | /// permit their use as function template parameters. | ||||
1234 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1235 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); | ||||
1236 | } | ||||
1237 | |||||
1238 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { | ||||
1239 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), | ||||
1240 | CK_IntegralComplexCast); | ||||
1241 | } | ||||
1242 | } | ||||
1243 | |||||
1244 | /// Handle integer arithmetic conversions. Helper function of | ||||
1245 | /// UsualArithmeticConversions() | ||||
1246 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> | ||||
1247 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, | ||||
1248 | ExprResult &RHS, QualType LHSType, | ||||
1249 | QualType RHSType, bool IsCompAssign) { | ||||
1250 | // The rules for this case are in C99 6.3.1.8 | ||||
1251 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); | ||||
1252 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); | ||||
1253 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); | ||||
1254 | if (LHSSigned == RHSSigned) { | ||||
1255 | // Same signedness; use the higher-ranked type | ||||
1256 | if (order >= 0) { | ||||
1257 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1258 | return LHSType; | ||||
1259 | } else if (!IsCompAssign) | ||||
1260 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1261 | return RHSType; | ||||
1262 | } else if (order != (LHSSigned ? 1 : -1)) { | ||||
1263 | // The unsigned type has greater than or equal rank to the | ||||
1264 | // signed type, so use the unsigned type | ||||
1265 | if (RHSSigned) { | ||||
1266 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1267 | return LHSType; | ||||
1268 | } else if (!IsCompAssign) | ||||
1269 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1270 | return RHSType; | ||||
1271 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { | ||||
1272 | // The two types are different widths; if we are here, that | ||||
1273 | // means the signed type is larger than the unsigned type, so | ||||
1274 | // use the signed type. | ||||
1275 | if (LHSSigned) { | ||||
1276 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); | ||||
1277 | return LHSType; | ||||
1278 | } else if (!IsCompAssign) | ||||
1279 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); | ||||
1280 | return RHSType; | ||||
1281 | } else { | ||||
1282 | // The signed type is higher-ranked than the unsigned type, | ||||
1283 | // but isn't actually any bigger (like unsigned int and long | ||||
1284 | // on most 32-bit systems). Use the unsigned type corresponding | ||||
1285 | // to the signed type. | ||||
1286 | QualType result = | ||||
1287 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); | ||||
1288 | RHS = (*doRHSCast)(S, RHS.get(), result); | ||||
1289 | if (!IsCompAssign) | ||||
1290 | LHS = (*doLHSCast)(S, LHS.get(), result); | ||||
1291 | return result; | ||||
1292 | } | ||||
1293 | } | ||||
1294 | |||||
1295 | /// Handle conversions with GCC complex int extension. Helper function | ||||
1296 | /// of UsualArithmeticConversions() | ||||
1297 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, | ||||
1298 | ExprResult &RHS, QualType LHSType, | ||||
1299 | QualType RHSType, | ||||
1300 | bool IsCompAssign) { | ||||
1301 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); | ||||
1302 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); | ||||
1303 | |||||
1304 | if (LHSComplexInt && RHSComplexInt) { | ||||
1305 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1306 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1307 | QualType ScalarType = | ||||
1308 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> | ||||
1309 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); | ||||
1310 | |||||
1311 | return S.Context.getComplexType(ScalarType); | ||||
1312 | } | ||||
1313 | |||||
1314 | if (LHSComplexInt) { | ||||
1315 | QualType LHSEltType = LHSComplexInt->getElementType(); | ||||
1316 | QualType ScalarType = | ||||
1317 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> | ||||
1318 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); | ||||
1319 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1320 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, | ||||
1321 | CK_IntegralRealToComplex); | ||||
1322 | |||||
1323 | return ComplexType; | ||||
1324 | } | ||||
1325 | |||||
1326 | assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail ("RHSComplexInt", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1326, __PRETTY_FUNCTION__)); | ||||
1327 | |||||
1328 | QualType RHSEltType = RHSComplexInt->getElementType(); | ||||
1329 | QualType ScalarType = | ||||
1330 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> | ||||
1331 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); | ||||
1332 | QualType ComplexType = S.Context.getComplexType(ScalarType); | ||||
1333 | |||||
1334 | if (!IsCompAssign) | ||||
1335 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, | ||||
1336 | CK_IntegralRealToComplex); | ||||
1337 | return ComplexType; | ||||
1338 | } | ||||
1339 | |||||
1340 | /// Return the rank of a given fixed point or integer type. The value itself | ||||
1341 | /// doesn't matter, but the values must be increasing with proper increasing | ||||
1342 | /// rank as described in N1169 4.1.1. | ||||
1343 | static unsigned GetFixedPointRank(QualType Ty) { | ||||
1344 | const auto *BTy = Ty->getAs<BuiltinType>(); | ||||
1345 | assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast< void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1345, __PRETTY_FUNCTION__)); | ||||
1346 | |||||
1347 | switch (BTy->getKind()) { | ||||
1348 | case BuiltinType::ShortFract: | ||||
1349 | case BuiltinType::UShortFract: | ||||
1350 | case BuiltinType::SatShortFract: | ||||
1351 | case BuiltinType::SatUShortFract: | ||||
1352 | return 1; | ||||
1353 | case BuiltinType::Fract: | ||||
1354 | case BuiltinType::UFract: | ||||
1355 | case BuiltinType::SatFract: | ||||
1356 | case BuiltinType::SatUFract: | ||||
1357 | return 2; | ||||
1358 | case BuiltinType::LongFract: | ||||
1359 | case BuiltinType::ULongFract: | ||||
1360 | case BuiltinType::SatLongFract: | ||||
1361 | case BuiltinType::SatULongFract: | ||||
1362 | return 3; | ||||
1363 | case BuiltinType::ShortAccum: | ||||
1364 | case BuiltinType::UShortAccum: | ||||
1365 | case BuiltinType::SatShortAccum: | ||||
1366 | case BuiltinType::SatUShortAccum: | ||||
1367 | return 4; | ||||
1368 | case BuiltinType::Accum: | ||||
1369 | case BuiltinType::UAccum: | ||||
1370 | case BuiltinType::SatAccum: | ||||
1371 | case BuiltinType::SatUAccum: | ||||
1372 | return 5; | ||||
1373 | case BuiltinType::LongAccum: | ||||
1374 | case BuiltinType::ULongAccum: | ||||
1375 | case BuiltinType::SatLongAccum: | ||||
1376 | case BuiltinType::SatULongAccum: | ||||
1377 | return 6; | ||||
1378 | default: | ||||
1379 | if (BTy->isInteger()) | ||||
1380 | return 0; | ||||
1381 | llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1381); | ||||
1382 | } | ||||
1383 | } | ||||
1384 | |||||
1385 | /// handleFixedPointConversion - Fixed point operations between fixed | ||||
1386 | /// point types and integers or other fixed point types do not fall under | ||||
1387 | /// usual arithmetic conversion since these conversions could result in loss | ||||
1388 | /// of precsision (N1169 4.1.4). These operations should be calculated with | ||||
1389 | /// the full precision of their result type (N1169 4.1.6.2.1). | ||||
1390 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, | ||||
1391 | QualType RHSTy) { | ||||
1392 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1393, __PRETTY_FUNCTION__)) | ||||
1393 | "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType ()) && "Expected at least one of the operands to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1393, __PRETTY_FUNCTION__)); | ||||
1394 | assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||
1395 | RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||
1396 | "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)) | ||||
1397 | "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType ()) && "Special fixed point arithmetic operation conversions are only " "applied to ints or other fixed point types") ? static_cast< void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1397, __PRETTY_FUNCTION__)); | ||||
1398 | |||||
1399 | // If one operand has signed fixed-point type and the other operand has | ||||
1400 | // unsigned fixed-point type, then the unsigned fixed-point operand is | ||||
1401 | // converted to its corresponding signed fixed-point type and the resulting | ||||
1402 | // type is the type of the converted operand. | ||||
1403 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) | ||||
1404 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); | ||||
1405 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) | ||||
1406 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); | ||||
1407 | |||||
1408 | // The result type is the type with the highest rank, whereby a fixed-point | ||||
1409 | // conversion rank is always greater than an integer conversion rank; if the | ||||
1410 | // type of either of the operands is a saturating fixedpoint type, the result | ||||
1411 | // type shall be the saturating fixed-point type corresponding to the type | ||||
1412 | // with the highest rank; the resulting value is converted (taking into | ||||
1413 | // account rounding and overflow) to the precision of the resulting type. | ||||
1414 | // Same ranks between signed and unsigned types are resolved earlier, so both | ||||
1415 | // types are either signed or both unsigned at this point. | ||||
1416 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); | ||||
1417 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); | ||||
1418 | |||||
1419 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; | ||||
1420 | |||||
1421 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) | ||||
1422 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); | ||||
1423 | |||||
1424 | return ResultTy; | ||||
1425 | } | ||||
1426 | |||||
1427 | /// Check that the usual arithmetic conversions can be performed on this pair of | ||||
1428 | /// expressions that might be of enumeration type. | ||||
1429 | static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, | ||||
1430 | SourceLocation Loc, | ||||
1431 | Sema::ArithConvKind ACK) { | ||||
1432 | // C++2a [expr.arith.conv]p1: | ||||
1433 | // If one operand is of enumeration type and the other operand is of a | ||||
1434 | // different enumeration type or a floating-point type, this behavior is | ||||
1435 | // deprecated ([depr.arith.conv.enum]). | ||||
1436 | // | ||||
1437 | // Warn on this in all language modes. Produce a deprecation warning in C++20. | ||||
1438 | // Eventually we will presumably reject these cases (in C++23 onwards?). | ||||
1439 | QualType L = LHS->getType(), R = RHS->getType(); | ||||
1440 | bool LEnum = L->isUnscopedEnumerationType(), | ||||
1441 | REnum = R->isUnscopedEnumerationType(); | ||||
1442 | bool IsCompAssign = ACK == Sema::ACK_CompAssign; | ||||
1443 | if ((!IsCompAssign && LEnum && R->isFloatingType()) || | ||||
1444 | (REnum && L->isFloatingType())) { | ||||
1445 | S.Diag(Loc, S.getLangOpts().CPlusPlus20 | ||||
1446 | ? diag::warn_arith_conv_enum_float_cxx20 | ||||
1447 | : diag::warn_arith_conv_enum_float) | ||||
1448 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1449 | << (int)ACK << LEnum << L << R; | ||||
1450 | } else if (!IsCompAssign && LEnum && REnum && | ||||
1451 | !S.Context.hasSameUnqualifiedType(L, R)) { | ||||
1452 | unsigned DiagID; | ||||
1453 | if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || | ||||
1454 | !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { | ||||
1455 | // If either enumeration type is unnamed, it's less likely that the | ||||
1456 | // user cares about this, but this situation is still deprecated in | ||||
1457 | // C++2a. Use a different warning group. | ||||
1458 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1459 | ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 | ||||
1460 | : diag::warn_arith_conv_mixed_anon_enum_types; | ||||
1461 | } else if (ACK == Sema::ACK_Conditional) { | ||||
1462 | // Conditional expressions are separated out because they have | ||||
1463 | // historically had a different warning flag. | ||||
1464 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1465 | ? diag::warn_conditional_mixed_enum_types_cxx20 | ||||
1466 | : diag::warn_conditional_mixed_enum_types; | ||||
1467 | } else if (ACK == Sema::ACK_Comparison) { | ||||
1468 | // Comparison expressions are separated out because they have | ||||
1469 | // historically had a different warning flag. | ||||
1470 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1471 | ? diag::warn_comparison_mixed_enum_types_cxx20 | ||||
1472 | : diag::warn_comparison_mixed_enum_types; | ||||
1473 | } else { | ||||
1474 | DiagID = S.getLangOpts().CPlusPlus20 | ||||
1475 | ? diag::warn_arith_conv_mixed_enum_types_cxx20 | ||||
1476 | : diag::warn_arith_conv_mixed_enum_types; | ||||
1477 | } | ||||
1478 | S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() | ||||
1479 | << (int)ACK << L << R; | ||||
1480 | } | ||||
1481 | } | ||||
1482 | |||||
1483 | /// UsualArithmeticConversions - Performs various conversions that are common to | ||||
1484 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this | ||||
1485 | /// routine returns the first non-arithmetic type found. The client is | ||||
1486 | /// responsible for emitting appropriate error diagnostics. | ||||
1487 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | ||||
1488 | SourceLocation Loc, | ||||
1489 | ArithConvKind ACK) { | ||||
1490 | checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); | ||||
1491 | |||||
1492 | if (ACK != ACK_CompAssign) { | ||||
1493 | LHS = UsualUnaryConversions(LHS.get()); | ||||
1494 | if (LHS.isInvalid()) | ||||
1495 | return QualType(); | ||||
1496 | } | ||||
1497 | |||||
1498 | RHS = UsualUnaryConversions(RHS.get()); | ||||
1499 | if (RHS.isInvalid()) | ||||
1500 | return QualType(); | ||||
1501 | |||||
1502 | // For conversion purposes, we ignore any qualifiers. | ||||
1503 | // For example, "const float" and "float" are equivalent. | ||||
1504 | QualType LHSType = | ||||
1505 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
1506 | QualType RHSType = | ||||
1507 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
1508 | |||||
1509 | // For conversion purposes, we ignore any atomic qualifier on the LHS. | ||||
1510 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) | ||||
1511 | LHSType = AtomicLHS->getValueType(); | ||||
1512 | |||||
1513 | // If both types are identical, no conversion is needed. | ||||
1514 | if (LHSType == RHSType) | ||||
1515 | return LHSType; | ||||
1516 | |||||
1517 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. | ||||
1518 | // The caller can deal with this (e.g. pointer + int). | ||||
1519 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) | ||||
1520 | return QualType(); | ||||
1521 | |||||
1522 | // Apply unary and bitfield promotions to the LHS's type. | ||||
1523 | QualType LHSUnpromotedType = LHSType; | ||||
1524 | if (LHSType->isPromotableIntegerType()) | ||||
1525 | LHSType = Context.getPromotedIntegerType(LHSType); | ||||
1526 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); | ||||
1527 | if (!LHSBitfieldPromoteTy.isNull()) | ||||
1528 | LHSType = LHSBitfieldPromoteTy; | ||||
1529 | if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) | ||||
1530 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); | ||||
1531 | |||||
1532 | // If both types are identical, no conversion is needed. | ||||
1533 | if (LHSType == RHSType) | ||||
1534 | return LHSType; | ||||
1535 | |||||
1536 | // ExtInt types aren't subject to conversions between them or normal integers, | ||||
1537 | // so this fails. | ||||
1538 | if(LHSType->isExtIntType() || RHSType->isExtIntType()) | ||||
1539 | return QualType(); | ||||
1540 | |||||
1541 | // At this point, we have two different arithmetic types. | ||||
1542 | |||||
1543 | // Diagnose attempts to convert between __float128 and long double where | ||||
1544 | // such conversions currently can't be handled. | ||||
1545 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
1546 | return QualType(); | ||||
1547 | |||||
1548 | // Handle complex types first (C99 6.3.1.8p1). | ||||
1549 | if (LHSType->isComplexType() || RHSType->isComplexType()) | ||||
1550 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1551 | ACK == ACK_CompAssign); | ||||
1552 | |||||
1553 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
1554 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
1555 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1556 | ACK == ACK_CompAssign); | ||||
1557 | |||||
1558 | // Handle GCC complex int extension. | ||||
1559 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) | ||||
1560 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, | ||||
1561 | ACK == ACK_CompAssign); | ||||
1562 | |||||
1563 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) | ||||
1564 | return handleFixedPointConversion(*this, LHSType, RHSType); | ||||
1565 | |||||
1566 | // Finally, we have two differing integer types. | ||||
1567 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
1568 | (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); | ||||
1569 | } | ||||
1570 | |||||
1571 | //===----------------------------------------------------------------------===// | ||||
1572 | // Semantic Analysis for various Expression Types | ||||
1573 | //===----------------------------------------------------------------------===// | ||||
1574 | |||||
1575 | |||||
1576 | ExprResult | ||||
1577 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1578 | SourceLocation DefaultLoc, | ||||
1579 | SourceLocation RParenLoc, | ||||
1580 | Expr *ControllingExpr, | ||||
1581 | ArrayRef<ParsedType> ArgTypes, | ||||
1582 | ArrayRef<Expr *> ArgExprs) { | ||||
1583 | unsigned NumAssocs = ArgTypes.size(); | ||||
1584 | assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1584, __PRETTY_FUNCTION__)); | ||||
1585 | |||||
1586 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; | ||||
1587 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1588 | if (ArgTypes[i]) | ||||
1589 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); | ||||
1590 | else | ||||
1591 | Types[i] = nullptr; | ||||
1592 | } | ||||
1593 | |||||
1594 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, | ||||
1595 | ControllingExpr, | ||||
1596 | llvm::makeArrayRef(Types, NumAssocs), | ||||
1597 | ArgExprs); | ||||
1598 | delete [] Types; | ||||
1599 | return ER; | ||||
1600 | } | ||||
1601 | |||||
1602 | ExprResult | ||||
1603 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, | ||||
1604 | SourceLocation DefaultLoc, | ||||
1605 | SourceLocation RParenLoc, | ||||
1606 | Expr *ControllingExpr, | ||||
1607 | ArrayRef<TypeSourceInfo *> Types, | ||||
1608 | ArrayRef<Expr *> Exprs) { | ||||
1609 | unsigned NumAssocs = Types.size(); | ||||
1610 | assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail ("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1610, __PRETTY_FUNCTION__)); | ||||
1611 | |||||
1612 | // Decay and strip qualifiers for the controlling expression type, and handle | ||||
1613 | // placeholder type replacement. See committee discussion from WG14 DR423. | ||||
1614 | { | ||||
1615 | EnterExpressionEvaluationContext Unevaluated( | ||||
1616 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
1617 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); | ||||
1618 | if (R.isInvalid()) | ||||
1619 | return ExprError(); | ||||
1620 | ControllingExpr = R.get(); | ||||
1621 | } | ||||
1622 | |||||
1623 | // The controlling expression is an unevaluated operand, so side effects are | ||||
1624 | // likely unintended. | ||||
1625 | if (!inTemplateInstantiation() && | ||||
1626 | ControllingExpr->HasSideEffects(Context, false)) | ||||
1627 | Diag(ControllingExpr->getExprLoc(), | ||||
1628 | diag::warn_side_effects_unevaluated_context); | ||||
1629 | |||||
1630 | bool TypeErrorFound = false, | ||||
1631 | IsResultDependent = ControllingExpr->isTypeDependent(), | ||||
1632 | ContainsUnexpandedParameterPack | ||||
1633 | = ControllingExpr->containsUnexpandedParameterPack(); | ||||
1634 | |||||
1635 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1636 | if (Exprs[i]->containsUnexpandedParameterPack()) | ||||
1637 | ContainsUnexpandedParameterPack = true; | ||||
1638 | |||||
1639 | if (Types[i]) { | ||||
1640 | if (Types[i]->getType()->containsUnexpandedParameterPack()) | ||||
1641 | ContainsUnexpandedParameterPack = true; | ||||
1642 | |||||
1643 | if (Types[i]->getType()->isDependentType()) { | ||||
1644 | IsResultDependent = true; | ||||
1645 | } else { | ||||
1646 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a | ||||
1647 | // complete object type other than a variably modified type." | ||||
1648 | unsigned D = 0; | ||||
1649 | if (Types[i]->getType()->isIncompleteType()) | ||||
1650 | D = diag::err_assoc_type_incomplete; | ||||
1651 | else if (!Types[i]->getType()->isObjectType()) | ||||
1652 | D = diag::err_assoc_type_nonobject; | ||||
1653 | else if (Types[i]->getType()->isVariablyModifiedType()) | ||||
1654 | D = diag::err_assoc_type_variably_modified; | ||||
1655 | |||||
1656 | if (D != 0) { | ||||
1657 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) | ||||
1658 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1659 | << Types[i]->getType(); | ||||
1660 | TypeErrorFound = true; | ||||
1661 | } | ||||
1662 | |||||
1663 | // C11 6.5.1.1p2 "No two generic associations in the same generic | ||||
1664 | // selection shall specify compatible types." | ||||
1665 | for (unsigned j = i+1; j < NumAssocs; ++j) | ||||
1666 | if (Types[j] && !Types[j]->getType()->isDependentType() && | ||||
1667 | Context.typesAreCompatible(Types[i]->getType(), | ||||
1668 | Types[j]->getType())) { | ||||
1669 | Diag(Types[j]->getTypeLoc().getBeginLoc(), | ||||
1670 | diag::err_assoc_compatible_types) | ||||
1671 | << Types[j]->getTypeLoc().getSourceRange() | ||||
1672 | << Types[j]->getType() | ||||
1673 | << Types[i]->getType(); | ||||
1674 | Diag(Types[i]->getTypeLoc().getBeginLoc(), | ||||
1675 | diag::note_compat_assoc) | ||||
1676 | << Types[i]->getTypeLoc().getSourceRange() | ||||
1677 | << Types[i]->getType(); | ||||
1678 | TypeErrorFound = true; | ||||
1679 | } | ||||
1680 | } | ||||
1681 | } | ||||
1682 | } | ||||
1683 | if (TypeErrorFound) | ||||
1684 | return ExprError(); | ||||
1685 | |||||
1686 | // If we determined that the generic selection is result-dependent, don't | ||||
1687 | // try to compute the result expression. | ||||
1688 | if (IsResultDependent) | ||||
1689 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, | ||||
1690 | Exprs, DefaultLoc, RParenLoc, | ||||
1691 | ContainsUnexpandedParameterPack); | ||||
1692 | |||||
1693 | SmallVector<unsigned, 1> CompatIndices; | ||||
1694 | unsigned DefaultIndex = -1U; | ||||
1695 | for (unsigned i = 0; i < NumAssocs; ++i) { | ||||
1696 | if (!Types[i]) | ||||
1697 | DefaultIndex = i; | ||||
1698 | else if (Context.typesAreCompatible(ControllingExpr->getType(), | ||||
1699 | Types[i]->getType())) | ||||
1700 | CompatIndices.push_back(i); | ||||
1701 | } | ||||
1702 | |||||
1703 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have | ||||
1704 | // type compatible with at most one of the types named in its generic | ||||
1705 | // association list." | ||||
1706 | if (CompatIndices.size() > 1) { | ||||
1707 | // We strip parens here because the controlling expression is typically | ||||
1708 | // parenthesized in macro definitions. | ||||
1709 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1710 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) | ||||
1711 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() | ||||
1712 | << (unsigned)CompatIndices.size(); | ||||
1713 | for (unsigned I : CompatIndices) { | ||||
1714 | Diag(Types[I]->getTypeLoc().getBeginLoc(), | ||||
1715 | diag::note_compat_assoc) | ||||
1716 | << Types[I]->getTypeLoc().getSourceRange() | ||||
1717 | << Types[I]->getType(); | ||||
1718 | } | ||||
1719 | return ExprError(); | ||||
1720 | } | ||||
1721 | |||||
1722 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, | ||||
1723 | // its controlling expression shall have type compatible with exactly one of | ||||
1724 | // the types named in its generic association list." | ||||
1725 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { | ||||
1726 | // We strip parens here because the controlling expression is typically | ||||
1727 | // parenthesized in macro definitions. | ||||
1728 | ControllingExpr = ControllingExpr->IgnoreParens(); | ||||
1729 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) | ||||
1730 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); | ||||
1731 | return ExprError(); | ||||
1732 | } | ||||
1733 | |||||
1734 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a | ||||
1735 | // type name that is compatible with the type of the controlling expression, | ||||
1736 | // then the result expression of the generic selection is the expression | ||||
1737 | // in that generic association. Otherwise, the result expression of the | ||||
1738 | // generic selection is the expression in the default generic association." | ||||
1739 | unsigned ResultIndex = | ||||
1740 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; | ||||
1741 | |||||
1742 | return GenericSelectionExpr::Create( | ||||
1743 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, | ||||
1744 | ContainsUnexpandedParameterPack, ResultIndex); | ||||
1745 | } | ||||
1746 | |||||
1747 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the | ||||
1748 | /// location of the token and the offset of the ud-suffix within it. | ||||
1749 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, | ||||
1750 | unsigned Offset) { | ||||
1751 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), | ||||
1752 | S.getLangOpts()); | ||||
1753 | } | ||||
1754 | |||||
1755 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up | ||||
1756 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. | ||||
1757 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, | ||||
1758 | IdentifierInfo *UDSuffix, | ||||
1759 | SourceLocation UDSuffixLoc, | ||||
1760 | ArrayRef<Expr*> Args, | ||||
1761 | SourceLocation LitEndLoc) { | ||||
1762 | assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator" ) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1762, __PRETTY_FUNCTION__)); | ||||
1763 | |||||
1764 | QualType ArgTy[2]; | ||||
1765 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { | ||||
1766 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); | ||||
1767 | if (ArgTy[ArgIdx]->isArrayType()) | ||||
1768 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); | ||||
1769 | } | ||||
1770 | |||||
1771 | DeclarationName OpName = | ||||
1772 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1773 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1774 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1775 | |||||
1776 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); | ||||
1777 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), | ||||
1778 | /*AllowRaw*/ false, /*AllowTemplate*/ false, | ||||
1779 | /*AllowStringTemplatePack*/ false, | ||||
1780 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) | ||||
1781 | return ExprError(); | ||||
1782 | |||||
1783 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); | ||||
1784 | } | ||||
1785 | |||||
1786 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | ||||
1787 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string | ||||
1788 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from | ||||
1789 | /// multiple tokens. However, the common case is that StringToks points to one | ||||
1790 | /// string. | ||||
1791 | /// | ||||
1792 | ExprResult | ||||
1793 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { | ||||
1794 | assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!" ) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1794, __PRETTY_FUNCTION__)); | ||||
1795 | |||||
1796 | StringLiteralParser Literal(StringToks, PP); | ||||
1797 | if (Literal.hadError) | ||||
1798 | return ExprError(); | ||||
1799 | |||||
1800 | SmallVector<SourceLocation, 4> StringTokLocs; | ||||
1801 | for (const Token &Tok : StringToks) | ||||
1802 | StringTokLocs.push_back(Tok.getLocation()); | ||||
1803 | |||||
1804 | QualType CharTy = Context.CharTy; | ||||
1805 | StringLiteral::StringKind Kind = StringLiteral::Ascii; | ||||
1806 | if (Literal.isWide()) { | ||||
1807 | CharTy = Context.getWideCharType(); | ||||
1808 | Kind = StringLiteral::Wide; | ||||
1809 | } else if (Literal.isUTF8()) { | ||||
1810 | if (getLangOpts().Char8) | ||||
1811 | CharTy = Context.Char8Ty; | ||||
1812 | Kind = StringLiteral::UTF8; | ||||
1813 | } else if (Literal.isUTF16()) { | ||||
1814 | CharTy = Context.Char16Ty; | ||||
1815 | Kind = StringLiteral::UTF16; | ||||
1816 | } else if (Literal.isUTF32()) { | ||||
1817 | CharTy = Context.Char32Ty; | ||||
1818 | Kind = StringLiteral::UTF32; | ||||
1819 | } else if (Literal.isPascal()) { | ||||
1820 | CharTy = Context.UnsignedCharTy; | ||||
1821 | } | ||||
1822 | |||||
1823 | // Warn on initializing an array of char from a u8 string literal; this | ||||
1824 | // becomes ill-formed in C++2a. | ||||
1825 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && | ||||
1826 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { | ||||
1827 | Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); | ||||
1828 | |||||
1829 | // Create removals for all 'u8' prefixes in the string literal(s). This | ||||
1830 | // ensures C++2a compatibility (but may change the program behavior when | ||||
1831 | // built by non-Clang compilers for which the execution character set is | ||||
1832 | // not always UTF-8). | ||||
1833 | auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); | ||||
1834 | SourceLocation RemovalDiagLoc; | ||||
1835 | for (const Token &Tok : StringToks) { | ||||
1836 | if (Tok.getKind() == tok::utf8_string_literal) { | ||||
1837 | if (RemovalDiagLoc.isInvalid()) | ||||
1838 | RemovalDiagLoc = Tok.getLocation(); | ||||
1839 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( | ||||
1840 | Tok.getLocation(), | ||||
1841 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, | ||||
1842 | getSourceManager(), getLangOpts()))); | ||||
1843 | } | ||||
1844 | } | ||||
1845 | Diag(RemovalDiagLoc, RemovalDiag); | ||||
1846 | } | ||||
1847 | |||||
1848 | QualType StrTy = | ||||
1849 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); | ||||
1850 | |||||
1851 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! | ||||
1852 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), | ||||
1853 | Kind, Literal.Pascal, StrTy, | ||||
1854 | &StringTokLocs[0], | ||||
1855 | StringTokLocs.size()); | ||||
1856 | if (Literal.getUDSuffix().empty()) | ||||
1857 | return Lit; | ||||
1858 | |||||
1859 | // We're building a user-defined literal. | ||||
1860 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
1861 | SourceLocation UDSuffixLoc = | ||||
1862 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], | ||||
1863 | Literal.getUDSuffixOffset()); | ||||
1864 | |||||
1865 | // Make sure we're allowed user-defined literals here. | ||||
1866 | if (!UDLScope) | ||||
1867 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); | ||||
1868 | |||||
1869 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form | ||||
1870 | // operator "" X (str, len) | ||||
1871 | QualType SizeType = Context.getSizeType(); | ||||
1872 | |||||
1873 | DeclarationName OpName = | ||||
1874 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
1875 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
1876 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
1877 | |||||
1878 | QualType ArgTy[] = { | ||||
1879 | Context.getArrayDecayedType(StrTy), SizeType | ||||
1880 | }; | ||||
1881 | |||||
1882 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
1883 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, | ||||
1884 | /*AllowRaw*/ false, /*AllowTemplate*/ true, | ||||
1885 | /*AllowStringTemplatePack*/ true, | ||||
1886 | /*DiagnoseMissing*/ true, Lit)) { | ||||
1887 | |||||
1888 | case LOLR_Cooked: { | ||||
1889 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); | ||||
1890 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, | ||||
1891 | StringTokLocs[0]); | ||||
1892 | Expr *Args[] = { Lit, LenArg }; | ||||
1893 | |||||
1894 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); | ||||
1895 | } | ||||
1896 | |||||
1897 | case LOLR_Template: { | ||||
1898 | TemplateArgumentListInfo ExplicitArgs; | ||||
1899 | TemplateArgument Arg(Lit); | ||||
1900 | TemplateArgumentLocInfo ArgInfo(Lit); | ||||
1901 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1902 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1903 | &ExplicitArgs); | ||||
1904 | } | ||||
1905 | |||||
1906 | case LOLR_StringTemplatePack: { | ||||
1907 | TemplateArgumentListInfo ExplicitArgs; | ||||
1908 | |||||
1909 | unsigned CharBits = Context.getIntWidth(CharTy); | ||||
1910 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); | ||||
1911 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
1912 | |||||
1913 | TemplateArgument TypeArg(CharTy); | ||||
1914 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); | ||||
1915 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); | ||||
1916 | |||||
1917 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { | ||||
1918 | Value = Lit->getCodeUnit(I); | ||||
1919 | TemplateArgument Arg(Context, Value, CharTy); | ||||
1920 | TemplateArgumentLocInfo ArgInfo; | ||||
1921 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
1922 | } | ||||
1923 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), | ||||
1924 | &ExplicitArgs); | ||||
1925 | } | ||||
1926 | case LOLR_Raw: | ||||
1927 | case LOLR_ErrorNoDiagnostic: | ||||
1928 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1928); | ||||
1929 | case LOLR_Error: | ||||
1930 | return ExprError(); | ||||
1931 | } | ||||
1932 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1932); | ||||
1933 | } | ||||
1934 | |||||
1935 | DeclRefExpr * | ||||
1936 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1937 | SourceLocation Loc, | ||||
1938 | const CXXScopeSpec *SS) { | ||||
1939 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); | ||||
1940 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); | ||||
1941 | } | ||||
1942 | |||||
1943 | DeclRefExpr * | ||||
1944 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
1945 | const DeclarationNameInfo &NameInfo, | ||||
1946 | const CXXScopeSpec *SS, NamedDecl *FoundD, | ||||
1947 | SourceLocation TemplateKWLoc, | ||||
1948 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
1949 | NestedNameSpecifierLoc NNS = | ||||
1950 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); | ||||
1951 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, | ||||
1952 | TemplateArgs); | ||||
1953 | } | ||||
1954 | |||||
1955 | // CUDA/HIP: Check whether a captured reference variable is referencing a | ||||
1956 | // host variable in a device or host device lambda. | ||||
1957 | static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, | ||||
1958 | VarDecl *VD) { | ||||
1959 | if (!S.getLangOpts().CUDA || !VD->hasInit()) | ||||
1960 | return false; | ||||
1961 | assert(VD->getType()->isReferenceType())((VD->getType()->isReferenceType()) ? static_cast<void > (0) : __assert_fail ("VD->getType()->isReferenceType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 1961, __PRETTY_FUNCTION__)); | ||||
1962 | |||||
1963 | // Check whether the reference variable is referencing a host variable. | ||||
1964 | auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); | ||||
1965 | if (!DRE) | ||||
1966 | return false; | ||||
1967 | auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
1968 | if (!Referee || !Referee->hasGlobalStorage() || | ||||
1969 | Referee->hasAttr<CUDADeviceAttr>()) | ||||
1970 | return false; | ||||
1971 | |||||
1972 | // Check whether the current function is a device or host device lambda. | ||||
1973 | // Check whether the reference variable is a capture by getDeclContext() | ||||
1974 | // since refersToEnclosingVariableOrCapture() is not ready at this point. | ||||
1975 | auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); | ||||
1976 | if (MD && MD->getParent()->isLambda() && | ||||
1977 | MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && | ||||
1978 | VD->getDeclContext() != MD) | ||||
1979 | return true; | ||||
1980 | |||||
1981 | return false; | ||||
1982 | } | ||||
1983 | |||||
1984 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { | ||||
1985 | // A declaration named in an unevaluated operand never constitutes an odr-use. | ||||
1986 | if (isUnevaluatedContext()) | ||||
1987 | return NOUR_Unevaluated; | ||||
1988 | |||||
1989 | // C++2a [basic.def.odr]p4: | ||||
1990 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
1991 | // is odr-used by e unless [...] x is a reference that is usable in | ||||
1992 | // constant expressions. | ||||
1993 | // CUDA/HIP: | ||||
1994 | // If a reference variable referencing a host variable is captured in a | ||||
1995 | // device or host device lambda, the value of the referee must be copied | ||||
1996 | // to the capture and the reference variable must be treated as odr-use | ||||
1997 | // since the value of the referee is not known at compile time and must | ||||
1998 | // be loaded from the captured. | ||||
1999 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2000 | if (VD->getType()->isReferenceType() && | ||||
2001 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && | ||||
2002 | !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && | ||||
2003 | VD->isUsableInConstantExpressions(Context)) | ||||
2004 | return NOUR_Constant; | ||||
2005 | } | ||||
2006 | |||||
2007 | // All remaining non-variable cases constitute an odr-use. For variables, we | ||||
2008 | // need to wait and see how the expression is used. | ||||
2009 | return NOUR_None; | ||||
2010 | } | ||||
2011 | |||||
2012 | /// BuildDeclRefExpr - Build an expression that references a | ||||
2013 | /// declaration that does not require a closure capture. | ||||
2014 | DeclRefExpr * | ||||
2015 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | ||||
2016 | const DeclarationNameInfo &NameInfo, | ||||
2017 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, | ||||
2018 | SourceLocation TemplateKWLoc, | ||||
2019 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2020 | bool RefersToCapturedVariable = | ||||
2021 | isa<VarDecl>(D) && | ||||
2022 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); | ||||
2023 | |||||
2024 | DeclRefExpr *E = DeclRefExpr::Create( | ||||
2025 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, | ||||
2026 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); | ||||
2027 | MarkDeclRefReferenced(E); | ||||
2028 | |||||
2029 | // C++ [except.spec]p17: | ||||
2030 | // An exception-specification is considered to be needed when: | ||||
2031 | // - in an expression, the function is the unique lookup result or | ||||
2032 | // the selected member of a set of overloaded functions. | ||||
2033 | // | ||||
2034 | // We delay doing this until after we've built the function reference and | ||||
2035 | // marked it as used so that: | ||||
2036 | // a) if the function is defaulted, we get errors from defining it before / | ||||
2037 | // instead of errors from computing its exception specification, and | ||||
2038 | // b) if the function is a defaulted comparison, we can use the body we | ||||
2039 | // build when defining it as input to the exception specification | ||||
2040 | // computation rather than computing a new body. | ||||
2041 | if (auto *FPT = Ty->getAs<FunctionProtoType>()) { | ||||
2042 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | ||||
2043 | if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) | ||||
2044 | E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); | ||||
2045 | } | ||||
2046 | } | ||||
2047 | |||||
2048 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && | ||||
2049 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && | ||||
2050 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) | ||||
2051 | getCurFunction()->recordUseOfWeak(E); | ||||
2052 | |||||
2053 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
2054 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) | ||||
2055 | FD = IFD->getAnonField(); | ||||
2056 | if (FD) { | ||||
2057 | UnusedPrivateFields.remove(FD); | ||||
2058 | // Just in case we're building an illegal pointer-to-member. | ||||
2059 | if (FD->isBitField()) | ||||
2060 | E->setObjectKind(OK_BitField); | ||||
2061 | } | ||||
2062 | |||||
2063 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier | ||||
2064 | // designates a bit-field. | ||||
2065 | if (auto *BD = dyn_cast<BindingDecl>(D)) | ||||
2066 | if (auto *BE = BD->getBinding()) | ||||
2067 | E->setObjectKind(BE->getObjectKind()); | ||||
2068 | |||||
2069 | return E; | ||||
2070 | } | ||||
2071 | |||||
2072 | /// Decomposes the given name into a DeclarationNameInfo, its location, and | ||||
2073 | /// possibly a list of template arguments. | ||||
2074 | /// | ||||
2075 | /// If this produces template arguments, it is permitted to call | ||||
2076 | /// DecomposeTemplateName. | ||||
2077 | /// | ||||
2078 | /// This actually loses a lot of source location information for | ||||
2079 | /// non-standard name kinds; we should consider preserving that in | ||||
2080 | /// some way. | ||||
2081 | void | ||||
2082 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, | ||||
2083 | TemplateArgumentListInfo &Buffer, | ||||
2084 | DeclarationNameInfo &NameInfo, | ||||
2085 | const TemplateArgumentListInfo *&TemplateArgs) { | ||||
2086 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
2087 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); | ||||
2088 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); | ||||
2089 | |||||
2090 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), | ||||
2091 | Id.TemplateId->NumArgs); | ||||
2092 | translateTemplateArguments(TemplateArgsPtr, Buffer); | ||||
2093 | |||||
2094 | TemplateName TName = Id.TemplateId->Template.get(); | ||||
2095 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; | ||||
2096 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); | ||||
2097 | TemplateArgs = &Buffer; | ||||
2098 | } else { | ||||
2099 | NameInfo = GetNameFromUnqualifiedId(Id); | ||||
2100 | TemplateArgs = nullptr; | ||||
2101 | } | ||||
2102 | } | ||||
2103 | |||||
2104 | static void emitEmptyLookupTypoDiagnostic( | ||||
2105 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, | ||||
2106 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, | ||||
2107 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { | ||||
2108 | DeclContext *Ctx = | ||||
2109 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); | ||||
2110 | if (!TC) { | ||||
2111 | // Emit a special diagnostic for failed member lookups. | ||||
2112 | // FIXME: computing the declaration context might fail here (?) | ||||
2113 | if (Ctx) | ||||
2114 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx | ||||
2115 | << SS.getRange(); | ||||
2116 | else | ||||
2117 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; | ||||
2118 | return; | ||||
2119 | } | ||||
2120 | |||||
2121 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); | ||||
2122 | bool DroppedSpecifier = | ||||
2123 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; | ||||
2124 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2125 | ? diag::note_implicit_param_decl | ||||
2126 | : diag::note_previous_decl; | ||||
2127 | if (!Ctx) | ||||
2128 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, | ||||
2129 | SemaRef.PDiag(NoteID)); | ||||
2130 | else | ||||
2131 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) | ||||
2132 | << Typo << Ctx << DroppedSpecifier | ||||
2133 | << SS.getRange(), | ||||
2134 | SemaRef.PDiag(NoteID)); | ||||
2135 | } | ||||
2136 | |||||
2137 | /// Diagnose a lookup that found results in an enclosing class during error | ||||
2138 | /// recovery. This usually indicates that the results were found in a dependent | ||||
2139 | /// base class that could not be searched as part of a template definition. | ||||
2140 | /// Always issues a diagnostic (though this may be only a warning in MS | ||||
2141 | /// compatibility mode). | ||||
2142 | /// | ||||
2143 | /// Return \c true if the error is unrecoverable, or \c false if the caller | ||||
2144 | /// should attempt to recover using these lookup results. | ||||
2145 | bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { | ||||
2146 | // During a default argument instantiation the CurContext points | ||||
2147 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a | ||||
2148 | // function parameter list, hence add an explicit check. | ||||
2149 | bool isDefaultArgument = | ||||
2150 | !CodeSynthesisContexts.empty() && | ||||
2151 | CodeSynthesisContexts.back().Kind == | ||||
2152 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; | ||||
2153 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); | ||||
2154 | bool isInstance = CurMethod && CurMethod->isInstance() && | ||||
2155 | R.getNamingClass() == CurMethod->getParent() && | ||||
2156 | !isDefaultArgument; | ||||
2157 | |||||
2158 | // There are two ways we can find a class-scope declaration during template | ||||
2159 | // instantiation that we did not find in the template definition: if it is a | ||||
2160 | // member of a dependent base class, or if it is declared after the point of | ||||
2161 | // use in the same class. Distinguish these by comparing the class in which | ||||
2162 | // the member was found to the naming class of the lookup. | ||||
2163 | unsigned DiagID = diag::err_found_in_dependent_base; | ||||
2164 | unsigned NoteID = diag::note_member_declared_at; | ||||
2165 | if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { | ||||
2166 | DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class | ||||
2167 | : diag::err_found_later_in_class; | ||||
2168 | } else if (getLangOpts().MSVCCompat) { | ||||
2169 | DiagID = diag::ext_found_in_dependent_base; | ||||
2170 | NoteID = diag::note_dependent_member_use; | ||||
2171 | } | ||||
2172 | |||||
2173 | if (isInstance) { | ||||
2174 | // Give a code modification hint to insert 'this->'. | ||||
2175 | Diag(R.getNameLoc(), DiagID) | ||||
2176 | << R.getLookupName() | ||||
2177 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); | ||||
2178 | CheckCXXThisCapture(R.getNameLoc()); | ||||
2179 | } else { | ||||
2180 | // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming | ||||
2181 | // they're not shadowed). | ||||
2182 | Diag(R.getNameLoc(), DiagID) << R.getLookupName(); | ||||
2183 | } | ||||
2184 | |||||
2185 | for (NamedDecl *D : R) | ||||
2186 | Diag(D->getLocation(), NoteID); | ||||
2187 | |||||
2188 | // Return true if we are inside a default argument instantiation | ||||
2189 | // and the found name refers to an instance member function, otherwise | ||||
2190 | // the caller will try to create an implicit member call and this is wrong | ||||
2191 | // for default arguments. | ||||
2192 | // | ||||
2193 | // FIXME: Is this special case necessary? We could allow the caller to | ||||
2194 | // diagnose this. | ||||
2195 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { | ||||
2196 | Diag(R.getNameLoc(), diag::err_member_call_without_object); | ||||
2197 | return true; | ||||
2198 | } | ||||
2199 | |||||
2200 | // Tell the callee to try to recover. | ||||
2201 | return false; | ||||
2202 | } | ||||
2203 | |||||
2204 | /// Diagnose an empty lookup. | ||||
2205 | /// | ||||
2206 | /// \return false if new lookup candidates were found | ||||
2207 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | ||||
2208 | CorrectionCandidateCallback &CCC, | ||||
2209 | TemplateArgumentListInfo *ExplicitTemplateArgs, | ||||
2210 | ArrayRef<Expr *> Args, TypoExpr **Out) { | ||||
2211 | DeclarationName Name = R.getLookupName(); | ||||
2212 | |||||
2213 | unsigned diagnostic = diag::err_undeclared_var_use; | ||||
2214 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; | ||||
2215 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || | ||||
2216 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || | ||||
2217 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
2218 | diagnostic = diag::err_undeclared_use; | ||||
2219 | diagnostic_suggest = diag::err_undeclared_use_suggest; | ||||
2220 | } | ||||
2221 | |||||
2222 | // If the original lookup was an unqualified lookup, fake an | ||||
2223 | // unqualified lookup. This is useful when (for example) the | ||||
2224 | // original lookup would not have found something because it was a | ||||
2225 | // dependent name. | ||||
2226 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; | ||||
2227 | while (DC) { | ||||
2228 | if (isa<CXXRecordDecl>(DC)) { | ||||
2229 | LookupQualifiedName(R, DC); | ||||
2230 | |||||
2231 | if (!R.empty()) { | ||||
2232 | // Don't give errors about ambiguities in this lookup. | ||||
2233 | R.suppressDiagnostics(); | ||||
2234 | |||||
2235 | // If there's a best viable function among the results, only mention | ||||
2236 | // that one in the notes. | ||||
2237 | OverloadCandidateSet Candidates(R.getNameLoc(), | ||||
2238 | OverloadCandidateSet::CSK_Normal); | ||||
2239 | AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); | ||||
2240 | OverloadCandidateSet::iterator Best; | ||||
2241 | if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == | ||||
2242 | OR_Success) { | ||||
2243 | R.clear(); | ||||
2244 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | ||||
2245 | R.resolveKind(); | ||||
2246 | } | ||||
2247 | |||||
2248 | return DiagnoseDependentMemberLookup(R); | ||||
2249 | } | ||||
2250 | |||||
2251 | R.clear(); | ||||
2252 | } | ||||
2253 | |||||
2254 | DC = DC->getLookupParent(); | ||||
2255 | } | ||||
2256 | |||||
2257 | // We didn't find anything, so try to correct for a typo. | ||||
2258 | TypoCorrection Corrected; | ||||
2259 | if (S && Out) { | ||||
2260 | SourceLocation TypoLoc = R.getNameLoc(); | ||||
2261 | assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2262, __PRETTY_FUNCTION__)) | ||||
2262 | "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!" ) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2262, __PRETTY_FUNCTION__)); | ||||
2263 | *Out = CorrectTypoDelayed( | ||||
2264 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
2265 | [=](const TypoCorrection &TC) { | ||||
2266 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, | ||||
2267 | diagnostic, diagnostic_suggest); | ||||
2268 | }, | ||||
2269 | nullptr, CTK_ErrorRecovery); | ||||
2270 | if (*Out) | ||||
2271 | return true; | ||||
2272 | } else if (S && | ||||
2273 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), | ||||
2274 | S, &SS, CCC, CTK_ErrorRecovery))) { | ||||
2275 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
2276 | bool DroppedSpecifier = | ||||
2277 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; | ||||
2278 | R.setLookupName(Corrected.getCorrection()); | ||||
2279 | |||||
2280 | bool AcceptableWithRecovery = false; | ||||
2281 | bool AcceptableWithoutRecovery = false; | ||||
2282 | NamedDecl *ND = Corrected.getFoundDecl(); | ||||
2283 | if (ND) { | ||||
2284 | if (Corrected.isOverloaded()) { | ||||
2285 | OverloadCandidateSet OCS(R.getNameLoc(), | ||||
2286 | OverloadCandidateSet::CSK_Normal); | ||||
2287 | OverloadCandidateSet::iterator Best; | ||||
2288 | for (NamedDecl *CD : Corrected) { | ||||
2289 | if (FunctionTemplateDecl *FTD = | ||||
2290 | dyn_cast<FunctionTemplateDecl>(CD)) | ||||
2291 | AddTemplateOverloadCandidate( | ||||
2292 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, | ||||
2293 | Args, OCS); | ||||
2294 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
2295 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) | ||||
2296 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), | ||||
2297 | Args, OCS); | ||||
2298 | } | ||||
2299 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { | ||||
2300 | case OR_Success: | ||||
2301 | ND = Best->FoundDecl; | ||||
2302 | Corrected.setCorrectionDecl(ND); | ||||
2303 | break; | ||||
2304 | default: | ||||
2305 | // FIXME: Arbitrarily pick the first declaration for the note. | ||||
2306 | Corrected.setCorrectionDecl(ND); | ||||
2307 | break; | ||||
2308 | } | ||||
2309 | } | ||||
2310 | R.addDecl(ND); | ||||
2311 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { | ||||
2312 | CXXRecordDecl *Record = nullptr; | ||||
2313 | if (Corrected.getCorrectionSpecifier()) { | ||||
2314 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); | ||||
2315 | Record = Ty->getAsCXXRecordDecl(); | ||||
2316 | } | ||||
2317 | if (!Record) | ||||
2318 | Record = cast<CXXRecordDecl>( | ||||
2319 | ND->getDeclContext()->getRedeclContext()); | ||||
2320 | R.setNamingClass(Record); | ||||
2321 | } | ||||
2322 | |||||
2323 | auto *UnderlyingND = ND->getUnderlyingDecl(); | ||||
2324 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || | ||||
2325 | isa<FunctionTemplateDecl>(UnderlyingND); | ||||
2326 | // FIXME: If we ended up with a typo for a type name or | ||||
2327 | // Objective-C class name, we're in trouble because the parser | ||||
2328 | // is in the wrong place to recover. Suggest the typo | ||||
2329 | // correction, but don't make it a fix-it since we're not going | ||||
2330 | // to recover well anyway. | ||||
2331 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || | ||||
2332 | getAsTypeTemplateDecl(UnderlyingND) || | ||||
2333 | isa<ObjCInterfaceDecl>(UnderlyingND); | ||||
2334 | } else { | ||||
2335 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it | ||||
2336 | // because we aren't able to recover. | ||||
2337 | AcceptableWithoutRecovery = true; | ||||
2338 | } | ||||
2339 | |||||
2340 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { | ||||
2341 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() | ||||
2342 | ? diag::note_implicit_param_decl | ||||
2343 | : diag::note_previous_decl; | ||||
2344 | if (SS.isEmpty()) | ||||
2345 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, | ||||
2346 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2347 | else | ||||
2348 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
2349 | << Name << computeDeclContext(SS, false) | ||||
2350 | << DroppedSpecifier << SS.getRange(), | ||||
2351 | PDiag(NoteID), AcceptableWithRecovery); | ||||
2352 | |||||
2353 | // Tell the callee whether to try to recover. | ||||
2354 | return !AcceptableWithRecovery; | ||||
2355 | } | ||||
2356 | } | ||||
2357 | R.clear(); | ||||
2358 | |||||
2359 | // Emit a special diagnostic for failed member lookups. | ||||
2360 | // FIXME: computing the declaration context might fail here (?) | ||||
2361 | if (!SS.isEmpty()) { | ||||
2362 | Diag(R.getNameLoc(), diag::err_no_member) | ||||
2363 | << Name << computeDeclContext(SS, false) | ||||
2364 | << SS.getRange(); | ||||
2365 | return true; | ||||
2366 | } | ||||
2367 | |||||
2368 | // Give up, we can't recover. | ||||
2369 | Diag(R.getNameLoc(), diagnostic) << Name; | ||||
2370 | return true; | ||||
2371 | } | ||||
2372 | |||||
2373 | /// In Microsoft mode, if we are inside a template class whose parent class has | ||||
2374 | /// dependent base classes, and we can't resolve an unqualified identifier, then | ||||
2375 | /// assume the identifier is a member of a dependent base class. We can only | ||||
2376 | /// recover successfully in static methods, instance methods, and other contexts | ||||
2377 | /// where 'this' is available. This doesn't precisely match MSVC's | ||||
2378 | /// instantiation model, but it's close enough. | ||||
2379 | static Expr * | ||||
2380 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, | ||||
2381 | DeclarationNameInfo &NameInfo, | ||||
2382 | SourceLocation TemplateKWLoc, | ||||
2383 | const TemplateArgumentListInfo *TemplateArgs) { | ||||
2384 | // Only try to recover from lookup into dependent bases in static methods or | ||||
2385 | // contexts where 'this' is available. | ||||
2386 | QualType ThisType = S.getCurrentThisType(); | ||||
2387 | const CXXRecordDecl *RD = nullptr; | ||||
2388 | if (!ThisType.isNull()) | ||||
2389 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); | ||||
2390 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) | ||||
2391 | RD = MD->getParent(); | ||||
2392 | if (!RD || !RD->hasAnyDependentBases()) | ||||
2393 | return nullptr; | ||||
2394 | |||||
2395 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' | ||||
2396 | // is available, suggest inserting 'this->' as a fixit. | ||||
2397 | SourceLocation Loc = NameInfo.getLoc(); | ||||
2398 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); | ||||
2399 | DB << NameInfo.getName() << RD; | ||||
2400 | |||||
2401 | if (!ThisType.isNull()) { | ||||
2402 | DB << FixItHint::CreateInsertion(Loc, "this->"); | ||||
2403 | return CXXDependentScopeMemberExpr::Create( | ||||
2404 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, | ||||
2405 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, | ||||
2406 | /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); | ||||
2407 | } | ||||
2408 | |||||
2409 | // Synthesize a fake NNS that points to the derived class. This will | ||||
2410 | // perform name lookup during template instantiation. | ||||
2411 | CXXScopeSpec SS; | ||||
2412 | auto *NNS = | ||||
2413 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); | ||||
2414 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); | ||||
2415 | return DependentScopeDeclRefExpr::Create( | ||||
2416 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, | ||||
2417 | TemplateArgs); | ||||
2418 | } | ||||
2419 | |||||
2420 | ExprResult | ||||
2421 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, | ||||
2422 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, | ||||
2423 | bool HasTrailingLParen, bool IsAddressOfOperand, | ||||
2424 | CorrectionCandidateCallback *CCC, | ||||
2425 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { | ||||
2426 | assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2427, __PRETTY_FUNCTION__)) | ||||
2427 | "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen") ? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2427, __PRETTY_FUNCTION__)); | ||||
2428 | if (SS.isInvalid()) | ||||
2429 | return ExprError(); | ||||
2430 | |||||
2431 | TemplateArgumentListInfo TemplateArgsBuffer; | ||||
2432 | |||||
2433 | // Decompose the UnqualifiedId into the following data. | ||||
2434 | DeclarationNameInfo NameInfo; | ||||
2435 | const TemplateArgumentListInfo *TemplateArgs; | ||||
2436 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); | ||||
2437 | |||||
2438 | DeclarationName Name = NameInfo.getName(); | ||||
2439 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
2440 | SourceLocation NameLoc = NameInfo.getLoc(); | ||||
2441 | |||||
2442 | if (II && II->isEditorPlaceholder()) { | ||||
2443 | // FIXME: When typed placeholders are supported we can create a typed | ||||
2444 | // placeholder expression node. | ||||
2445 | return ExprError(); | ||||
2446 | } | ||||
2447 | |||||
2448 | // C++ [temp.dep.expr]p3: | ||||
2449 | // An id-expression is type-dependent if it contains: | ||||
2450 | // -- an identifier that was declared with a dependent type, | ||||
2451 | // (note: handled after lookup) | ||||
2452 | // -- a template-id that is dependent, | ||||
2453 | // (note: handled in BuildTemplateIdExpr) | ||||
2454 | // -- a conversion-function-id that specifies a dependent type, | ||||
2455 | // -- a nested-name-specifier that contains a class-name that | ||||
2456 | // names a dependent type. | ||||
2457 | // Determine whether this is a member of an unknown specialization; | ||||
2458 | // we need to handle these differently. | ||||
2459 | bool DependentID = false; | ||||
2460 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && | ||||
2461 | Name.getCXXNameType()->isDependentType()) { | ||||
2462 | DependentID = true; | ||||
2463 | } else if (SS.isSet()) { | ||||
2464 | if (DeclContext *DC = computeDeclContext(SS, false)) { | ||||
2465 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2466 | return ExprError(); | ||||
2467 | } else { | ||||
2468 | DependentID = true; | ||||
2469 | } | ||||
2470 | } | ||||
2471 | |||||
2472 | if (DependentID) | ||||
2473 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2474 | IsAddressOfOperand, TemplateArgs); | ||||
2475 | |||||
2476 | // Perform the required lookup. | ||||
2477 | LookupResult R(*this, NameInfo, | ||||
2478 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) | ||||
2479 | ? LookupObjCImplicitSelfParam | ||||
2480 | : LookupOrdinaryName); | ||||
2481 | if (TemplateKWLoc.isValid() || TemplateArgs) { | ||||
2482 | // Lookup the template name again to correctly establish the context in | ||||
2483 | // which it was found. This is really unfortunate as we already did the | ||||
2484 | // lookup to determine that it was a template name in the first place. If | ||||
2485 | // this becomes a performance hit, we can work harder to preserve those | ||||
2486 | // results until we get here but it's likely not worth it. | ||||
2487 | bool MemberOfUnknownSpecialization; | ||||
2488 | AssumedTemplateKind AssumedTemplate; | ||||
2489 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, | ||||
2490 | MemberOfUnknownSpecialization, TemplateKWLoc, | ||||
2491 | &AssumedTemplate)) | ||||
2492 | return ExprError(); | ||||
2493 | |||||
2494 | if (MemberOfUnknownSpecialization || | ||||
2495 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) | ||||
2496 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2497 | IsAddressOfOperand, TemplateArgs); | ||||
2498 | } else { | ||||
2499 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); | ||||
2500 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); | ||||
2501 | |||||
2502 | // If the result might be in a dependent base class, this is a dependent | ||||
2503 | // id-expression. | ||||
2504 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2505 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, | ||||
2506 | IsAddressOfOperand, TemplateArgs); | ||||
2507 | |||||
2508 | // If this reference is in an Objective-C method, then we need to do | ||||
2509 | // some special Objective-C lookup, too. | ||||
2510 | if (IvarLookupFollowUp) { | ||||
2511 | ExprResult E(LookupInObjCMethod(R, S, II, true)); | ||||
2512 | if (E.isInvalid()) | ||||
2513 | return ExprError(); | ||||
2514 | |||||
2515 | if (Expr *Ex = E.getAs<Expr>()) | ||||
2516 | return Ex; | ||||
2517 | } | ||||
2518 | } | ||||
2519 | |||||
2520 | if (R.isAmbiguous()) | ||||
2521 | return ExprError(); | ||||
2522 | |||||
2523 | // This could be an implicitly declared function reference (legal in C90, | ||||
2524 | // extension in C99, forbidden in C++). | ||||
2525 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { | ||||
2526 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); | ||||
2527 | if (D) R.addDecl(D); | ||||
2528 | } | ||||
2529 | |||||
2530 | // Determine whether this name might be a candidate for | ||||
2531 | // argument-dependent lookup. | ||||
2532 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); | ||||
2533 | |||||
2534 | if (R.empty() && !ADL) { | ||||
2535 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
2536 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, | ||||
2537 | TemplateKWLoc, TemplateArgs)) | ||||
2538 | return E; | ||||
2539 | } | ||||
2540 | |||||
2541 | // Don't diagnose an empty lookup for inline assembly. | ||||
2542 | if (IsInlineAsmIdentifier) | ||||
2543 | return ExprError(); | ||||
2544 | |||||
2545 | // If this name wasn't predeclared and if this is not a function | ||||
2546 | // call, diagnose the problem. | ||||
2547 | TypoExpr *TE = nullptr; | ||||
2548 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() | ||||
2549 | : nullptr); | ||||
2550 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; | ||||
2551 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2552, __PRETTY_FUNCTION__)) | ||||
2552 | "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && "Typo correction callback misconfigured") ? static_cast<void > (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2552, __PRETTY_FUNCTION__)); | ||||
2553 | if (CCC) { | ||||
2554 | // Make sure the callback knows what the typo being diagnosed is. | ||||
2555 | CCC->setTypoName(II); | ||||
2556 | if (SS.isValid()) | ||||
2557 | CCC->setTypoNNS(SS.getScopeRep()); | ||||
2558 | } | ||||
2559 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for | ||||
2560 | // a template name, but we happen to have always already looked up the name | ||||
2561 | // before we get here if it must be a template name. | ||||
2562 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, | ||||
2563 | None, &TE)) { | ||||
2564 | if (TE && KeywordReplacement) { | ||||
2565 | auto &State = getTypoExprState(TE); | ||||
2566 | auto BestTC = State.Consumer->getNextCorrection(); | ||||
2567 | if (BestTC.isKeyword()) { | ||||
2568 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); | ||||
2569 | if (State.DiagHandler) | ||||
2570 | State.DiagHandler(BestTC); | ||||
2571 | KeywordReplacement->startToken(); | ||||
2572 | KeywordReplacement->setKind(II->getTokenID()); | ||||
2573 | KeywordReplacement->setIdentifierInfo(II); | ||||
2574 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); | ||||
2575 | // Clean up the state associated with the TypoExpr, since it has | ||||
2576 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). | ||||
2577 | clearDelayedTypo(TE); | ||||
2578 | // Signal that a correction to a keyword was performed by returning a | ||||
2579 | // valid-but-null ExprResult. | ||||
2580 | return (Expr*)nullptr; | ||||
2581 | } | ||||
2582 | State.Consumer->resetCorrectionStream(); | ||||
2583 | } | ||||
2584 | return TE ? TE : ExprError(); | ||||
2585 | } | ||||
2586 | |||||
2587 | assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2588, __PRETTY_FUNCTION__)) | ||||
2588 | "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2588, __PRETTY_FUNCTION__)); | ||||
2589 | |||||
2590 | // If we found an Objective-C instance variable, let | ||||
2591 | // LookupInObjCMethod build the appropriate expression to | ||||
2592 | // reference the ivar. | ||||
2593 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { | ||||
2594 | R.clear(); | ||||
2595 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); | ||||
2596 | // In a hopelessly buggy code, Objective-C instance variable | ||||
2597 | // lookup fails and no expression will be built to reference it. | ||||
2598 | if (!E.isInvalid() && !E.get()) | ||||
2599 | return ExprError(); | ||||
2600 | return E; | ||||
2601 | } | ||||
2602 | } | ||||
2603 | |||||
2604 | // This is guaranteed from this point on. | ||||
2605 | assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail ("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2605, __PRETTY_FUNCTION__)); | ||||
2606 | |||||
2607 | // Check whether this might be a C++ implicit instance member access. | ||||
2608 | // C++ [class.mfct.non-static]p3: | ||||
2609 | // When an id-expression that is not part of a class member access | ||||
2610 | // syntax and not used to form a pointer to member is used in the | ||||
2611 | // body of a non-static member function of class X, if name lookup | ||||
2612 | // resolves the name in the id-expression to a non-static non-type | ||||
2613 | // member of some class C, the id-expression is transformed into a | ||||
2614 | // class member access expression using (*this) as the | ||||
2615 | // postfix-expression to the left of the . operator. | ||||
2616 | // | ||||
2617 | // But we don't actually need to do this for '&' operands if R | ||||
2618 | // resolved to a function or overloaded function set, because the | ||||
2619 | // expression is ill-formed if it actually works out to be a | ||||
2620 | // non-static member function: | ||||
2621 | // | ||||
2622 | // C++ [expr.ref]p4: | ||||
2623 | // Otherwise, if E1.E2 refers to a non-static member function. . . | ||||
2624 | // [t]he expression can be used only as the left-hand operand of a | ||||
2625 | // member function call. | ||||
2626 | // | ||||
2627 | // There are other safeguards against such uses, but it's important | ||||
2628 | // to get this right here so that we don't end up making a | ||||
2629 | // spuriously dependent expression if we're inside a dependent | ||||
2630 | // instance method. | ||||
2631 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { | ||||
2632 | bool MightBeImplicitMember; | ||||
2633 | if (!IsAddressOfOperand) | ||||
2634 | MightBeImplicitMember = true; | ||||
2635 | else if (!SS.isEmpty()) | ||||
2636 | MightBeImplicitMember = false; | ||||
2637 | else if (R.isOverloadedResult()) | ||||
2638 | MightBeImplicitMember = false; | ||||
2639 | else if (R.isUnresolvableResult()) | ||||
2640 | MightBeImplicitMember = true; | ||||
2641 | else | ||||
2642 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || | ||||
2643 | isa<IndirectFieldDecl>(R.getFoundDecl()) || | ||||
2644 | isa<MSPropertyDecl>(R.getFoundDecl()); | ||||
2645 | |||||
2646 | if (MightBeImplicitMember) | ||||
2647 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, | ||||
2648 | R, TemplateArgs, S); | ||||
2649 | } | ||||
2650 | |||||
2651 | if (TemplateArgs || TemplateKWLoc.isValid()) { | ||||
2652 | |||||
2653 | // In C++1y, if this is a variable template id, then check it | ||||
2654 | // in BuildTemplateIdExpr(). | ||||
2655 | // The single lookup result must be a variable template declaration. | ||||
2656 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && | ||||
2657 | Id.TemplateId->Kind == TNK_Var_template) { | ||||
2658 | assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2659, __PRETTY_FUNCTION__)) | ||||
2659 | "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found." ) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2659, __PRETTY_FUNCTION__)); | ||||
2660 | } | ||||
2661 | |||||
2662 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); | ||||
2663 | } | ||||
2664 | |||||
2665 | return BuildDeclarationNameExpr(SS, R, ADL); | ||||
2666 | } | ||||
2667 | |||||
2668 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified | ||||
2669 | /// declaration name, generally during template instantiation. | ||||
2670 | /// There's a large number of things which don't need to be done along | ||||
2671 | /// this path. | ||||
2672 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( | ||||
2673 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, | ||||
2674 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { | ||||
2675 | DeclContext *DC = computeDeclContext(SS, false); | ||||
2676 | if (!DC) | ||||
2677 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2678 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2679 | |||||
2680 | if (RequireCompleteDeclContext(SS, DC)) | ||||
2681 | return ExprError(); | ||||
2682 | |||||
2683 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
2684 | LookupQualifiedName(R, DC); | ||||
2685 | |||||
2686 | if (R.isAmbiguous()) | ||||
2687 | return ExprError(); | ||||
2688 | |||||
2689 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) | ||||
2690 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
2691 | NameInfo, /*TemplateArgs=*/nullptr); | ||||
2692 | |||||
2693 | if (R.empty()) { | ||||
2694 | // Don't diagnose problems with invalid record decl, the secondary no_member | ||||
2695 | // diagnostic during template instantiation is likely bogus, e.g. if a class | ||||
2696 | // is invalid because it's derived from an invalid base class, then missing | ||||
2697 | // members were likely supposed to be inherited. | ||||
2698 | if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) | ||||
2699 | if (CD->isInvalidDecl()) | ||||
2700 | return ExprError(); | ||||
2701 | Diag(NameInfo.getLoc(), diag::err_no_member) | ||||
2702 | << NameInfo.getName() << DC << SS.getRange(); | ||||
2703 | return ExprError(); | ||||
2704 | } | ||||
2705 | |||||
2706 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { | ||||
2707 | // Diagnose a missing typename if this resolved unambiguously to a type in | ||||
2708 | // a dependent context. If we can recover with a type, downgrade this to | ||||
2709 | // a warning in Microsoft compatibility mode. | ||||
2710 | unsigned DiagID = diag::err_typename_missing; | ||||
2711 | if (RecoveryTSI && getLangOpts().MSVCCompat) | ||||
2712 | DiagID = diag::ext_typename_missing; | ||||
2713 | SourceLocation Loc = SS.getBeginLoc(); | ||||
2714 | auto D = Diag(Loc, DiagID); | ||||
2715 | D << SS.getScopeRep() << NameInfo.getName().getAsString() | ||||
2716 | << SourceRange(Loc, NameInfo.getEndLoc()); | ||||
2717 | |||||
2718 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE | ||||
2719 | // context. | ||||
2720 | if (!RecoveryTSI) | ||||
2721 | return ExprError(); | ||||
2722 | |||||
2723 | // Only issue the fixit if we're prepared to recover. | ||||
2724 | D << FixItHint::CreateInsertion(Loc, "typename "); | ||||
2725 | |||||
2726 | // Recover by pretending this was an elaborated type. | ||||
2727 | QualType Ty = Context.getTypeDeclType(TD); | ||||
2728 | TypeLocBuilder TLB; | ||||
2729 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); | ||||
2730 | |||||
2731 | QualType ET = getElaboratedType(ETK_None, SS, Ty); | ||||
2732 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); | ||||
2733 | QTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
2734 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
2735 | |||||
2736 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); | ||||
2737 | |||||
2738 | return ExprEmpty(); | ||||
2739 | } | ||||
2740 | |||||
2741 | // Defend against this resolving to an implicit member access. We usually | ||||
2742 | // won't get here if this might be a legitimate a class member (we end up in | ||||
2743 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming | ||||
2744 | // a pointer-to-member or in an unevaluated context in C++11. | ||||
2745 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) | ||||
2746 | return BuildPossibleImplicitMemberExpr(SS, | ||||
2747 | /*TemplateKWLoc=*/SourceLocation(), | ||||
2748 | R, /*TemplateArgs=*/nullptr, S); | ||||
2749 | |||||
2750 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); | ||||
2751 | } | ||||
2752 | |||||
2753 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2754 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2755 | /// should form a reference to an ivar. | ||||
2756 | /// | ||||
2757 | /// Ideally, most of this would be done by lookup, but there's | ||||
2758 | /// actually quite a lot of extra work involved. | ||||
2759 | DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2760 | IdentifierInfo *II) { | ||||
2761 | SourceLocation Loc = Lookup.getNameLoc(); | ||||
2762 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2763 | |||||
2764 | // Check for error condition which is already reported. | ||||
2765 | if (!CurMethod) | ||||
2766 | return DeclResult(true); | ||||
2767 | |||||
2768 | // There are two cases to handle here. 1) scoped lookup could have failed, | ||||
2769 | // in which case we should look for an ivar. 2) scoped lookup could have | ||||
2770 | // found a decl, but that decl is outside the current instance method (i.e. | ||||
2771 | // a global variable). In these two cases, we do a lookup for an ivar with | ||||
2772 | // this name, if the lookup sucedes, we replace it our current decl. | ||||
2773 | |||||
2774 | // If we're in a class method, we don't normally want to look for | ||||
2775 | // ivars. But if we don't find anything else, and there's an | ||||
2776 | // ivar, that's an error. | ||||
2777 | bool IsClassMethod = CurMethod->isClassMethod(); | ||||
2778 | |||||
2779 | bool LookForIvars; | ||||
2780 | if (Lookup.empty()) | ||||
2781 | LookForIvars = true; | ||||
2782 | else if (IsClassMethod) | ||||
2783 | LookForIvars = false; | ||||
2784 | else | ||||
2785 | LookForIvars = (Lookup.isSingleResult() && | ||||
2786 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); | ||||
2787 | ObjCInterfaceDecl *IFace = nullptr; | ||||
2788 | if (LookForIvars) { | ||||
2789 | IFace = CurMethod->getClassInterface(); | ||||
2790 | ObjCInterfaceDecl *ClassDeclared; | ||||
2791 | ObjCIvarDecl *IV = nullptr; | ||||
2792 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { | ||||
2793 | // Diagnose using an ivar in a class method. | ||||
2794 | if (IsClassMethod) { | ||||
2795 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2796 | return DeclResult(true); | ||||
2797 | } | ||||
2798 | |||||
2799 | // Diagnose the use of an ivar outside of the declaring class. | ||||
2800 | if (IV->getAccessControl() == ObjCIvarDecl::Private && | ||||
2801 | !declaresSameEntity(ClassDeclared, IFace) && | ||||
2802 | !getLangOpts().DebuggerSupport) | ||||
2803 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); | ||||
2804 | |||||
2805 | // Success. | ||||
2806 | return IV; | ||||
2807 | } | ||||
2808 | } else if (CurMethod->isInstanceMethod()) { | ||||
2809 | // We should warn if a local variable hides an ivar. | ||||
2810 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { | ||||
2811 | ObjCInterfaceDecl *ClassDeclared; | ||||
2812 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { | ||||
2813 | if (IV->getAccessControl() != ObjCIvarDecl::Private || | ||||
2814 | declaresSameEntity(IFace, ClassDeclared)) | ||||
2815 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); | ||||
2816 | } | ||||
2817 | } | ||||
2818 | } else if (Lookup.isSingleResult() && | ||||
2819 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { | ||||
2820 | // If accessing a stand-alone ivar in a class method, this is an error. | ||||
2821 | if (const ObjCIvarDecl *IV = | ||||
2822 | dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { | ||||
2823 | Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); | ||||
2824 | return DeclResult(true); | ||||
2825 | } | ||||
2826 | } | ||||
2827 | |||||
2828 | // Didn't encounter an error, didn't find an ivar. | ||||
2829 | return DeclResult(false); | ||||
2830 | } | ||||
2831 | |||||
2832 | ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, | ||||
2833 | ObjCIvarDecl *IV) { | ||||
2834 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
2835 | assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2836, __PRETTY_FUNCTION__)) | ||||
2836 | "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() && "should not reference ivar from this context") ? static_cast <void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2836, __PRETTY_FUNCTION__)); | ||||
2837 | |||||
2838 | ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); | ||||
2839 | assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context" ) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 2839, __PRETTY_FUNCTION__)); | ||||
2840 | |||||
2841 | // If we're referencing an invalid decl, just return this as a silent | ||||
2842 | // error node. The error diagnostic was already emitted on the decl. | ||||
2843 | if (IV->isInvalidDecl()) | ||||
2844 | return ExprError(); | ||||
2845 | |||||
2846 | // Check if referencing a field with __attribute__((deprecated)). | ||||
2847 | if (DiagnoseUseOfDecl(IV, Loc)) | ||||
2848 | return ExprError(); | ||||
2849 | |||||
2850 | // FIXME: This should use a new expr for a direct reference, don't | ||||
2851 | // turn this into Self->ivar, just return a BareIVarExpr or something. | ||||
2852 | IdentifierInfo &II = Context.Idents.get("self"); | ||||
2853 | UnqualifiedId SelfName; | ||||
2854 | SelfName.setImplicitSelfParam(&II); | ||||
2855 | CXXScopeSpec SelfScopeSpec; | ||||
2856 | SourceLocation TemplateKWLoc; | ||||
2857 | ExprResult SelfExpr = | ||||
2858 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, | ||||
2859 | /*HasTrailingLParen=*/false, | ||||
2860 | /*IsAddressOfOperand=*/false); | ||||
2861 | if (SelfExpr.isInvalid()) | ||||
2862 | return ExprError(); | ||||
2863 | |||||
2864 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); | ||||
2865 | if (SelfExpr.isInvalid()) | ||||
2866 | return ExprError(); | ||||
2867 | |||||
2868 | MarkAnyDeclReferenced(Loc, IV, true); | ||||
2869 | |||||
2870 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); | ||||
2871 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && | ||||
2872 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) | ||||
2873 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); | ||||
2874 | |||||
2875 | ObjCIvarRefExpr *Result = new (Context) | ||||
2876 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, | ||||
2877 | IV->getLocation(), SelfExpr.get(), true, true); | ||||
2878 | |||||
2879 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
2880 | if (!isUnevaluatedContext() && | ||||
2881 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) | ||||
2882 | getCurFunction()->recordUseOfWeak(Result); | ||||
2883 | } | ||||
2884 | if (getLangOpts().ObjCAutoRefCount) | ||||
2885 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) | ||||
2886 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); | ||||
2887 | |||||
2888 | return Result; | ||||
2889 | } | ||||
2890 | |||||
2891 | /// The parser has read a name in, and Sema has detected that we're currently | ||||
2892 | /// inside an ObjC method. Perform some additional checks and determine if we | ||||
2893 | /// should form a reference to an ivar. If so, build an expression referencing | ||||
2894 | /// that ivar. | ||||
2895 | ExprResult | ||||
2896 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, | ||||
2897 | IdentifierInfo *II, bool AllowBuiltinCreation) { | ||||
2898 | // FIXME: Integrate this lookup step into LookupParsedName. | ||||
2899 | DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); | ||||
2900 | if (Ivar.isInvalid()) | ||||
2901 | return ExprError(); | ||||
2902 | if (Ivar.isUsable()) | ||||
2903 | return BuildIvarRefExpr(S, Lookup.getNameLoc(), | ||||
2904 | cast<ObjCIvarDecl>(Ivar.get())); | ||||
2905 | |||||
2906 | if (Lookup.empty() && II && AllowBuiltinCreation) | ||||
2907 | LookupBuiltin(Lookup); | ||||
2908 | |||||
2909 | // Sentinel value saying that we didn't do anything special. | ||||
2910 | return ExprResult(false); | ||||
2911 | } | ||||
2912 | |||||
2913 | /// Cast a base object to a member's actual type. | ||||
2914 | /// | ||||
2915 | /// There are two relevant checks: | ||||
2916 | /// | ||||
2917 | /// C++ [class.access.base]p7: | ||||
2918 | /// | ||||
2919 | /// If a class member access operator [...] is used to access a non-static | ||||
2920 | /// data member or non-static member function, the reference is ill-formed if | ||||
2921 | /// the left operand [...] cannot be implicitly converted to a pointer to the | ||||
2922 | /// naming class of the right operand. | ||||
2923 | /// | ||||
2924 | /// C++ [expr.ref]p7: | ||||
2925 | /// | ||||
2926 | /// If E2 is a non-static data member or a non-static member function, the | ||||
2927 | /// program is ill-formed if the class of which E2 is directly a member is an | ||||
2928 | /// ambiguous base (11.8) of the naming class (11.9.3) of E2. | ||||
2929 | /// | ||||
2930 | /// Note that the latter check does not consider access; the access of the | ||||
2931 | /// "real" base class is checked as appropriate when checking the access of the | ||||
2932 | /// member name. | ||||
2933 | ExprResult | ||||
2934 | Sema::PerformObjectMemberConversion(Expr *From, | ||||
2935 | NestedNameSpecifier *Qualifier, | ||||
2936 | NamedDecl *FoundDecl, | ||||
2937 | NamedDecl *Member) { | ||||
2938 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); | ||||
2939 | if (!RD) | ||||
2940 | return From; | ||||
2941 | |||||
2942 | QualType DestRecordType; | ||||
2943 | QualType DestType; | ||||
2944 | QualType FromRecordType; | ||||
2945 | QualType FromType = From->getType(); | ||||
2946 | bool PointerConversions = false; | ||||
2947 | if (isa<FieldDecl>(Member)) { | ||||
2948 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); | ||||
2949 | auto FromPtrType = FromType->getAs<PointerType>(); | ||||
2950 | DestRecordType = Context.getAddrSpaceQualType( | ||||
2951 | DestRecordType, FromPtrType | ||||
2952 | ? FromType->getPointeeType().getAddressSpace() | ||||
2953 | : FromType.getAddressSpace()); | ||||
2954 | |||||
2955 | if (FromPtrType) { | ||||
2956 | DestType = Context.getPointerType(DestRecordType); | ||||
2957 | FromRecordType = FromPtrType->getPointeeType(); | ||||
2958 | PointerConversions = true; | ||||
2959 | } else { | ||||
2960 | DestType = DestRecordType; | ||||
2961 | FromRecordType = FromType; | ||||
2962 | } | ||||
2963 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { | ||||
2964 | if (Method->isStatic()) | ||||
2965 | return From; | ||||
2966 | |||||
2967 | DestType = Method->getThisType(); | ||||
2968 | DestRecordType = DestType->getPointeeType(); | ||||
2969 | |||||
2970 | if (FromType->getAs<PointerType>()) { | ||||
2971 | FromRecordType = FromType->getPointeeType(); | ||||
2972 | PointerConversions = true; | ||||
2973 | } else { | ||||
2974 | FromRecordType = FromType; | ||||
2975 | DestType = DestRecordType; | ||||
2976 | } | ||||
2977 | |||||
2978 | LangAS FromAS = FromRecordType.getAddressSpace(); | ||||
2979 | LangAS DestAS = DestRecordType.getAddressSpace(); | ||||
2980 | if (FromAS != DestAS) { | ||||
2981 | QualType FromRecordTypeWithoutAS = | ||||
2982 | Context.removeAddrSpaceQualType(FromRecordType); | ||||
2983 | QualType FromTypeWithDestAS = | ||||
2984 | Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); | ||||
2985 | if (PointerConversions) | ||||
2986 | FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); | ||||
2987 | From = ImpCastExprToType(From, FromTypeWithDestAS, | ||||
2988 | CK_AddressSpaceConversion, From->getValueKind()) | ||||
2989 | .get(); | ||||
2990 | } | ||||
2991 | } else { | ||||
2992 | // No conversion necessary. | ||||
2993 | return From; | ||||
2994 | } | ||||
2995 | |||||
2996 | if (DestType->isDependentType() || FromType->isDependentType()) | ||||
2997 | return From; | ||||
2998 | |||||
2999 | // If the unqualified types are the same, no conversion is necessary. | ||||
3000 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3001 | return From; | ||||
3002 | |||||
3003 | SourceRange FromRange = From->getSourceRange(); | ||||
3004 | SourceLocation FromLoc = FromRange.getBegin(); | ||||
3005 | |||||
3006 | ExprValueKind VK = From->getValueKind(); | ||||
3007 | |||||
3008 | // C++ [class.member.lookup]p8: | ||||
3009 | // [...] Ambiguities can often be resolved by qualifying a name with its | ||||
3010 | // class name. | ||||
3011 | // | ||||
3012 | // If the member was a qualified name and the qualified referred to a | ||||
3013 | // specific base subobject type, we'll cast to that intermediate type | ||||
3014 | // first and then to the object in which the member is declared. That allows | ||||
3015 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: | ||||
3016 | // | ||||
3017 | // class Base { public: int x; }; | ||||
3018 | // class Derived1 : public Base { }; | ||||
3019 | // class Derived2 : public Base { }; | ||||
3020 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; | ||||
3021 | // | ||||
3022 | // void VeryDerived::f() { | ||||
3023 | // x = 17; // error: ambiguous base subobjects | ||||
3024 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 | ||||
3025 | // } | ||||
3026 | if (Qualifier && Qualifier->getAsType()) { | ||||
3027 | QualType QType = QualType(Qualifier->getAsType(), 0); | ||||
3028 | assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type" ) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3028, __PRETTY_FUNCTION__)); | ||||
3029 | |||||
3030 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); | ||||
3031 | |||||
3032 | // In C++98, the qualifier type doesn't actually have to be a base | ||||
3033 | // type of the object type, in which case we just ignore it. | ||||
3034 | // Otherwise build the appropriate casts. | ||||
3035 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { | ||||
3036 | CXXCastPath BasePath; | ||||
3037 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, | ||||
3038 | FromLoc, FromRange, &BasePath)) | ||||
3039 | return ExprError(); | ||||
3040 | |||||
3041 | if (PointerConversions) | ||||
3042 | QType = Context.getPointerType(QType); | ||||
3043 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, | ||||
3044 | VK, &BasePath).get(); | ||||
3045 | |||||
3046 | FromType = QType; | ||||
3047 | FromRecordType = QRecordType; | ||||
3048 | |||||
3049 | // If the qualifier type was the same as the destination type, | ||||
3050 | // we're done. | ||||
3051 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) | ||||
3052 | return From; | ||||
3053 | } | ||||
3054 | } | ||||
3055 | |||||
3056 | CXXCastPath BasePath; | ||||
3057 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, | ||||
3058 | FromLoc, FromRange, &BasePath, | ||||
3059 | /*IgnoreAccess=*/true)) | ||||
3060 | return ExprError(); | ||||
3061 | |||||
3062 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, | ||||
3063 | VK, &BasePath); | ||||
3064 | } | ||||
3065 | |||||
3066 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, | ||||
3067 | const LookupResult &R, | ||||
3068 | bool HasTrailingLParen) { | ||||
3069 | // Only when used directly as the postfix-expression of a call. | ||||
3070 | if (!HasTrailingLParen) | ||||
3071 | return false; | ||||
3072 | |||||
3073 | // Never if a scope specifier was provided. | ||||
3074 | if (SS.isSet()) | ||||
3075 | return false; | ||||
3076 | |||||
3077 | // Only in C++ or ObjC++. | ||||
3078 | if (!getLangOpts().CPlusPlus) | ||||
3079 | return false; | ||||
3080 | |||||
3081 | // Turn off ADL when we find certain kinds of declarations during | ||||
3082 | // normal lookup: | ||||
3083 | for (NamedDecl *D : R) { | ||||
3084 | // C++0x [basic.lookup.argdep]p3: | ||||
3085 | // -- a declaration of a class member | ||||
3086 | // Since using decls preserve this property, we check this on the | ||||
3087 | // original decl. | ||||
3088 | if (D->isCXXClassMember()) | ||||
3089 | return false; | ||||
3090 | |||||
3091 | // C++0x [basic.lookup.argdep]p3: | ||||
3092 | // -- a block-scope function declaration that is not a | ||||
3093 | // using-declaration | ||||
3094 | // NOTE: we also trigger this for function templates (in fact, we | ||||
3095 | // don't check the decl type at all, since all other decl types | ||||
3096 | // turn off ADL anyway). | ||||
3097 | if (isa<UsingShadowDecl>(D)) | ||||
3098 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||
3099 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3100 | return false; | ||||
3101 | |||||
3102 | // C++0x [basic.lookup.argdep]p3: | ||||
3103 | // -- a declaration that is neither a function or a function | ||||
3104 | // template | ||||
3105 | // And also for builtin functions. | ||||
3106 | if (isa<FunctionDecl>(D)) { | ||||
3107 | FunctionDecl *FDecl = cast<FunctionDecl>(D); | ||||
3108 | |||||
3109 | // But also builtin functions. | ||||
3110 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) | ||||
3111 | return false; | ||||
3112 | } else if (!isa<FunctionTemplateDecl>(D)) | ||||
3113 | return false; | ||||
3114 | } | ||||
3115 | |||||
3116 | return true; | ||||
3117 | } | ||||
3118 | |||||
3119 | |||||
3120 | /// Diagnoses obvious problems with the use of the given declaration | ||||
3121 | /// as an expression. This is only actually called for lookups that | ||||
3122 | /// were not overloaded, and it doesn't promise that the declaration | ||||
3123 | /// will in fact be used. | ||||
3124 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { | ||||
3125 | if (D->isInvalidDecl()) | ||||
3126 | return true; | ||||
3127 | |||||
3128 | if (isa<TypedefNameDecl>(D)) { | ||||
3129 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); | ||||
3130 | return true; | ||||
3131 | } | ||||
3132 | |||||
3133 | if (isa<ObjCInterfaceDecl>(D)) { | ||||
3134 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); | ||||
3135 | return true; | ||||
3136 | } | ||||
3137 | |||||
3138 | if (isa<NamespaceDecl>(D)) { | ||||
3139 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); | ||||
3140 | return true; | ||||
3141 | } | ||||
3142 | |||||
3143 | return false; | ||||
3144 | } | ||||
3145 | |||||
3146 | // Certain multiversion types should be treated as overloaded even when there is | ||||
3147 | // only one result. | ||||
3148 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { | ||||
3149 | assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result" ) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3149, __PRETTY_FUNCTION__)); | ||||
3150 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); | ||||
3151 | return FD && | ||||
3152 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); | ||||
3153 | } | ||||
3154 | |||||
3155 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, | ||||
3156 | LookupResult &R, bool NeedsADL, | ||||
3157 | bool AcceptInvalidDecl) { | ||||
3158 | // If this is a single, fully-resolved result and we don't need ADL, | ||||
3159 | // just build an ordinary singleton decl ref. | ||||
3160 | if (!NeedsADL && R.isSingleResult() && | ||||
3161 | !R.getAsSingle<FunctionTemplateDecl>() && | ||||
3162 | !ShouldLookupResultBeMultiVersionOverload(R)) | ||||
3163 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), | ||||
3164 | R.getRepresentativeDecl(), nullptr, | ||||
3165 | AcceptInvalidDecl); | ||||
3166 | |||||
3167 | // We only need to check the declaration if there's exactly one | ||||
3168 | // result, because in the overloaded case the results can only be | ||||
3169 | // functions and function templates. | ||||
3170 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && | ||||
3171 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) | ||||
3172 | return ExprError(); | ||||
3173 | |||||
3174 | // Otherwise, just build an unresolved lookup expression. Suppress | ||||
3175 | // any lookup-related diagnostics; we'll hash these out later, when | ||||
3176 | // we've picked a target. | ||||
3177 | R.suppressDiagnostics(); | ||||
3178 | |||||
3179 | UnresolvedLookupExpr *ULE | ||||
3180 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), | ||||
3181 | SS.getWithLocInContext(Context), | ||||
3182 | R.getLookupNameInfo(), | ||||
3183 | NeedsADL, R.isOverloadedResult(), | ||||
3184 | R.begin(), R.end()); | ||||
3185 | |||||
3186 | return ULE; | ||||
3187 | } | ||||
3188 | |||||
3189 | static void | ||||
3190 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
3191 | ValueDecl *var, DeclContext *DC); | ||||
3192 | |||||
3193 | /// Complete semantic analysis for a reference to the given declaration. | ||||
3194 | ExprResult Sema::BuildDeclarationNameExpr( | ||||
3195 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | ||||
3196 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, | ||||
3197 | bool AcceptInvalidDecl) { | ||||
3198 | assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast <void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3198, __PRETTY_FUNCTION__)); | ||||
3199 | assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3200, __PRETTY_FUNCTION__)) | ||||
3200 | "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template" ) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3200, __PRETTY_FUNCTION__)); | ||||
3201 | |||||
3202 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3203 | if (CheckDeclInExpr(*this, Loc, D)) | ||||
3204 | return ExprError(); | ||||
3205 | |||||
3206 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { | ||||
3207 | // Specifically diagnose references to class templates that are missing | ||||
3208 | // a template argument list. | ||||
3209 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); | ||||
3210 | return ExprError(); | ||||
3211 | } | ||||
3212 | |||||
3213 | // Make sure that we're referring to a value. | ||||
3214 | ValueDecl *VD = dyn_cast<ValueDecl>(D); | ||||
3215 | if (!VD) { | ||||
3216 | Diag(Loc, diag::err_ref_non_value) | ||||
3217 | << D << SS.getRange(); | ||||
3218 | Diag(D->getLocation(), diag::note_declared_at); | ||||
3219 | return ExprError(); | ||||
3220 | } | ||||
3221 | |||||
3222 | // Check whether this declaration can be used. Note that we suppress | ||||
3223 | // this check when we're going to perform argument-dependent lookup | ||||
3224 | // on this function name, because this might not be the function | ||||
3225 | // that overload resolution actually selects. | ||||
3226 | if (DiagnoseUseOfDecl(VD, Loc)) | ||||
3227 | return ExprError(); | ||||
3228 | |||||
3229 | // Only create DeclRefExpr's for valid Decl's. | ||||
3230 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) | ||||
3231 | return ExprError(); | ||||
3232 | |||||
3233 | // Handle members of anonymous structs and unions. If we got here, | ||||
3234 | // and the reference is to a class member indirect field, then this | ||||
3235 | // must be the subject of a pointer-to-member expression. | ||||
3236 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) | ||||
3237 | if (!indirectField->isCXXClassMember()) | ||||
3238 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), | ||||
3239 | indirectField); | ||||
3240 | |||||
3241 | { | ||||
3242 | QualType type = VD->getType(); | ||||
3243 | if (type.isNull()) | ||||
3244 | return ExprError(); | ||||
3245 | ExprValueKind valueKind = VK_RValue; | ||||
3246 | |||||
3247 | // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of | ||||
3248 | // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, | ||||
3249 | // is expanded by some outer '...' in the context of the use. | ||||
3250 | type = type.getNonPackExpansionType(); | ||||
3251 | |||||
3252 | switch (D->getKind()) { | ||||
3253 | // Ignore all the non-ValueDecl kinds. | ||||
3254 | #define ABSTRACT_DECL(kind) | ||||
3255 | #define VALUE(type, base) | ||||
3256 | #define DECL(type, base) \ | ||||
3257 | case Decl::type: | ||||
3258 | #include "clang/AST/DeclNodes.inc" | ||||
3259 | llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3259); | ||||
3260 | |||||
3261 | // These shouldn't make it here. | ||||
3262 | case Decl::ObjCAtDefsField: | ||||
3263 | llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3263); | ||||
3264 | |||||
3265 | // Enum constants are always r-values and never references. | ||||
3266 | // Unresolved using declarations are dependent. | ||||
3267 | case Decl::EnumConstant: | ||||
3268 | case Decl::UnresolvedUsingValue: | ||||
3269 | case Decl::OMPDeclareReduction: | ||||
3270 | case Decl::OMPDeclareMapper: | ||||
3271 | valueKind = VK_RValue; | ||||
3272 | break; | ||||
3273 | |||||
3274 | // Fields and indirect fields that got here must be for | ||||
3275 | // pointer-to-member expressions; we just call them l-values for | ||||
3276 | // internal consistency, because this subexpression doesn't really | ||||
3277 | // exist in the high-level semantics. | ||||
3278 | case Decl::Field: | ||||
3279 | case Decl::IndirectField: | ||||
3280 | case Decl::ObjCIvar: | ||||
3281 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3282, __PRETTY_FUNCTION__)) | ||||
3282 | "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3282, __PRETTY_FUNCTION__)); | ||||
3283 | |||||
3284 | // These can't have reference type in well-formed programs, but | ||||
3285 | // for internal consistency we do this anyway. | ||||
3286 | type = type.getNonReferenceType(); | ||||
3287 | valueKind = VK_LValue; | ||||
3288 | break; | ||||
3289 | |||||
3290 | // Non-type template parameters are either l-values or r-values | ||||
3291 | // depending on the type. | ||||
3292 | case Decl::NonTypeTemplateParm: { | ||||
3293 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { | ||||
3294 | type = reftype->getPointeeType(); | ||||
3295 | valueKind = VK_LValue; // even if the parameter is an r-value reference | ||||
3296 | break; | ||||
3297 | } | ||||
3298 | |||||
3299 | // [expr.prim.id.unqual]p2: | ||||
3300 | // If the entity is a template parameter object for a template | ||||
3301 | // parameter of type T, the type of the expression is const T. | ||||
3302 | // [...] The expression is an lvalue if the entity is a [...] template | ||||
3303 | // parameter object. | ||||
3304 | if (type->isRecordType()) { | ||||
3305 | type = type.getUnqualifiedType().withConst(); | ||||
3306 | valueKind = VK_LValue; | ||||
3307 | break; | ||||
3308 | } | ||||
3309 | |||||
3310 | // For non-references, we need to strip qualifiers just in case | ||||
3311 | // the template parameter was declared as 'const int' or whatever. | ||||
3312 | valueKind = VK_RValue; | ||||
3313 | type = type.getUnqualifiedType(); | ||||
3314 | break; | ||||
3315 | } | ||||
3316 | |||||
3317 | case Decl::Var: | ||||
3318 | case Decl::VarTemplateSpecialization: | ||||
3319 | case Decl::VarTemplatePartialSpecialization: | ||||
3320 | case Decl::Decomposition: | ||||
3321 | case Decl::OMPCapturedExpr: | ||||
3322 | // In C, "extern void blah;" is valid and is an r-value. | ||||
3323 | if (!getLangOpts().CPlusPlus && | ||||
3324 | !type.hasQualifiers() && | ||||
3325 | type->isVoidType()) { | ||||
3326 | valueKind = VK_RValue; | ||||
3327 | break; | ||||
3328 | } | ||||
3329 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3330 | |||||
3331 | case Decl::ImplicitParam: | ||||
3332 | case Decl::ParmVar: { | ||||
3333 | // These are always l-values. | ||||
3334 | valueKind = VK_LValue; | ||||
3335 | type = type.getNonReferenceType(); | ||||
3336 | |||||
3337 | // FIXME: Does the addition of const really only apply in | ||||
3338 | // potentially-evaluated contexts? Since the variable isn't actually | ||||
3339 | // captured in an unevaluated context, it seems that the answer is no. | ||||
3340 | if (!isUnevaluatedContext()) { | ||||
3341 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); | ||||
3342 | if (!CapturedType.isNull()) | ||||
3343 | type = CapturedType; | ||||
3344 | } | ||||
3345 | |||||
3346 | break; | ||||
3347 | } | ||||
3348 | |||||
3349 | case Decl::Binding: { | ||||
3350 | // These are always lvalues. | ||||
3351 | valueKind = VK_LValue; | ||||
3352 | type = type.getNonReferenceType(); | ||||
3353 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually | ||||
3354 | // decides how that's supposed to work. | ||||
3355 | auto *BD = cast<BindingDecl>(VD); | ||||
3356 | if (BD->getDeclContext() != CurContext) { | ||||
3357 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); | ||||
3358 | if (DD && DD->hasLocalStorage()) | ||||
3359 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); | ||||
3360 | } | ||||
3361 | break; | ||||
3362 | } | ||||
3363 | |||||
3364 | case Decl::Function: { | ||||
3365 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { | ||||
3366 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { | ||||
3367 | type = Context.BuiltinFnTy; | ||||
3368 | valueKind = VK_RValue; | ||||
3369 | break; | ||||
3370 | } | ||||
3371 | } | ||||
3372 | |||||
3373 | const FunctionType *fty = type->castAs<FunctionType>(); | ||||
3374 | |||||
3375 | // If we're referring to a function with an __unknown_anytype | ||||
3376 | // result type, make the entire expression __unknown_anytype. | ||||
3377 | if (fty->getReturnType() == Context.UnknownAnyTy) { | ||||
3378 | type = Context.UnknownAnyTy; | ||||
3379 | valueKind = VK_RValue; | ||||
3380 | break; | ||||
3381 | } | ||||
3382 | |||||
3383 | // Functions are l-values in C++. | ||||
3384 | if (getLangOpts().CPlusPlus) { | ||||
3385 | valueKind = VK_LValue; | ||||
3386 | break; | ||||
3387 | } | ||||
3388 | |||||
3389 | // C99 DR 316 says that, if a function type comes from a | ||||
3390 | // function definition (without a prototype), that type is only | ||||
3391 | // used for checking compatibility. Therefore, when referencing | ||||
3392 | // the function, we pretend that we don't have the full function | ||||
3393 | // type. | ||||
3394 | if (!cast<FunctionDecl>(VD)->hasPrototype() && | ||||
3395 | isa<FunctionProtoType>(fty)) | ||||
3396 | type = Context.getFunctionNoProtoType(fty->getReturnType(), | ||||
3397 | fty->getExtInfo()); | ||||
3398 | |||||
3399 | // Functions are r-values in C. | ||||
3400 | valueKind = VK_RValue; | ||||
3401 | break; | ||||
3402 | } | ||||
3403 | |||||
3404 | case Decl::CXXDeductionGuide: | ||||
3405 | llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3405); | ||||
3406 | |||||
3407 | case Decl::MSProperty: | ||||
3408 | case Decl::MSGuid: | ||||
3409 | case Decl::TemplateParamObject: | ||||
3410 | // FIXME: Should MSGuidDecl and template parameter objects be subject to | ||||
3411 | // capture in OpenMP, or duplicated between host and device? | ||||
3412 | valueKind = VK_LValue; | ||||
3413 | break; | ||||
3414 | |||||
3415 | case Decl::CXXMethod: | ||||
3416 | // If we're referring to a method with an __unknown_anytype | ||||
3417 | // result type, make the entire expression __unknown_anytype. | ||||
3418 | // This should only be possible with a type written directly. | ||||
3419 | if (const FunctionProtoType *proto | ||||
3420 | = dyn_cast<FunctionProtoType>(VD->getType())) | ||||
3421 | if (proto->getReturnType() == Context.UnknownAnyTy) { | ||||
3422 | type = Context.UnknownAnyTy; | ||||
3423 | valueKind = VK_RValue; | ||||
3424 | break; | ||||
3425 | } | ||||
3426 | |||||
3427 | // C++ methods are l-values if static, r-values if non-static. | ||||
3428 | if (cast<CXXMethodDecl>(VD)->isStatic()) { | ||||
3429 | valueKind = VK_LValue; | ||||
3430 | break; | ||||
3431 | } | ||||
3432 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3433 | |||||
3434 | case Decl::CXXConversion: | ||||
3435 | case Decl::CXXDestructor: | ||||
3436 | case Decl::CXXConstructor: | ||||
3437 | valueKind = VK_RValue; | ||||
3438 | break; | ||||
3439 | } | ||||
3440 | |||||
3441 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, | ||||
3442 | /*FIXME: TemplateKWLoc*/ SourceLocation(), | ||||
3443 | TemplateArgs); | ||||
3444 | } | ||||
3445 | } | ||||
3446 | |||||
3447 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, | ||||
3448 | SmallString<32> &Target) { | ||||
3449 | Target.resize(CharByteWidth * (Source.size() + 1)); | ||||
3450 | char *ResultPtr = &Target[0]; | ||||
3451 | const llvm::UTF8 *ErrorPtr; | ||||
3452 | bool success = | ||||
3453 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); | ||||
3454 | (void)success; | ||||
3455 | assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3455, __PRETTY_FUNCTION__)); | ||||
3456 | Target.resize(ResultPtr - &Target[0]); | ||||
3457 | } | ||||
3458 | |||||
3459 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, | ||||
3460 | PredefinedExpr::IdentKind IK) { | ||||
3461 | // Pick the current block, lambda, captured statement or function. | ||||
3462 | Decl *currentDecl = nullptr; | ||||
3463 | if (const BlockScopeInfo *BSI = getCurBlock()) | ||||
3464 | currentDecl = BSI->TheDecl; | ||||
3465 | else if (const LambdaScopeInfo *LSI = getCurLambda()) | ||||
3466 | currentDecl = LSI->CallOperator; | ||||
3467 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) | ||||
3468 | currentDecl = CSI->TheCapturedDecl; | ||||
3469 | else | ||||
3470 | currentDecl = getCurFunctionOrMethodDecl(); | ||||
3471 | |||||
3472 | if (!currentDecl) { | ||||
3473 | Diag(Loc, diag::ext_predef_outside_function); | ||||
3474 | currentDecl = Context.getTranslationUnitDecl(); | ||||
3475 | } | ||||
3476 | |||||
3477 | QualType ResTy; | ||||
3478 | StringLiteral *SL = nullptr; | ||||
3479 | if (cast<DeclContext>(currentDecl)->isDependentContext()) | ||||
3480 | ResTy = Context.DependentTy; | ||||
3481 | else { | ||||
3482 | // Pre-defined identifiers are of type char[x], where x is the length of | ||||
3483 | // the string. | ||||
3484 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); | ||||
3485 | unsigned Length = Str.length(); | ||||
3486 | |||||
3487 | llvm::APInt LengthI(32, Length + 1); | ||||
3488 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { | ||||
3489 | ResTy = | ||||
3490 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); | ||||
3491 | SmallString<32> RawChars; | ||||
3492 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), | ||||
3493 | Str, RawChars); | ||||
3494 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3495 | ArrayType::Normal, | ||||
3496 | /*IndexTypeQuals*/ 0); | ||||
3497 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, | ||||
3498 | /*Pascal*/ false, ResTy, Loc); | ||||
3499 | } else { | ||||
3500 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); | ||||
3501 | ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, | ||||
3502 | ArrayType::Normal, | ||||
3503 | /*IndexTypeQuals*/ 0); | ||||
3504 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, | ||||
3505 | /*Pascal*/ false, ResTy, Loc); | ||||
3506 | } | ||||
3507 | } | ||||
3508 | |||||
3509 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); | ||||
3510 | } | ||||
3511 | |||||
3512 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { | ||||
3513 | PredefinedExpr::IdentKind IK; | ||||
3514 | |||||
3515 | switch (Kind) { | ||||
3516 | default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3516); | ||||
3517 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] | ||||
3518 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; | ||||
3519 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] | ||||
3520 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] | ||||
3521 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] | ||||
3522 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] | ||||
3523 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; | ||||
3524 | } | ||||
3525 | |||||
3526 | return BuildPredefinedExpr(Loc, IK); | ||||
3527 | } | ||||
3528 | |||||
3529 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { | ||||
3530 | SmallString<16> CharBuffer; | ||||
3531 | bool Invalid = false; | ||||
3532 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); | ||||
3533 | if (Invalid) | ||||
3534 | return ExprError(); | ||||
3535 | |||||
3536 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), | ||||
3537 | PP, Tok.getKind()); | ||||
3538 | if (Literal.hadError()) | ||||
3539 | return ExprError(); | ||||
3540 | |||||
3541 | QualType Ty; | ||||
3542 | if (Literal.isWide()) | ||||
3543 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. | ||||
3544 | else if (Literal.isUTF8() && getLangOpts().Char8) | ||||
3545 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. | ||||
3546 | else if (Literal.isUTF16()) | ||||
3547 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. | ||||
3548 | else if (Literal.isUTF32()) | ||||
3549 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. | ||||
3550 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) | ||||
3551 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. | ||||
3552 | else | ||||
3553 | Ty = Context.CharTy; // 'x' -> char in C++ | ||||
3554 | |||||
3555 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; | ||||
3556 | if (Literal.isWide()) | ||||
3557 | Kind = CharacterLiteral::Wide; | ||||
3558 | else if (Literal.isUTF16()) | ||||
3559 | Kind = CharacterLiteral::UTF16; | ||||
3560 | else if (Literal.isUTF32()) | ||||
3561 | Kind = CharacterLiteral::UTF32; | ||||
3562 | else if (Literal.isUTF8()) | ||||
3563 | Kind = CharacterLiteral::UTF8; | ||||
3564 | |||||
3565 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, | ||||
3566 | Tok.getLocation()); | ||||
3567 | |||||
3568 | if (Literal.getUDSuffix().empty()) | ||||
3569 | return Lit; | ||||
3570 | |||||
3571 | // We're building a user-defined literal. | ||||
3572 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3573 | SourceLocation UDSuffixLoc = | ||||
3574 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3575 | |||||
3576 | // Make sure we're allowed user-defined literals here. | ||||
3577 | if (!UDLScope) | ||||
3578 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); | ||||
3579 | |||||
3580 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form | ||||
3581 | // operator "" X (ch) | ||||
3582 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, | ||||
3583 | Lit, Tok.getLocation()); | ||||
3584 | } | ||||
3585 | |||||
3586 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { | ||||
3587 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3588 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), | ||||
3589 | Context.IntTy, Loc); | ||||
3590 | } | ||||
3591 | |||||
3592 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, | ||||
3593 | QualType Ty, SourceLocation Loc) { | ||||
3594 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); | ||||
3595 | |||||
3596 | using llvm::APFloat; | ||||
3597 | APFloat Val(Format); | ||||
3598 | |||||
3599 | APFloat::opStatus result = Literal.GetFloatValue(Val); | ||||
3600 | |||||
3601 | // Overflow is always an error, but underflow is only an error if | ||||
3602 | // we underflowed to zero (APFloat reports denormals as underflow). | ||||
3603 | if ((result & APFloat::opOverflow) || | ||||
3604 | ((result & APFloat::opUnderflow) && Val.isZero())) { | ||||
3605 | unsigned diagnostic; | ||||
3606 | SmallString<20> buffer; | ||||
3607 | if (result & APFloat::opOverflow) { | ||||
3608 | diagnostic = diag::warn_float_overflow; | ||||
3609 | APFloat::getLargest(Format).toString(buffer); | ||||
3610 | } else { | ||||
3611 | diagnostic = diag::warn_float_underflow; | ||||
3612 | APFloat::getSmallest(Format).toString(buffer); | ||||
3613 | } | ||||
3614 | |||||
3615 | S.Diag(Loc, diagnostic) | ||||
3616 | << Ty | ||||
3617 | << StringRef(buffer.data(), buffer.size()); | ||||
3618 | } | ||||
3619 | |||||
3620 | bool isExact = (result == APFloat::opOK); | ||||
3621 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); | ||||
3622 | } | ||||
3623 | |||||
3624 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { | ||||
3625 | assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void> (0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3625, __PRETTY_FUNCTION__)); | ||||
3626 | |||||
3627 | if (E->isValueDependent()) | ||||
3628 | return false; | ||||
3629 | |||||
3630 | QualType QT = E->getType(); | ||||
3631 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { | ||||
3632 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; | ||||
3633 | return true; | ||||
3634 | } | ||||
3635 | |||||
3636 | llvm::APSInt ValueAPS; | ||||
3637 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); | ||||
3638 | |||||
3639 | if (R.isInvalid()) | ||||
3640 | return true; | ||||
3641 | |||||
3642 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); | ||||
3643 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { | ||||
3644 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) | ||||
3645 | << ValueAPS.toString(10) << ValueIsPositive; | ||||
3646 | return true; | ||||
3647 | } | ||||
3648 | |||||
3649 | return false; | ||||
3650 | } | ||||
3651 | |||||
3652 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { | ||||
3653 | // Fast path for a single digit (which is quite common). A single digit | ||||
3654 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. | ||||
3655 | if (Tok.getLength() == 1) { | ||||
3656 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); | ||||
3657 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); | ||||
3658 | } | ||||
3659 | |||||
3660 | SmallString<128> SpellingBuffer; | ||||
3661 | // NumericLiteralParser wants to overread by one character. Add padding to | ||||
3662 | // the buffer in case the token is copied to the buffer. If getSpelling() | ||||
3663 | // returns a StringRef to the memory buffer, it should have a null char at | ||||
3664 | // the EOF, so it is also safe. | ||||
3665 | SpellingBuffer.resize(Tok.getLength() + 1); | ||||
3666 | |||||
3667 | // Get the spelling of the token, which eliminates trigraphs, etc. | ||||
3668 | bool Invalid = false; | ||||
3669 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); | ||||
3670 | if (Invalid) | ||||
3671 | return ExprError(); | ||||
3672 | |||||
3673 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), | ||||
3674 | PP.getSourceManager(), PP.getLangOpts(), | ||||
3675 | PP.getTargetInfo(), PP.getDiagnostics()); | ||||
3676 | if (Literal.hadError) | ||||
3677 | return ExprError(); | ||||
3678 | |||||
3679 | if (Literal.hasUDSuffix()) { | ||||
3680 | // We're building a user-defined literal. | ||||
3681 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); | ||||
3682 | SourceLocation UDSuffixLoc = | ||||
3683 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); | ||||
3684 | |||||
3685 | // Make sure we're allowed user-defined literals here. | ||||
3686 | if (!UDLScope) | ||||
3687 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); | ||||
3688 | |||||
3689 | QualType CookedTy; | ||||
3690 | if (Literal.isFloatingLiteral()) { | ||||
3691 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type | ||||
3692 | // long double, the literal is treated as a call of the form | ||||
3693 | // operator "" X (f L) | ||||
3694 | CookedTy = Context.LongDoubleTy; | ||||
3695 | } else { | ||||
3696 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type | ||||
3697 | // unsigned long long, the literal is treated as a call of the form | ||||
3698 | // operator "" X (n ULL) | ||||
3699 | CookedTy = Context.UnsignedLongLongTy; | ||||
3700 | } | ||||
3701 | |||||
3702 | DeclarationName OpName = | ||||
3703 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); | ||||
3704 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); | ||||
3705 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); | ||||
3706 | |||||
3707 | SourceLocation TokLoc = Tok.getLocation(); | ||||
3708 | |||||
3709 | // Perform literal operator lookup to determine if we're building a raw | ||||
3710 | // literal or a cooked one. | ||||
3711 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); | ||||
3712 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, | ||||
3713 | /*AllowRaw*/ true, /*AllowTemplate*/ true, | ||||
3714 | /*AllowStringTemplatePack*/ false, | ||||
3715 | /*DiagnoseMissing*/ !Literal.isImaginary)) { | ||||
3716 | case LOLR_ErrorNoDiagnostic: | ||||
3717 | // Lookup failure for imaginary constants isn't fatal, there's still the | ||||
3718 | // GNU extension producing _Complex types. | ||||
3719 | break; | ||||
3720 | case LOLR_Error: | ||||
3721 | return ExprError(); | ||||
3722 | case LOLR_Cooked: { | ||||
3723 | Expr *Lit; | ||||
3724 | if (Literal.isFloatingLiteral()) { | ||||
3725 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); | ||||
3726 | } else { | ||||
3727 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); | ||||
3728 | if (Literal.GetIntegerValue(ResultVal)) | ||||
3729 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3730 | << /* Unsigned */ 1; | ||||
3731 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, | ||||
3732 | Tok.getLocation()); | ||||
3733 | } | ||||
3734 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3735 | } | ||||
3736 | |||||
3737 | case LOLR_Raw: { | ||||
3738 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the | ||||
3739 | // literal is treated as a call of the form | ||||
3740 | // operator "" X ("n") | ||||
3741 | unsigned Length = Literal.getUDSuffixOffset(); | ||||
3742 | QualType StrTy = Context.getConstantArrayType( | ||||
3743 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), | ||||
3744 | llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); | ||||
3745 | Expr *Lit = StringLiteral::Create( | ||||
3746 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, | ||||
3747 | /*Pascal*/false, StrTy, &TokLoc, 1); | ||||
3748 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); | ||||
3749 | } | ||||
3750 | |||||
3751 | case LOLR_Template: { | ||||
3752 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator | ||||
3753 | // template), L is treated as a call fo the form | ||||
3754 | // operator "" X <'c1', 'c2', ... 'ck'>() | ||||
3755 | // where n is the source character sequence c1 c2 ... ck. | ||||
3756 | TemplateArgumentListInfo ExplicitArgs; | ||||
3757 | unsigned CharBits = Context.getIntWidth(Context.CharTy); | ||||
3758 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); | ||||
3759 | llvm::APSInt Value(CharBits, CharIsUnsigned); | ||||
3760 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { | ||||
3761 | Value = TokSpelling[I]; | ||||
3762 | TemplateArgument Arg(Context, Value, Context.CharTy); | ||||
3763 | TemplateArgumentLocInfo ArgInfo; | ||||
3764 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); | ||||
3765 | } | ||||
3766 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, | ||||
3767 | &ExplicitArgs); | ||||
3768 | } | ||||
3769 | case LOLR_StringTemplatePack: | ||||
3770 | llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3770); | ||||
3771 | } | ||||
3772 | } | ||||
3773 | |||||
3774 | Expr *Res; | ||||
3775 | |||||
3776 | if (Literal.isFixedPointLiteral()) { | ||||
3777 | QualType Ty; | ||||
3778 | |||||
3779 | if (Literal.isAccum) { | ||||
3780 | if (Literal.isHalf) { | ||||
3781 | Ty = Context.ShortAccumTy; | ||||
3782 | } else if (Literal.isLong) { | ||||
3783 | Ty = Context.LongAccumTy; | ||||
3784 | } else { | ||||
3785 | Ty = Context.AccumTy; | ||||
3786 | } | ||||
3787 | } else if (Literal.isFract) { | ||||
3788 | if (Literal.isHalf) { | ||||
3789 | Ty = Context.ShortFractTy; | ||||
3790 | } else if (Literal.isLong) { | ||||
3791 | Ty = Context.LongFractTy; | ||||
3792 | } else { | ||||
3793 | Ty = Context.FractTy; | ||||
3794 | } | ||||
3795 | } | ||||
3796 | |||||
3797 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); | ||||
3798 | |||||
3799 | bool isSigned = !Literal.isUnsigned; | ||||
3800 | unsigned scale = Context.getFixedPointScale(Ty); | ||||
3801 | unsigned bit_width = Context.getTypeInfo(Ty).Width; | ||||
3802 | |||||
3803 | llvm::APInt Val(bit_width, 0, isSigned); | ||||
3804 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); | ||||
3805 | bool ValIsZero = Val.isNullValue() && !Overflowed; | ||||
3806 | |||||
3807 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); | ||||
3808 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) | ||||
3809 | // Clause 6.4.4 - The value of a constant shall be in the range of | ||||
3810 | // representable values for its type, with exception for constants of a | ||||
3811 | // fract type with a value of exactly 1; such a constant shall denote | ||||
3812 | // the maximal value for the type. | ||||
3813 | --Val; | ||||
3814 | else if (Val.ugt(MaxVal) || Overflowed) | ||||
3815 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); | ||||
3816 | |||||
3817 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, | ||||
3818 | Tok.getLocation(), scale); | ||||
3819 | } else if (Literal.isFloatingLiteral()) { | ||||
3820 | QualType Ty; | ||||
3821 | if (Literal.isHalf){ | ||||
3822 | if (getOpenCLOptions().isEnabled("cl_khr_fp16")) | ||||
3823 | Ty = Context.HalfTy; | ||||
3824 | else { | ||||
3825 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); | ||||
3826 | return ExprError(); | ||||
3827 | } | ||||
3828 | } else if (Literal.isFloat) | ||||
3829 | Ty = Context.FloatTy; | ||||
3830 | else if (Literal.isLong) | ||||
3831 | Ty = Context.LongDoubleTy; | ||||
3832 | else if (Literal.isFloat16) | ||||
3833 | Ty = Context.Float16Ty; | ||||
3834 | else if (Literal.isFloat128) | ||||
3835 | Ty = Context.Float128Ty; | ||||
3836 | else | ||||
3837 | Ty = Context.DoubleTy; | ||||
3838 | |||||
3839 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); | ||||
3840 | |||||
3841 | if (Ty == Context.DoubleTy) { | ||||
3842 | if (getLangOpts().SinglePrecisionConstants) { | ||||
3843 | if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { | ||||
3844 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3845 | } | ||||
3846 | } else if (getLangOpts().OpenCL && | ||||
3847 | !getOpenCLOptions().isEnabled("cl_khr_fp64")) { | ||||
3848 | // Impose single-precision float type when cl_khr_fp64 is not enabled. | ||||
3849 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); | ||||
3850 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); | ||||
3851 | } | ||||
3852 | } | ||||
3853 | } else if (!Literal.isIntegerLiteral()) { | ||||
3854 | return ExprError(); | ||||
3855 | } else { | ||||
3856 | QualType Ty; | ||||
3857 | |||||
3858 | // 'long long' is a C99 or C++11 feature. | ||||
3859 | if (!getLangOpts().C99 && Literal.isLongLong) { | ||||
3860 | if (getLangOpts().CPlusPlus) | ||||
3861 | Diag(Tok.getLocation(), | ||||
3862 | getLangOpts().CPlusPlus11 ? | ||||
3863 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||
3864 | else | ||||
3865 | Diag(Tok.getLocation(), diag::ext_c99_longlong); | ||||
3866 | } | ||||
3867 | |||||
3868 | // Get the value in the widest-possible width. | ||||
3869 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); | ||||
3870 | llvm::APInt ResultVal(MaxWidth, 0); | ||||
3871 | |||||
3872 | if (Literal.GetIntegerValue(ResultVal)) { | ||||
3873 | // If this value didn't fit into uintmax_t, error and force to ull. | ||||
3874 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) | ||||
3875 | << /* Unsigned */ 1; | ||||
3876 | Ty = Context.UnsignedLongLongTy; | ||||
3877 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3878, __PRETTY_FUNCTION__)) | ||||
3878 | "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?") ? static_cast<void> (0) : __assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3878, __PRETTY_FUNCTION__)); | ||||
3879 | } else { | ||||
3880 | // If this value fits into a ULL, try to figure out what else it fits into | ||||
3881 | // according to the rules of C99 6.4.4.1p5. | ||||
3882 | |||||
3883 | // Octal, Hexadecimal, and integers with a U suffix are allowed to | ||||
3884 | // be an unsigned int. | ||||
3885 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; | ||||
3886 | |||||
3887 | // Check from smallest to largest, picking the smallest type we can. | ||||
3888 | unsigned Width = 0; | ||||
3889 | |||||
3890 | // Microsoft specific integer suffixes are explicitly sized. | ||||
3891 | if (Literal.MicrosoftInteger) { | ||||
3892 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { | ||||
3893 | Width = 8; | ||||
3894 | Ty = Context.CharTy; | ||||
3895 | } else { | ||||
3896 | Width = Literal.MicrosoftInteger; | ||||
3897 | Ty = Context.getIntTypeForBitwidth(Width, | ||||
3898 | /*Signed=*/!Literal.isUnsigned); | ||||
3899 | } | ||||
3900 | } | ||||
3901 | |||||
3902 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { | ||||
3903 | // Are int/unsigned possibilities? | ||||
3904 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); | ||||
3905 | |||||
3906 | // Does it fit in a unsigned int? | ||||
3907 | if (ResultVal.isIntN(IntSize)) { | ||||
3908 | // Does it fit in a signed int? | ||||
3909 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) | ||||
3910 | Ty = Context.IntTy; | ||||
3911 | else if (AllowUnsigned) | ||||
3912 | Ty = Context.UnsignedIntTy; | ||||
3913 | Width = IntSize; | ||||
3914 | } | ||||
3915 | } | ||||
3916 | |||||
3917 | // Are long/unsigned long possibilities? | ||||
3918 | if (Ty.isNull() && !Literal.isLongLong) { | ||||
3919 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); | ||||
3920 | |||||
3921 | // Does it fit in a unsigned long? | ||||
3922 | if (ResultVal.isIntN(LongSize)) { | ||||
3923 | // Does it fit in a signed long? | ||||
3924 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) | ||||
3925 | Ty = Context.LongTy; | ||||
3926 | else if (AllowUnsigned) | ||||
3927 | Ty = Context.UnsignedLongTy; | ||||
3928 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 | ||||
3929 | // is compatible. | ||||
3930 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { | ||||
3931 | const unsigned LongLongSize = | ||||
3932 | Context.getTargetInfo().getLongLongWidth(); | ||||
3933 | Diag(Tok.getLocation(), | ||||
3934 | getLangOpts().CPlusPlus | ||||
3935 | ? Literal.isLong | ||||
3936 | ? diag::warn_old_implicitly_unsigned_long_cxx | ||||
3937 | : /*C++98 UB*/ diag:: | ||||
3938 | ext_old_implicitly_unsigned_long_cxx | ||||
3939 | : diag::warn_old_implicitly_unsigned_long) | ||||
3940 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 | ||||
3941 | : /*will be ill-formed*/ 1); | ||||
3942 | Ty = Context.UnsignedLongTy; | ||||
3943 | } | ||||
3944 | Width = LongSize; | ||||
3945 | } | ||||
3946 | } | ||||
3947 | |||||
3948 | // Check long long if needed. | ||||
3949 | if (Ty.isNull()) { | ||||
3950 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); | ||||
3951 | |||||
3952 | // Does it fit in a unsigned long long? | ||||
3953 | if (ResultVal.isIntN(LongLongSize)) { | ||||
3954 | // Does it fit in a signed long long? | ||||
3955 | // To be compatible with MSVC, hex integer literals ending with the | ||||
3956 | // LL or i64 suffix are always signed in Microsoft mode. | ||||
3957 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || | ||||
3958 | (getLangOpts().MSVCCompat && Literal.isLongLong))) | ||||
3959 | Ty = Context.LongLongTy; | ||||
3960 | else if (AllowUnsigned) | ||||
3961 | Ty = Context.UnsignedLongLongTy; | ||||
3962 | Width = LongLongSize; | ||||
3963 | } | ||||
3964 | } | ||||
3965 | |||||
3966 | // If we still couldn't decide a type, we probably have something that | ||||
3967 | // does not fit in a signed long long, but has no U suffix. | ||||
3968 | if (Ty.isNull()) { | ||||
3969 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); | ||||
3970 | Ty = Context.UnsignedLongLongTy; | ||||
3971 | Width = Context.getTargetInfo().getLongLongWidth(); | ||||
3972 | } | ||||
3973 | |||||
3974 | if (ResultVal.getBitWidth() != Width) | ||||
3975 | ResultVal = ResultVal.trunc(Width); | ||||
3976 | } | ||||
3977 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); | ||||
3978 | } | ||||
3979 | |||||
3980 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. | ||||
3981 | if (Literal.isImaginary) { | ||||
3982 | Res = new (Context) ImaginaryLiteral(Res, | ||||
3983 | Context.getComplexType(Res->getType())); | ||||
3984 | |||||
3985 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); | ||||
3986 | } | ||||
3987 | return Res; | ||||
3988 | } | ||||
3989 | |||||
3990 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { | ||||
3991 | assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast <void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 3991, __PRETTY_FUNCTION__)); | ||||
3992 | return new (Context) ParenExpr(L, R, E); | ||||
3993 | } | ||||
3994 | |||||
3995 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, | ||||
3996 | SourceLocation Loc, | ||||
3997 | SourceRange ArgRange) { | ||||
3998 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in | ||||
3999 | // scalar or vector data type argument..." | ||||
4000 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic | ||||
4001 | // type (C99 6.2.5p18) or void. | ||||
4002 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { | ||||
4003 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) | ||||
4004 | << T << ArgRange; | ||||
4005 | return true; | ||||
4006 | } | ||||
4007 | |||||
4008 | assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4009, __PRETTY_FUNCTION__)) | ||||
4009 | "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) && "Scalar types should always be complete") ? static_cast<void > (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4009, __PRETTY_FUNCTION__)); | ||||
4010 | return false; | ||||
4011 | } | ||||
4012 | |||||
4013 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, | ||||
4014 | SourceLocation Loc, | ||||
4015 | SourceRange ArgRange, | ||||
4016 | UnaryExprOrTypeTrait TraitKind) { | ||||
4017 | // Invalid types must be hard errors for SFINAE in C++. | ||||
4018 | if (S.LangOpts.CPlusPlus) | ||||
4019 | return true; | ||||
4020 | |||||
4021 | // C99 6.5.3.4p1: | ||||
4022 | if (T->isFunctionType() && | ||||
4023 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || | ||||
4024 | TraitKind == UETT_PreferredAlignOf)) { | ||||
4025 | // sizeof(function)/alignof(function) is allowed as an extension. | ||||
4026 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) | ||||
4027 | << getTraitSpelling(TraitKind) << ArgRange; | ||||
4028 | return false; | ||||
4029 | } | ||||
4030 | |||||
4031 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where | ||||
4032 | // this is an error (OpenCL v1.1 s6.3.k) | ||||
4033 | if (T->isVoidType()) { | ||||
4034 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type | ||||
4035 | : diag::ext_sizeof_alignof_void_type; | ||||
4036 | S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; | ||||
4037 | return false; | ||||
4038 | } | ||||
4039 | |||||
4040 | return true; | ||||
4041 | } | ||||
4042 | |||||
4043 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, | ||||
4044 | SourceLocation Loc, | ||||
4045 | SourceRange ArgRange, | ||||
4046 | UnaryExprOrTypeTrait TraitKind) { | ||||
4047 | // Reject sizeof(interface) and sizeof(interface<proto>) if the | ||||
4048 | // runtime doesn't allow it. | ||||
4049 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { | ||||
4050 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) | ||||
4051 | << T << (TraitKind == UETT_SizeOf) | ||||
4052 | << ArgRange; | ||||
4053 | return true; | ||||
4054 | } | ||||
4055 | |||||
4056 | return false; | ||||
4057 | } | ||||
4058 | |||||
4059 | /// Check whether E is a pointer from a decayed array type (the decayed | ||||
4060 | /// pointer type is equal to T) and emit a warning if it is. | ||||
4061 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, | ||||
4062 | Expr *E) { | ||||
4063 | // Don't warn if the operation changed the type. | ||||
4064 | if (T != E->getType()) | ||||
4065 | return; | ||||
4066 | |||||
4067 | // Now look for array decays. | ||||
4068 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); | ||||
4069 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) | ||||
4070 | return; | ||||
4071 | |||||
4072 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() | ||||
4073 | << ICE->getType() | ||||
4074 | << ICE->getSubExpr()->getType(); | ||||
4075 | } | ||||
4076 | |||||
4077 | /// Check the constraints on expression operands to unary type expression | ||||
4078 | /// and type traits. | ||||
4079 | /// | ||||
4080 | /// Completes any types necessary and validates the constraints on the operand | ||||
4081 | /// expression. The logic mostly mirrors the type-based overload, but may modify | ||||
4082 | /// the expression as it completes the type for that expression through template | ||||
4083 | /// instantiation, etc. | ||||
4084 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, | ||||
4085 | UnaryExprOrTypeTrait ExprKind) { | ||||
4086 | QualType ExprTy = E->getType(); | ||||
4087 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4087, __PRETTY_FUNCTION__)); | ||||
4088 | |||||
4089 | bool IsUnevaluatedOperand = | ||||
4090 | (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || | ||||
4091 | ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); | ||||
4092 | if (IsUnevaluatedOperand) { | ||||
4093 | ExprResult Result = CheckUnevaluatedOperand(E); | ||||
4094 | if (Result.isInvalid()) | ||||
4095 | return true; | ||||
4096 | E = Result.get(); | ||||
4097 | } | ||||
4098 | |||||
4099 | // The operand for sizeof and alignof is in an unevaluated expression context, | ||||
4100 | // so side effects could result in unintended consequences. | ||||
4101 | // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes | ||||
4102 | // used to build SFINAE gadgets. | ||||
4103 | // FIXME: Should we consider instantiation-dependent operands to 'alignof'? | ||||
4104 | if (IsUnevaluatedOperand && !inTemplateInstantiation() && | ||||
4105 | !E->isInstantiationDependent() && | ||||
4106 | E->HasSideEffects(Context, false)) | ||||
4107 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
4108 | |||||
4109 | if (ExprKind == UETT_VecStep) | ||||
4110 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4111 | E->getSourceRange()); | ||||
4112 | |||||
4113 | // Explicitly list some types as extensions. | ||||
4114 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), | ||||
4115 | E->getSourceRange(), ExprKind)) | ||||
4116 | return false; | ||||
4117 | |||||
4118 | // 'alignof' applied to an expression only requires the base element type of | ||||
4119 | // the expression to be complete. 'sizeof' requires the expression's type to | ||||
4120 | // be complete (and will attempt to complete it if it's an array of unknown | ||||
4121 | // bound). | ||||
4122 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4123 | if (RequireCompleteSizedType( | ||||
4124 | E->getExprLoc(), Context.getBaseElementType(E->getType()), | ||||
4125 | diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4126 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4127 | return true; | ||||
4128 | } else { | ||||
4129 | if (RequireCompleteSizedExprType( | ||||
4130 | E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4131 | getTraitSpelling(ExprKind), E->getSourceRange())) | ||||
4132 | return true; | ||||
4133 | } | ||||
4134 | |||||
4135 | // Completing the expression's type may have changed it. | ||||
4136 | ExprTy = E->getType(); | ||||
4137 | assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4137, __PRETTY_FUNCTION__)); | ||||
4138 | |||||
4139 | if (ExprTy->isFunctionType()) { | ||||
4140 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) | ||||
4141 | << getTraitSpelling(ExprKind) << E->getSourceRange(); | ||||
4142 | return true; | ||||
4143 | } | ||||
4144 | |||||
4145 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), | ||||
4146 | E->getSourceRange(), ExprKind)) | ||||
4147 | return true; | ||||
4148 | |||||
4149 | if (ExprKind == UETT_SizeOf) { | ||||
4150 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
4151 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { | ||||
4152 | QualType OType = PVD->getOriginalType(); | ||||
4153 | QualType Type = PVD->getType(); | ||||
4154 | if (Type->isPointerType() && OType->isArrayType()) { | ||||
4155 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) | ||||
4156 | << Type << OType; | ||||
4157 | Diag(PVD->getLocation(), diag::note_declared_at); | ||||
4158 | } | ||||
4159 | } | ||||
4160 | } | ||||
4161 | |||||
4162 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array | ||||
4163 | // decays into a pointer and returns an unintended result. This is most | ||||
4164 | // likely a typo for "sizeof(array) op x". | ||||
4165 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { | ||||
4166 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4167 | BO->getLHS()); | ||||
4168 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), | ||||
4169 | BO->getRHS()); | ||||
4170 | } | ||||
4171 | } | ||||
4172 | |||||
4173 | return false; | ||||
4174 | } | ||||
4175 | |||||
4176 | /// Check the constraints on operands to unary expression and type | ||||
4177 | /// traits. | ||||
4178 | /// | ||||
4179 | /// This will complete any types necessary, and validate the various constraints | ||||
4180 | /// on those operands. | ||||
4181 | /// | ||||
4182 | /// The UsualUnaryConversions() function is *not* called by this routine. | ||||
4183 | /// C99 6.3.2.1p[2-4] all state: | ||||
4184 | /// Except when it is the operand of the sizeof operator ... | ||||
4185 | /// | ||||
4186 | /// C++ [expr.sizeof]p4 | ||||
4187 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer | ||||
4188 | /// standard conversions are not applied to the operand of sizeof. | ||||
4189 | /// | ||||
4190 | /// This policy is followed for all of the unary trait expressions. | ||||
4191 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, | ||||
4192 | SourceLocation OpLoc, | ||||
4193 | SourceRange ExprRange, | ||||
4194 | UnaryExprOrTypeTrait ExprKind) { | ||||
4195 | if (ExprType->isDependentType()) | ||||
4196 | return false; | ||||
4197 | |||||
4198 | // C++ [expr.sizeof]p2: | ||||
4199 | // When applied to a reference or a reference type, the result | ||||
4200 | // is the size of the referenced type. | ||||
4201 | // C++11 [expr.alignof]p3: | ||||
4202 | // When alignof is applied to a reference type, the result | ||||
4203 | // shall be the alignment of the referenced type. | ||||
4204 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) | ||||
4205 | ExprType = Ref->getPointeeType(); | ||||
4206 | |||||
4207 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: | ||||
4208 | // When alignof or _Alignof is applied to an array type, the result | ||||
4209 | // is the alignment of the element type. | ||||
4210 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || | ||||
4211 | ExprKind == UETT_OpenMPRequiredSimdAlign) | ||||
4212 | ExprType = Context.getBaseElementType(ExprType); | ||||
4213 | |||||
4214 | if (ExprKind == UETT_VecStep) | ||||
4215 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); | ||||
4216 | |||||
4217 | // Explicitly list some types as extensions. | ||||
4218 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, | ||||
4219 | ExprKind)) | ||||
4220 | return false; | ||||
4221 | |||||
4222 | if (RequireCompleteSizedType( | ||||
4223 | OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, | ||||
4224 | getTraitSpelling(ExprKind), ExprRange)) | ||||
4225 | return true; | ||||
4226 | |||||
4227 | if (ExprType->isFunctionType()) { | ||||
4228 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) | ||||
4229 | << getTraitSpelling(ExprKind) << ExprRange; | ||||
4230 | return true; | ||||
4231 | } | ||||
4232 | |||||
4233 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, | ||||
4234 | ExprKind)) | ||||
4235 | return true; | ||||
4236 | |||||
4237 | return false; | ||||
4238 | } | ||||
4239 | |||||
4240 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { | ||||
4241 | // Cannot know anything else if the expression is dependent. | ||||
4242 | if (E->isTypeDependent()) | ||||
4243 | return false; | ||||
4244 | |||||
4245 | if (E->getObjectKind() == OK_BitField) { | ||||
4246 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | ||||
4247 | << 1 << E->getSourceRange(); | ||||
4248 | return true; | ||||
4249 | } | ||||
4250 | |||||
4251 | ValueDecl *D = nullptr; | ||||
4252 | Expr *Inner = E->IgnoreParens(); | ||||
4253 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { | ||||
4254 | D = DRE->getDecl(); | ||||
4255 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { | ||||
4256 | D = ME->getMemberDecl(); | ||||
4257 | } | ||||
4258 | |||||
4259 | // If it's a field, require the containing struct to have a | ||||
4260 | // complete definition so that we can compute the layout. | ||||
4261 | // | ||||
4262 | // This can happen in C++11 onwards, either by naming the member | ||||
4263 | // in a way that is not transformed into a member access expression | ||||
4264 | // (in an unevaluated operand, for instance), or by naming the member | ||||
4265 | // in a trailing-return-type. | ||||
4266 | // | ||||
4267 | // For the record, since __alignof__ on expressions is a GCC | ||||
4268 | // extension, GCC seems to permit this but always gives the | ||||
4269 | // nonsensical answer 0. | ||||
4270 | // | ||||
4271 | // We don't really need the layout here --- we could instead just | ||||
4272 | // directly check for all the appropriate alignment-lowing | ||||
4273 | // attributes --- but that would require duplicating a lot of | ||||
4274 | // logic that just isn't worth duplicating for such a marginal | ||||
4275 | // use-case. | ||||
4276 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { | ||||
4277 | // Fast path this check, since we at least know the record has a | ||||
4278 | // definition if we can find a member of it. | ||||
4279 | if (!FD->getParent()->isCompleteDefinition()) { | ||||
4280 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) | ||||
4281 | << E->getSourceRange(); | ||||
4282 | return true; | ||||
4283 | } | ||||
4284 | |||||
4285 | // Otherwise, if it's a field, and the field doesn't have | ||||
4286 | // reference type, then it must have a complete type (or be a | ||||
4287 | // flexible array member, which we explicitly want to | ||||
4288 | // white-list anyway), which makes the following checks trivial. | ||||
4289 | if (!FD->getType()->isReferenceType()) | ||||
4290 | return false; | ||||
4291 | } | ||||
4292 | |||||
4293 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); | ||||
4294 | } | ||||
4295 | |||||
4296 | bool Sema::CheckVecStepExpr(Expr *E) { | ||||
4297 | E = E->IgnoreParens(); | ||||
4298 | |||||
4299 | // Cannot know anything else if the expression is dependent. | ||||
4300 | if (E->isTypeDependent()) | ||||
4301 | return false; | ||||
4302 | |||||
4303 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); | ||||
4304 | } | ||||
4305 | |||||
4306 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, | ||||
4307 | CapturingScopeInfo *CSI) { | ||||
4308 | assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> ( 0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4308, __PRETTY_FUNCTION__)); | ||||
4309 | assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail ("CSI != nullptr", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4309, __PRETTY_FUNCTION__)); | ||||
4310 | |||||
4311 | // We're going to walk down into the type and look for VLA expressions. | ||||
4312 | do { | ||||
4313 | const Type *Ty = T.getTypePtr(); | ||||
4314 | switch (Ty->getTypeClass()) { | ||||
4315 | #define TYPE(Class, Base) | ||||
4316 | #define ABSTRACT_TYPE(Class, Base) | ||||
4317 | #define NON_CANONICAL_TYPE(Class, Base) | ||||
4318 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: | ||||
4319 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) | ||||
4320 | #include "clang/AST/TypeNodes.inc" | ||||
4321 | T = QualType(); | ||||
4322 | break; | ||||
4323 | // These types are never variably-modified. | ||||
4324 | case Type::Builtin: | ||||
4325 | case Type::Complex: | ||||
4326 | case Type::Vector: | ||||
4327 | case Type::ExtVector: | ||||
4328 | case Type::ConstantMatrix: | ||||
4329 | case Type::Record: | ||||
4330 | case Type::Enum: | ||||
4331 | case Type::Elaborated: | ||||
4332 | case Type::TemplateSpecialization: | ||||
4333 | case Type::ObjCObject: | ||||
4334 | case Type::ObjCInterface: | ||||
4335 | case Type::ObjCObjectPointer: | ||||
4336 | case Type::ObjCTypeParam: | ||||
4337 | case Type::Pipe: | ||||
4338 | case Type::ExtInt: | ||||
4339 | llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4339); | ||||
4340 | case Type::Adjusted: | ||||
4341 | T = cast<AdjustedType>(Ty)->getOriginalType(); | ||||
4342 | break; | ||||
4343 | case Type::Decayed: | ||||
4344 | T = cast<DecayedType>(Ty)->getPointeeType(); | ||||
4345 | break; | ||||
4346 | case Type::Pointer: | ||||
4347 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
4348 | break; | ||||
4349 | case Type::BlockPointer: | ||||
4350 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
4351 | break; | ||||
4352 | case Type::LValueReference: | ||||
4353 | case Type::RValueReference: | ||||
4354 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
4355 | break; | ||||
4356 | case Type::MemberPointer: | ||||
4357 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
4358 | break; | ||||
4359 | case Type::ConstantArray: | ||||
4360 | case Type::IncompleteArray: | ||||
4361 | // Losing element qualification here is fine. | ||||
4362 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
4363 | break; | ||||
4364 | case Type::VariableArray: { | ||||
4365 | // Losing element qualification here is fine. | ||||
4366 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); | ||||
4367 | |||||
4368 | // Unknown size indication requires no size computation. | ||||
4369 | // Otherwise, evaluate and record it. | ||||
4370 | auto Size = VAT->getSizeExpr(); | ||||
4371 | if (Size && !CSI->isVLATypeCaptured(VAT) && | ||||
4372 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) | ||||
4373 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); | ||||
4374 | |||||
4375 | T = VAT->getElementType(); | ||||
4376 | break; | ||||
4377 | } | ||||
4378 | case Type::FunctionProto: | ||||
4379 | case Type::FunctionNoProto: | ||||
4380 | T = cast<FunctionType>(Ty)->getReturnType(); | ||||
4381 | break; | ||||
4382 | case Type::Paren: | ||||
4383 | case Type::TypeOf: | ||||
4384 | case Type::UnaryTransform: | ||||
4385 | case Type::Attributed: | ||||
4386 | case Type::SubstTemplateTypeParm: | ||||
4387 | case Type::MacroQualified: | ||||
4388 | // Keep walking after single level desugaring. | ||||
4389 | T = T.getSingleStepDesugaredType(Context); | ||||
4390 | break; | ||||
4391 | case Type::Typedef: | ||||
4392 | T = cast<TypedefType>(Ty)->desugar(); | ||||
4393 | break; | ||||
4394 | case Type::Decltype: | ||||
4395 | T = cast<DecltypeType>(Ty)->desugar(); | ||||
4396 | break; | ||||
4397 | case Type::Auto: | ||||
4398 | case Type::DeducedTemplateSpecialization: | ||||
4399 | T = cast<DeducedType>(Ty)->getDeducedType(); | ||||
4400 | break; | ||||
4401 | case Type::TypeOfExpr: | ||||
4402 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); | ||||
4403 | break; | ||||
4404 | case Type::Atomic: | ||||
4405 | T = cast<AtomicType>(Ty)->getValueType(); | ||||
4406 | break; | ||||
4407 | } | ||||
4408 | } while (!T.isNull() && T->isVariablyModifiedType()); | ||||
4409 | } | ||||
4410 | |||||
4411 | /// Build a sizeof or alignof expression given a type operand. | ||||
4412 | ExprResult | ||||
4413 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | ||||
4414 | SourceLocation OpLoc, | ||||
4415 | UnaryExprOrTypeTrait ExprKind, | ||||
4416 | SourceRange R) { | ||||
4417 | if (!TInfo) | ||||
4418 | return ExprError(); | ||||
4419 | |||||
4420 | QualType T = TInfo->getType(); | ||||
4421 | |||||
4422 | if (!T->isDependentType() && | ||||
4423 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) | ||||
4424 | return ExprError(); | ||||
4425 | |||||
4426 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { | ||||
4427 | if (auto *TT = T->getAs<TypedefType>()) { | ||||
4428 | for (auto I = FunctionScopes.rbegin(), | ||||
4429 | E = std::prev(FunctionScopes.rend()); | ||||
4430 | I != E; ++I) { | ||||
4431 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
4432 | if (CSI == nullptr) | ||||
4433 | break; | ||||
4434 | DeclContext *DC = nullptr; | ||||
4435 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
4436 | DC = LSI->CallOperator; | ||||
4437 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
4438 | DC = CRSI->TheCapturedDecl; | ||||
4439 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
4440 | DC = BSI->TheDecl; | ||||
4441 | if (DC) { | ||||
4442 | if (DC->containsDecl(TT->getDecl())) | ||||
4443 | break; | ||||
4444 | captureVariablyModifiedType(Context, T, CSI); | ||||
4445 | } | ||||
4446 | } | ||||
4447 | } | ||||
4448 | } | ||||
4449 | |||||
4450 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4451 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4452 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); | ||||
4453 | } | ||||
4454 | |||||
4455 | /// Build a sizeof or alignof expression given an expression | ||||
4456 | /// operand. | ||||
4457 | ExprResult | ||||
4458 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | ||||
4459 | UnaryExprOrTypeTrait ExprKind) { | ||||
4460 | ExprResult PE = CheckPlaceholderExpr(E); | ||||
4461 | if (PE.isInvalid()) | ||||
4462 | return ExprError(); | ||||
4463 | |||||
4464 | E = PE.get(); | ||||
4465 | |||||
4466 | // Verify that the operand is valid. | ||||
4467 | bool isInvalid = false; | ||||
4468 | if (E->isTypeDependent()) { | ||||
4469 | // Delay type-checking for type-dependent expressions. | ||||
4470 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { | ||||
4471 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); | ||||
4472 | } else if (ExprKind == UETT_VecStep) { | ||||
4473 | isInvalid = CheckVecStepExpr(E); | ||||
4474 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { | ||||
4475 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); | ||||
4476 | isInvalid = true; | ||||
4477 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. | ||||
4478 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; | ||||
4479 | isInvalid = true; | ||||
4480 | } else { | ||||
4481 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); | ||||
4482 | } | ||||
4483 | |||||
4484 | if (isInvalid) | ||||
4485 | return ExprError(); | ||||
4486 | |||||
4487 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { | ||||
4488 | PE = TransformToPotentiallyEvaluated(E); | ||||
4489 | if (PE.isInvalid()) return ExprError(); | ||||
4490 | E = PE.get(); | ||||
4491 | } | ||||
4492 | |||||
4493 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. | ||||
4494 | return new (Context) UnaryExprOrTypeTraitExpr( | ||||
4495 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); | ||||
4496 | } | ||||
4497 | |||||
4498 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c | ||||
4499 | /// expr and the same for @c alignof and @c __alignof | ||||
4500 | /// Note that the ArgRange is invalid if isType is false. | ||||
4501 | ExprResult | ||||
4502 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | ||||
4503 | UnaryExprOrTypeTrait ExprKind, bool IsType, | ||||
4504 | void *TyOrEx, SourceRange ArgRange) { | ||||
4505 | // If error parsing type, ignore. | ||||
4506 | if (!TyOrEx) return ExprError(); | ||||
4507 | |||||
4508 | if (IsType) { | ||||
4509 | TypeSourceInfo *TInfo; | ||||
4510 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); | ||||
4511 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); | ||||
4512 | } | ||||
4513 | |||||
4514 | Expr *ArgEx = (Expr *)TyOrEx; | ||||
4515 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); | ||||
4516 | return Result; | ||||
4517 | } | ||||
4518 | |||||
4519 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, | ||||
4520 | bool IsReal) { | ||||
4521 | if (V.get()->isTypeDependent()) | ||||
4522 | return S.Context.DependentTy; | ||||
4523 | |||||
4524 | // _Real and _Imag are only l-values for normal l-values. | ||||
4525 | if (V.get()->getObjectKind() != OK_Ordinary) { | ||||
4526 | V = S.DefaultLvalueConversion(V.get()); | ||||
4527 | if (V.isInvalid()) | ||||
4528 | return QualType(); | ||||
4529 | } | ||||
4530 | |||||
4531 | // These operators return the element type of a complex type. | ||||
4532 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) | ||||
4533 | return CT->getElementType(); | ||||
4534 | |||||
4535 | // Otherwise they pass through real integer and floating point types here. | ||||
4536 | if (V.get()->getType()->isArithmeticType()) | ||||
4537 | return V.get()->getType(); | ||||
4538 | |||||
4539 | // Test for placeholders. | ||||
4540 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); | ||||
4541 | if (PR.isInvalid()) return QualType(); | ||||
4542 | if (PR.get() != V.get()) { | ||||
4543 | V = PR; | ||||
4544 | return CheckRealImagOperand(S, V, Loc, IsReal); | ||||
4545 | } | ||||
4546 | |||||
4547 | // Reject anything else. | ||||
4548 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() | ||||
4549 | << (IsReal ? "__real" : "__imag"); | ||||
4550 | return QualType(); | ||||
4551 | } | ||||
4552 | |||||
4553 | |||||
4554 | |||||
4555 | ExprResult | ||||
4556 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
4557 | tok::TokenKind Kind, Expr *Input) { | ||||
4558 | UnaryOperatorKind Opc; | ||||
4559 | switch (Kind) { | ||||
4560 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4560); | ||||
4561 | case tok::plusplus: Opc = UO_PostInc; break; | ||||
4562 | case tok::minusminus: Opc = UO_PostDec; break; | ||||
4563 | } | ||||
4564 | |||||
4565 | // Since this might is a postfix expression, get rid of ParenListExprs. | ||||
4566 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); | ||||
4567 | if (Result.isInvalid()) return ExprError(); | ||||
4568 | Input = Result.get(); | ||||
4569 | |||||
4570 | return BuildUnaryOp(S, OpLoc, Opc, Input); | ||||
4571 | } | ||||
4572 | |||||
4573 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. | ||||
4574 | /// | ||||
4575 | /// \return true on error | ||||
4576 | static bool checkArithmeticOnObjCPointer(Sema &S, | ||||
4577 | SourceLocation opLoc, | ||||
4578 | Expr *op) { | ||||
4579 | assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast <void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4579, __PRETTY_FUNCTION__)); | ||||
4580 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && | ||||
4581 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) | ||||
4582 | return false; | ||||
4583 | |||||
4584 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) | ||||
4585 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() | ||||
4586 | << op->getSourceRange(); | ||||
4587 | return true; | ||||
4588 | } | ||||
4589 | |||||
4590 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { | ||||
4591 | auto *BaseNoParens = Base->IgnoreParens(); | ||||
4592 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) | ||||
4593 | return MSProp->getPropertyDecl()->getType()->isArrayType(); | ||||
4594 | return isa<MSPropertySubscriptExpr>(BaseNoParens); | ||||
4595 | } | ||||
4596 | |||||
4597 | ExprResult | ||||
4598 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, | ||||
4599 | Expr *idx, SourceLocation rbLoc) { | ||||
4600 | if (base && !base->getType().isNull() && | ||||
4601 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) | ||||
4602 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), | ||||
4603 | SourceLocation(), /*Length*/ nullptr, | ||||
4604 | /*Stride=*/nullptr, rbLoc); | ||||
4605 | |||||
4606 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
4607 | if (isa<ParenListExpr>(base)) { | ||||
4608 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); | ||||
4609 | if (result.isInvalid()) return ExprError(); | ||||
4610 | base = result.get(); | ||||
4611 | } | ||||
4612 | |||||
4613 | // Check if base and idx form a MatrixSubscriptExpr. | ||||
4614 | // | ||||
4615 | // Helper to check for comma expressions, which are not allowed as indices for | ||||
4616 | // matrix subscript expressions. | ||||
4617 | auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { | ||||
4618 | if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { | ||||
4619 | Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) | ||||
4620 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4621 | return true; | ||||
4622 | } | ||||
4623 | return false; | ||||
4624 | }; | ||||
4625 | // The matrix subscript operator ([][])is considered a single operator. | ||||
4626 | // Separating the index expressions by parenthesis is not allowed. | ||||
4627 | if (base->getType()->isSpecificPlaceholderType( | ||||
4628 | BuiltinType::IncompleteMatrixIdx) && | ||||
4629 | !isa<MatrixSubscriptExpr>(base)) { | ||||
4630 | Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) | ||||
4631 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4632 | return ExprError(); | ||||
4633 | } | ||||
4634 | // If the base is a MatrixSubscriptExpr, try to create a new | ||||
4635 | // MatrixSubscriptExpr. | ||||
4636 | auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); | ||||
4637 | if (matSubscriptE) { | ||||
4638 | if (CheckAndReportCommaError(idx)) | ||||
4639 | return ExprError(); | ||||
4640 | |||||
4641 | assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4642, __PRETTY_FUNCTION__)) | ||||
4642 | "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript" ) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4642, __PRETTY_FUNCTION__)); | ||||
4643 | return CreateBuiltinMatrixSubscriptExpr( | ||||
4644 | matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); | ||||
4645 | } | ||||
4646 | |||||
4647 | // Handle any non-overload placeholder types in the base and index | ||||
4648 | // expressions. We can't handle overloads here because the other | ||||
4649 | // operand might be an overloadable type, in which case the overload | ||||
4650 | // resolution for the operator overload should get the first crack | ||||
4651 | // at the overload. | ||||
4652 | bool IsMSPropertySubscript = false; | ||||
4653 | if (base->getType()->isNonOverloadPlaceholderType()) { | ||||
4654 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); | ||||
4655 | if (!IsMSPropertySubscript) { | ||||
4656 | ExprResult result = CheckPlaceholderExpr(base); | ||||
4657 | if (result.isInvalid()) | ||||
4658 | return ExprError(); | ||||
4659 | base = result.get(); | ||||
4660 | } | ||||
4661 | } | ||||
4662 | |||||
4663 | // If the base is a matrix type, try to create a new MatrixSubscriptExpr. | ||||
4664 | if (base->getType()->isMatrixType()) { | ||||
4665 | if (CheckAndReportCommaError(idx)) | ||||
4666 | return ExprError(); | ||||
4667 | |||||
4668 | return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); | ||||
4669 | } | ||||
4670 | |||||
4671 | // A comma-expression as the index is deprecated in C++2a onwards. | ||||
4672 | if (getLangOpts().CPlusPlus20 && | ||||
4673 | ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || | ||||
4674 | (isa<CXXOperatorCallExpr>(idx) && | ||||
4675 | cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { | ||||
4676 | Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) | ||||
4677 | << SourceRange(base->getBeginLoc(), rbLoc); | ||||
4678 | } | ||||
4679 | |||||
4680 | if (idx->getType()->isNonOverloadPlaceholderType()) { | ||||
4681 | ExprResult result = CheckPlaceholderExpr(idx); | ||||
4682 | if (result.isInvalid()) return ExprError(); | ||||
4683 | idx = result.get(); | ||||
4684 | } | ||||
4685 | |||||
4686 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4687 | if (getLangOpts().CPlusPlus && | ||||
4688 | (base->isTypeDependent() || idx->isTypeDependent())) { | ||||
4689 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, | ||||
4690 | VK_LValue, OK_Ordinary, rbLoc); | ||||
4691 | } | ||||
4692 | |||||
4693 | // MSDN, property (C++) | ||||
4694 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx | ||||
4695 | // This attribute can also be used in the declaration of an empty array in a | ||||
4696 | // class or structure definition. For example: | ||||
4697 | // __declspec(property(get=GetX, put=PutX)) int x[]; | ||||
4698 | // The above statement indicates that x[] can be used with one or more array | ||||
4699 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), | ||||
4700 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); | ||||
4701 | if (IsMSPropertySubscript) { | ||||
4702 | // Build MS property subscript expression if base is MS property reference | ||||
4703 | // or MS property subscript. | ||||
4704 | return new (Context) MSPropertySubscriptExpr( | ||||
4705 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); | ||||
4706 | } | ||||
4707 | |||||
4708 | // Use C++ overloaded-operator rules if either operand has record | ||||
4709 | // type. The spec says to do this if either type is *overloadable*, | ||||
4710 | // but enum types can't declare subscript operators or conversion | ||||
4711 | // operators, so there's nothing interesting for overload resolution | ||||
4712 | // to do if there aren't any record types involved. | ||||
4713 | // | ||||
4714 | // ObjC pointers have their own subscripting logic that is not tied | ||||
4715 | // to overload resolution and so should not take this path. | ||||
4716 | if (getLangOpts().CPlusPlus && | ||||
4717 | (base->getType()->isRecordType() || | ||||
4718 | (!base->getType()->isObjCObjectPointerType() && | ||||
4719 | idx->getType()->isRecordType()))) { | ||||
4720 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); | ||||
4721 | } | ||||
4722 | |||||
4723 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); | ||||
4724 | |||||
4725 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) | ||||
4726 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); | ||||
4727 | |||||
4728 | return Res; | ||||
4729 | } | ||||
4730 | |||||
4731 | ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { | ||||
4732 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); | ||||
4733 | InitializationKind Kind = | ||||
4734 | InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); | ||||
4735 | InitializationSequence InitSeq(*this, Entity, Kind, E); | ||||
4736 | return InitSeq.Perform(*this, Entity, Kind, E); | ||||
4737 | } | ||||
4738 | |||||
4739 | ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, | ||||
4740 | Expr *ColumnIdx, | ||||
4741 | SourceLocation RBLoc) { | ||||
4742 | ExprResult BaseR = CheckPlaceholderExpr(Base); | ||||
4743 | if (BaseR.isInvalid()) | ||||
4744 | return BaseR; | ||||
4745 | Base = BaseR.get(); | ||||
4746 | |||||
4747 | ExprResult RowR = CheckPlaceholderExpr(RowIdx); | ||||
4748 | if (RowR.isInvalid()) | ||||
4749 | return RowR; | ||||
4750 | RowIdx = RowR.get(); | ||||
4751 | |||||
4752 | if (!ColumnIdx) | ||||
4753 | return new (Context) MatrixSubscriptExpr( | ||||
4754 | Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); | ||||
4755 | |||||
4756 | // Build an unanalyzed expression if any of the operands is type-dependent. | ||||
4757 | if (Base->isTypeDependent() || RowIdx->isTypeDependent() || | ||||
4758 | ColumnIdx->isTypeDependent()) | ||||
4759 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4760 | Context.DependentTy, RBLoc); | ||||
4761 | |||||
4762 | ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); | ||||
4763 | if (ColumnR.isInvalid()) | ||||
4764 | return ColumnR; | ||||
4765 | ColumnIdx = ColumnR.get(); | ||||
4766 | |||||
4767 | // Check that IndexExpr is an integer expression. If it is a constant | ||||
4768 | // expression, check that it is less than Dim (= the number of elements in the | ||||
4769 | // corresponding dimension). | ||||
4770 | auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, | ||||
4771 | bool IsColumnIdx) -> Expr * { | ||||
4772 | if (!IndexExpr->getType()->isIntegerType() && | ||||
4773 | !IndexExpr->isTypeDependent()) { | ||||
4774 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) | ||||
4775 | << IsColumnIdx; | ||||
4776 | return nullptr; | ||||
4777 | } | ||||
4778 | |||||
4779 | if (Optional<llvm::APSInt> Idx = | ||||
4780 | IndexExpr->getIntegerConstantExpr(Context)) { | ||||
4781 | if ((*Idx < 0 || *Idx >= Dim)) { | ||||
4782 | Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) | ||||
4783 | << IsColumnIdx << Dim; | ||||
4784 | return nullptr; | ||||
4785 | } | ||||
4786 | } | ||||
4787 | |||||
4788 | ExprResult ConvExpr = | ||||
4789 | tryConvertExprToType(IndexExpr, Context.getSizeType()); | ||||
4790 | assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4791, __PRETTY_FUNCTION__)) | ||||
4791 | "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type" ) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 4791, __PRETTY_FUNCTION__)); | ||||
4792 | return ConvExpr.get(); | ||||
4793 | }; | ||||
4794 | |||||
4795 | auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); | ||||
4796 | RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); | ||||
4797 | ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); | ||||
4798 | if (!RowIdx || !ColumnIdx) | ||||
4799 | return ExprError(); | ||||
4800 | |||||
4801 | return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, | ||||
4802 | MTy->getElementType(), RBLoc); | ||||
4803 | } | ||||
4804 | |||||
4805 | void Sema::CheckAddressOfNoDeref(const Expr *E) { | ||||
4806 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4807 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); | ||||
4808 | |||||
4809 | // For expressions like `&(*s).b`, the base is recorded and what should be | ||||
4810 | // checked. | ||||
4811 | const MemberExpr *Member = nullptr; | ||||
4812 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) | ||||
4813 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); | ||||
4814 | |||||
4815 | LastRecord.PossibleDerefs.erase(StrippedExpr); | ||||
4816 | } | ||||
4817 | |||||
4818 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { | ||||
4819 | if (isUnevaluatedContext()) | ||||
4820 | return; | ||||
4821 | |||||
4822 | QualType ResultTy = E->getType(); | ||||
4823 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); | ||||
4824 | |||||
4825 | // Bail if the element is an array since it is not memory access. | ||||
4826 | if (isa<ArrayType>(ResultTy)) | ||||
4827 | return; | ||||
4828 | |||||
4829 | if (ResultTy->hasAttr(attr::NoDeref)) { | ||||
4830 | LastRecord.PossibleDerefs.insert(E); | ||||
4831 | return; | ||||
4832 | } | ||||
4833 | |||||
4834 | // Check if the base type is a pointer to a member access of a struct | ||||
4835 | // marked with noderef. | ||||
4836 | const Expr *Base = E->getBase(); | ||||
4837 | QualType BaseTy = Base->getType(); | ||||
4838 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) | ||||
4839 | // Not a pointer access | ||||
4840 | return; | ||||
4841 | |||||
4842 | const MemberExpr *Member = nullptr; | ||||
4843 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && | ||||
4844 | Member->isArrow()) | ||||
4845 | Base = Member->getBase(); | ||||
4846 | |||||
4847 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { | ||||
4848 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) | ||||
4849 | LastRecord.PossibleDerefs.insert(E); | ||||
4850 | } | ||||
4851 | } | ||||
4852 | |||||
4853 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | ||||
4854 | Expr *LowerBound, | ||||
4855 | SourceLocation ColonLocFirst, | ||||
4856 | SourceLocation ColonLocSecond, | ||||
4857 | Expr *Length, Expr *Stride, | ||||
4858 | SourceLocation RBLoc) { | ||||
4859 | if (Base->getType()->isPlaceholderType() && | ||||
4860 | !Base->getType()->isSpecificPlaceholderType( | ||||
4861 | BuiltinType::OMPArraySection)) { | ||||
4862 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
4863 | if (Result.isInvalid()) | ||||
4864 | return ExprError(); | ||||
4865 | Base = Result.get(); | ||||
4866 | } | ||||
4867 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { | ||||
4868 | ExprResult Result = CheckPlaceholderExpr(LowerBound); | ||||
4869 | if (Result.isInvalid()) | ||||
4870 | return ExprError(); | ||||
4871 | Result = DefaultLvalueConversion(Result.get()); | ||||
4872 | if (Result.isInvalid()) | ||||
4873 | return ExprError(); | ||||
4874 | LowerBound = Result.get(); | ||||
4875 | } | ||||
4876 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { | ||||
4877 | ExprResult Result = CheckPlaceholderExpr(Length); | ||||
4878 | if (Result.isInvalid()) | ||||
4879 | return ExprError(); | ||||
4880 | Result = DefaultLvalueConversion(Result.get()); | ||||
4881 | if (Result.isInvalid()) | ||||
4882 | return ExprError(); | ||||
4883 | Length = Result.get(); | ||||
4884 | } | ||||
4885 | if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { | ||||
4886 | ExprResult Result = CheckPlaceholderExpr(Stride); | ||||
4887 | if (Result.isInvalid()) | ||||
4888 | return ExprError(); | ||||
4889 | Result = DefaultLvalueConversion(Result.get()); | ||||
4890 | if (Result.isInvalid()) | ||||
4891 | return ExprError(); | ||||
4892 | Stride = Result.get(); | ||||
4893 | } | ||||
4894 | |||||
4895 | // Build an unanalyzed expression if either operand is type-dependent. | ||||
4896 | if (Base->isTypeDependent() || | ||||
4897 | (LowerBound && | ||||
4898 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || | ||||
4899 | (Length && (Length->isTypeDependent() || Length->isValueDependent())) || | ||||
4900 | (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { | ||||
4901 | return new (Context) OMPArraySectionExpr( | ||||
4902 | Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, | ||||
4903 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
4904 | } | ||||
4905 | |||||
4906 | // Perform default conversions. | ||||
4907 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); | ||||
4908 | QualType ResultTy; | ||||
4909 | if (OriginalTy->isAnyPointerType()) { | ||||
4910 | ResultTy = OriginalTy->getPointeeType(); | ||||
4911 | } else if (OriginalTy->isArrayType()) { | ||||
4912 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); | ||||
4913 | } else { | ||||
4914 | return ExprError( | ||||
4915 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) | ||||
4916 | << Base->getSourceRange()); | ||||
4917 | } | ||||
4918 | // C99 6.5.2.1p1 | ||||
4919 | if (LowerBound) { | ||||
4920 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), | ||||
4921 | LowerBound); | ||||
4922 | if (Res.isInvalid()) | ||||
4923 | return ExprError(Diag(LowerBound->getExprLoc(), | ||||
4924 | diag::err_omp_typecheck_section_not_integer) | ||||
4925 | << 0 << LowerBound->getSourceRange()); | ||||
4926 | LowerBound = Res.get(); | ||||
4927 | |||||
4928 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4929 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4930 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4931 | << 0 << LowerBound->getSourceRange(); | ||||
4932 | } | ||||
4933 | if (Length) { | ||||
4934 | auto Res = | ||||
4935 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); | ||||
4936 | if (Res.isInvalid()) | ||||
4937 | return ExprError(Diag(Length->getExprLoc(), | ||||
4938 | diag::err_omp_typecheck_section_not_integer) | ||||
4939 | << 1 << Length->getSourceRange()); | ||||
4940 | Length = Res.get(); | ||||
4941 | |||||
4942 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4943 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4944 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4945 | << 1 << Length->getSourceRange(); | ||||
4946 | } | ||||
4947 | if (Stride) { | ||||
4948 | ExprResult Res = | ||||
4949 | PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); | ||||
4950 | if (Res.isInvalid()) | ||||
4951 | return ExprError(Diag(Stride->getExprLoc(), | ||||
4952 | diag::err_omp_typecheck_section_not_integer) | ||||
4953 | << 1 << Stride->getSourceRange()); | ||||
4954 | Stride = Res.get(); | ||||
4955 | |||||
4956 | if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
4957 | Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
4958 | Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) | ||||
4959 | << 1 << Stride->getSourceRange(); | ||||
4960 | } | ||||
4961 | |||||
4962 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
4963 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
4964 | // type. Note that functions are not objects, and that (in C99 parlance) | ||||
4965 | // incomplete types are not object types. | ||||
4966 | if (ResultTy->isFunctionType()) { | ||||
4967 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) | ||||
4968 | << ResultTy << Base->getSourceRange(); | ||||
4969 | return ExprError(); | ||||
4970 | } | ||||
4971 | |||||
4972 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, | ||||
4973 | diag::err_omp_section_incomplete_type, Base)) | ||||
4974 | return ExprError(); | ||||
4975 | |||||
4976 | if (LowerBound && !OriginalTy->isAnyPointerType()) { | ||||
4977 | Expr::EvalResult Result; | ||||
4978 | if (LowerBound->EvaluateAsInt(Result, Context)) { | ||||
4979 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
4980 | // The array section must be a subset of the original array. | ||||
4981 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); | ||||
4982 | if (LowerBoundValue.isNegative()) { | ||||
4983 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) | ||||
4984 | << LowerBound->getSourceRange(); | ||||
4985 | return ExprError(); | ||||
4986 | } | ||||
4987 | } | ||||
4988 | } | ||||
4989 | |||||
4990 | if (Length) { | ||||
4991 | Expr::EvalResult Result; | ||||
4992 | if (Length->EvaluateAsInt(Result, Context)) { | ||||
4993 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
4994 | // The length must evaluate to non-negative integers. | ||||
4995 | llvm::APSInt LengthValue = Result.Val.getInt(); | ||||
4996 | if (LengthValue.isNegative()) { | ||||
4997 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) | ||||
4998 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||
4999 | << Length->getSourceRange(); | ||||
5000 | return ExprError(); | ||||
5001 | } | ||||
5002 | } | ||||
5003 | } else if (ColonLocFirst.isValid() && | ||||
5004 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && | ||||
5005 | !OriginalTy->isVariableArrayType()))) { | ||||
5006 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5007 | // When the size of the array dimension is not known, the length must be | ||||
5008 | // specified explicitly. | ||||
5009 | Diag(ColonLocFirst, diag::err_omp_section_length_undefined) | ||||
5010 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); | ||||
5011 | return ExprError(); | ||||
5012 | } | ||||
5013 | |||||
5014 | if (Stride) { | ||||
5015 | Expr::EvalResult Result; | ||||
5016 | if (Stride->EvaluateAsInt(Result, Context)) { | ||||
5017 | // OpenMP 5.0, [2.1.5 Array Sections] | ||||
5018 | // The stride must evaluate to a positive integer. | ||||
5019 | llvm::APSInt StrideValue = Result.Val.getInt(); | ||||
5020 | if (!StrideValue.isStrictlyPositive()) { | ||||
5021 | Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) | ||||
5022 | << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) | ||||
5023 | << Stride->getSourceRange(); | ||||
5024 | return ExprError(); | ||||
5025 | } | ||||
5026 | } | ||||
5027 | } | ||||
5028 | |||||
5029 | if (!Base->getType()->isSpecificPlaceholderType( | ||||
5030 | BuiltinType::OMPArraySection)) { | ||||
5031 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); | ||||
5032 | if (Result.isInvalid()) | ||||
5033 | return ExprError(); | ||||
5034 | Base = Result.get(); | ||||
5035 | } | ||||
5036 | return new (Context) OMPArraySectionExpr( | ||||
5037 | Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, | ||||
5038 | OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); | ||||
5039 | } | ||||
5040 | |||||
5041 | ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, | ||||
5042 | SourceLocation RParenLoc, | ||||
5043 | ArrayRef<Expr *> Dims, | ||||
5044 | ArrayRef<SourceRange> Brackets) { | ||||
5045 | if (Base->getType()->isPlaceholderType()) { | ||||
5046 | ExprResult Result = CheckPlaceholderExpr(Base); | ||||
5047 | if (Result.isInvalid()) | ||||
5048 | return ExprError(); | ||||
5049 | Result = DefaultLvalueConversion(Result.get()); | ||||
5050 | if (Result.isInvalid()) | ||||
5051 | return ExprError(); | ||||
5052 | Base = Result.get(); | ||||
5053 | } | ||||
5054 | QualType BaseTy = Base->getType(); | ||||
5055 | // Delay analysis of the types/expressions if instantiation/specialization is | ||||
5056 | // required. | ||||
5057 | if (!BaseTy->isPointerType() && Base->isTypeDependent()) | ||||
5058 | return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, | ||||
5059 | LParenLoc, RParenLoc, Dims, Brackets); | ||||
5060 | if (!BaseTy->isPointerType() || | ||||
5061 | (!Base->isTypeDependent() && | ||||
5062 | BaseTy->getPointeeType()->isIncompleteType())) | ||||
5063 | return ExprError(Diag(Base->getExprLoc(), | ||||
5064 | diag::err_omp_non_pointer_type_array_shaping_base) | ||||
5065 | << Base->getSourceRange()); | ||||
5066 | |||||
5067 | SmallVector<Expr *, 4> NewDims; | ||||
5068 | bool ErrorFound = false; | ||||
5069 | for (Expr *Dim : Dims) { | ||||
5070 | if (Dim->getType()->isPlaceholderType()) { | ||||
5071 | ExprResult Result = CheckPlaceholderExpr(Dim); | ||||
5072 | if (Result.isInvalid()) { | ||||
5073 | ErrorFound = true; | ||||
5074 | continue; | ||||
5075 | } | ||||
5076 | Result = DefaultLvalueConversion(Result.get()); | ||||
5077 | if (Result.isInvalid()) { | ||||
5078 | ErrorFound = true; | ||||
5079 | continue; | ||||
5080 | } | ||||
5081 | Dim = Result.get(); | ||||
5082 | } | ||||
5083 | if (!Dim->isTypeDependent()) { | ||||
5084 | ExprResult Result = | ||||
5085 | PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); | ||||
5086 | if (Result.isInvalid()) { | ||||
5087 | ErrorFound = true; | ||||
5088 | Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) | ||||
5089 | << Dim->getSourceRange(); | ||||
5090 | continue; | ||||
5091 | } | ||||
5092 | Dim = Result.get(); | ||||
5093 | Expr::EvalResult EvResult; | ||||
5094 | if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { | ||||
5095 | // OpenMP 5.0, [2.1.4 Array Shaping] | ||||
5096 | // Each si is an integral type expression that must evaluate to a | ||||
5097 | // positive integer. | ||||
5098 | llvm::APSInt Value = EvResult.Val.getInt(); | ||||
5099 | if (!Value.isStrictlyPositive()) { | ||||
5100 | Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) | ||||
5101 | << Value.toString(/*Radix=*/10, /*Signed=*/true) | ||||
5102 | << Dim->getSourceRange(); | ||||
5103 | ErrorFound = true; | ||||
5104 | continue; | ||||
5105 | } | ||||
5106 | } | ||||
5107 | } | ||||
5108 | NewDims.push_back(Dim); | ||||
5109 | } | ||||
5110 | if (ErrorFound) | ||||
5111 | return ExprError(); | ||||
5112 | return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, | ||||
5113 | LParenLoc, RParenLoc, NewDims, Brackets); | ||||
5114 | } | ||||
5115 | |||||
5116 | ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, | ||||
5117 | SourceLocation LLoc, SourceLocation RLoc, | ||||
5118 | ArrayRef<OMPIteratorData> Data) { | ||||
5119 | SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; | ||||
5120 | bool IsCorrect = true; | ||||
5121 | for (const OMPIteratorData &D : Data) { | ||||
5122 | TypeSourceInfo *TInfo = nullptr; | ||||
5123 | SourceLocation StartLoc; | ||||
5124 | QualType DeclTy; | ||||
5125 | if (!D.Type.getAsOpaquePtr()) { | ||||
5126 | // OpenMP 5.0, 2.1.6 Iterators | ||||
5127 | // In an iterator-specifier, if the iterator-type is not specified then | ||||
5128 | // the type of that iterator is of int type. | ||||
5129 | DeclTy = Context.IntTy; | ||||
5130 | StartLoc = D.DeclIdentLoc; | ||||
5131 | } else { | ||||
5132 | DeclTy = GetTypeFromParser(D.Type, &TInfo); | ||||
5133 | StartLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5134 | } | ||||
5135 | |||||
5136 | bool IsDeclTyDependent = DeclTy->isDependentType() || | ||||
5137 | DeclTy->containsUnexpandedParameterPack() || | ||||
5138 | DeclTy->isInstantiationDependentType(); | ||||
5139 | if (!IsDeclTyDependent) { | ||||
5140 | if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { | ||||
5141 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5142 | // The iterator-type must be an integral or pointer type. | ||||
5143 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5144 | << DeclTy; | ||||
5145 | IsCorrect = false; | ||||
5146 | continue; | ||||
5147 | } | ||||
5148 | if (DeclTy.isConstant(Context)) { | ||||
5149 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ | ||||
5150 | // The iterator-type must not be const qualified. | ||||
5151 | Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) | ||||
5152 | << DeclTy; | ||||
5153 | IsCorrect = false; | ||||
5154 | continue; | ||||
5155 | } | ||||
5156 | } | ||||
5157 | |||||
5158 | // Iterator declaration. | ||||
5159 | assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast <void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5159, __PRETTY_FUNCTION__)); | ||||
5160 | // Always try to create iterator declarator to avoid extra error messages | ||||
5161 | // about unknown declarations use. | ||||
5162 | auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, | ||||
5163 | D.DeclIdent, DeclTy, TInfo, SC_None); | ||||
5164 | VD->setImplicit(); | ||||
5165 | if (S) { | ||||
5166 | // Check for conflicting previous declaration. | ||||
5167 | DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); | ||||
5168 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5169 | ForVisibleRedeclaration); | ||||
5170 | Previous.suppressDiagnostics(); | ||||
5171 | LookupName(Previous, S); | ||||
5172 | |||||
5173 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, | ||||
5174 | /*AllowInlineNamespace=*/false); | ||||
5175 | if (!Previous.empty()) { | ||||
5176 | NamedDecl *Old = Previous.getRepresentativeDecl(); | ||||
5177 | Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); | ||||
5178 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
5179 | } else { | ||||
5180 | PushOnScopeChains(VD, S); | ||||
5181 | } | ||||
5182 | } else { | ||||
5183 | CurContext->addDecl(VD); | ||||
5184 | } | ||||
5185 | Expr *Begin = D.Range.Begin; | ||||
5186 | if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { | ||||
5187 | ExprResult BeginRes = | ||||
5188 | PerformImplicitConversion(Begin, DeclTy, AA_Converting); | ||||
5189 | Begin = BeginRes.get(); | ||||
5190 | } | ||||
5191 | Expr *End = D.Range.End; | ||||
5192 | if (!IsDeclTyDependent && End && !End->isTypeDependent()) { | ||||
5193 | ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); | ||||
5194 | End = EndRes.get(); | ||||
5195 | } | ||||
5196 | Expr *Step = D.Range.Step; | ||||
5197 | if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { | ||||
5198 | if (!Step->getType()->isIntegralType(Context)) { | ||||
5199 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) | ||||
5200 | << Step << Step->getSourceRange(); | ||||
5201 | IsCorrect = false; | ||||
5202 | continue; | ||||
5203 | } | ||||
5204 | Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); | ||||
5205 | // OpenMP 5.0, 2.1.6 Iterators, Restrictions | ||||
5206 | // If the step expression of a range-specification equals zero, the | ||||
5207 | // behavior is unspecified. | ||||
5208 | if (Result && Result->isNullValue()) { | ||||
5209 | Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) | ||||
5210 | << Step << Step->getSourceRange(); | ||||
5211 | IsCorrect = false; | ||||
5212 | continue; | ||||
5213 | } | ||||
5214 | } | ||||
5215 | if (!Begin || !End || !IsCorrect) { | ||||
5216 | IsCorrect = false; | ||||
5217 | continue; | ||||
5218 | } | ||||
5219 | OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); | ||||
5220 | IDElem.IteratorDecl = VD; | ||||
5221 | IDElem.AssignmentLoc = D.AssignLoc; | ||||
5222 | IDElem.Range.Begin = Begin; | ||||
5223 | IDElem.Range.End = End; | ||||
5224 | IDElem.Range.Step = Step; | ||||
5225 | IDElem.ColonLoc = D.ColonLoc; | ||||
5226 | IDElem.SecondColonLoc = D.SecColonLoc; | ||||
5227 | } | ||||
5228 | if (!IsCorrect) { | ||||
5229 | // Invalidate all created iterator declarations if error is found. | ||||
5230 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5231 | if (Decl *ID = D.IteratorDecl) | ||||
5232 | ID->setInvalidDecl(); | ||||
5233 | } | ||||
5234 | return ExprError(); | ||||
5235 | } | ||||
5236 | SmallVector<OMPIteratorHelperData, 4> Helpers; | ||||
5237 | if (!CurContext->isDependentContext()) { | ||||
5238 | // Build number of ityeration for each iteration range. | ||||
5239 | // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : | ||||
5240 | // ((Begini-Stepi-1-Endi) / -Stepi); | ||||
5241 | for (OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5242 | // (Endi - Begini) | ||||
5243 | ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, | ||||
5244 | D.Range.Begin); | ||||
5245 | if(!Res.isUsable()) { | ||||
5246 | IsCorrect = false; | ||||
5247 | continue; | ||||
5248 | } | ||||
5249 | ExprResult St, St1; | ||||
5250 | if (D.Range.Step) { | ||||
5251 | St = D.Range.Step; | ||||
5252 | // (Endi - Begini) + Stepi | ||||
5253 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); | ||||
5254 | if (!Res.isUsable()) { | ||||
5255 | IsCorrect = false; | ||||
5256 | continue; | ||||
5257 | } | ||||
5258 | // (Endi - Begini) + Stepi - 1 | ||||
5259 | Res = | ||||
5260 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), | ||||
5261 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5262 | if (!Res.isUsable()) { | ||||
5263 | IsCorrect = false; | ||||
5264 | continue; | ||||
5265 | } | ||||
5266 | // ((Endi - Begini) + Stepi - 1) / Stepi | ||||
5267 | Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); | ||||
5268 | if (!Res.isUsable()) { | ||||
5269 | IsCorrect = false; | ||||
5270 | continue; | ||||
5271 | } | ||||
5272 | St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); | ||||
5273 | // (Begini - Endi) | ||||
5274 | ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, | ||||
5275 | D.Range.Begin, D.Range.End); | ||||
5276 | if (!Res1.isUsable()) { | ||||
5277 | IsCorrect = false; | ||||
5278 | continue; | ||||
5279 | } | ||||
5280 | // (Begini - Endi) - Stepi | ||||
5281 | Res1 = | ||||
5282 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); | ||||
5283 | if (!Res1.isUsable()) { | ||||
5284 | IsCorrect = false; | ||||
5285 | continue; | ||||
5286 | } | ||||
5287 | // (Begini - Endi) - Stepi - 1 | ||||
5288 | Res1 = | ||||
5289 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), | ||||
5290 | ActOnIntegerConstant(D.AssignmentLoc, 1).get()); | ||||
5291 | if (!Res1.isUsable()) { | ||||
5292 | IsCorrect = false; | ||||
5293 | continue; | ||||
5294 | } | ||||
5295 | // ((Begini - Endi) - Stepi - 1) / (-Stepi) | ||||
5296 | Res1 = | ||||
5297 | CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); | ||||
5298 | if (!Res1.isUsable()) { | ||||
5299 | IsCorrect = false; | ||||
5300 | continue; | ||||
5301 | } | ||||
5302 | // Stepi > 0. | ||||
5303 | ExprResult CmpRes = | ||||
5304 | CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, | ||||
5305 | ActOnIntegerConstant(D.AssignmentLoc, 0).get()); | ||||
5306 | if (!CmpRes.isUsable()) { | ||||
5307 | IsCorrect = false; | ||||
5308 | continue; | ||||
5309 | } | ||||
5310 | Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), | ||||
5311 | Res.get(), Res1.get()); | ||||
5312 | if (!Res.isUsable()) { | ||||
5313 | IsCorrect = false; | ||||
5314 | continue; | ||||
5315 | } | ||||
5316 | } | ||||
5317 | Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); | ||||
5318 | if (!Res.isUsable()) { | ||||
5319 | IsCorrect = false; | ||||
5320 | continue; | ||||
5321 | } | ||||
5322 | |||||
5323 | // Build counter update. | ||||
5324 | // Build counter. | ||||
5325 | auto *CounterVD = | ||||
5326 | VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), | ||||
5327 | D.IteratorDecl->getBeginLoc(), nullptr, | ||||
5328 | Res.get()->getType(), nullptr, SC_None); | ||||
5329 | CounterVD->setImplicit(); | ||||
5330 | ExprResult RefRes = | ||||
5331 | BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, | ||||
5332 | D.IteratorDecl->getBeginLoc()); | ||||
5333 | // Build counter update. | ||||
5334 | // I = Begini + counter * Stepi; | ||||
5335 | ExprResult UpdateRes; | ||||
5336 | if (D.Range.Step) { | ||||
5337 | UpdateRes = CreateBuiltinBinOp( | ||||
5338 | D.AssignmentLoc, BO_Mul, | ||||
5339 | DefaultLvalueConversion(RefRes.get()).get(), St.get()); | ||||
5340 | } else { | ||||
5341 | UpdateRes = DefaultLvalueConversion(RefRes.get()); | ||||
5342 | } | ||||
5343 | if (!UpdateRes.isUsable()) { | ||||
5344 | IsCorrect = false; | ||||
5345 | continue; | ||||
5346 | } | ||||
5347 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, | ||||
5348 | UpdateRes.get()); | ||||
5349 | if (!UpdateRes.isUsable()) { | ||||
5350 | IsCorrect = false; | ||||
5351 | continue; | ||||
5352 | } | ||||
5353 | ExprResult VDRes = | ||||
5354 | BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), | ||||
5355 | cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, | ||||
5356 | D.IteratorDecl->getBeginLoc()); | ||||
5357 | UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), | ||||
5358 | UpdateRes.get()); | ||||
5359 | if (!UpdateRes.isUsable()) { | ||||
5360 | IsCorrect = false; | ||||
5361 | continue; | ||||
5362 | } | ||||
5363 | UpdateRes = | ||||
5364 | ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); | ||||
5365 | if (!UpdateRes.isUsable()) { | ||||
5366 | IsCorrect = false; | ||||
5367 | continue; | ||||
5368 | } | ||||
5369 | ExprResult CounterUpdateRes = | ||||
5370 | CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); | ||||
5371 | if (!CounterUpdateRes.isUsable()) { | ||||
5372 | IsCorrect = false; | ||||
5373 | continue; | ||||
5374 | } | ||||
5375 | CounterUpdateRes = | ||||
5376 | ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); | ||||
5377 | if (!CounterUpdateRes.isUsable()) { | ||||
5378 | IsCorrect = false; | ||||
5379 | continue; | ||||
5380 | } | ||||
5381 | OMPIteratorHelperData &HD = Helpers.emplace_back(); | ||||
5382 | HD.CounterVD = CounterVD; | ||||
5383 | HD.Upper = Res.get(); | ||||
5384 | HD.Update = UpdateRes.get(); | ||||
5385 | HD.CounterUpdate = CounterUpdateRes.get(); | ||||
5386 | } | ||||
5387 | } else { | ||||
5388 | Helpers.assign(ID.size(), {}); | ||||
5389 | } | ||||
5390 | if (!IsCorrect) { | ||||
5391 | // Invalidate all created iterator declarations if error is found. | ||||
5392 | for (const OMPIteratorExpr::IteratorDefinition &D : ID) { | ||||
5393 | if (Decl *ID = D.IteratorDecl) | ||||
5394 | ID->setInvalidDecl(); | ||||
5395 | } | ||||
5396 | return ExprError(); | ||||
5397 | } | ||||
5398 | return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, | ||||
5399 | LLoc, RLoc, ID, Helpers); | ||||
5400 | } | ||||
5401 | |||||
5402 | ExprResult | ||||
5403 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | ||||
5404 | Expr *Idx, SourceLocation RLoc) { | ||||
5405 | Expr *LHSExp = Base; | ||||
5406 | Expr *RHSExp = Idx; | ||||
5407 | |||||
5408 | ExprValueKind VK = VK_LValue; | ||||
5409 | ExprObjectKind OK = OK_Ordinary; | ||||
5410 | |||||
5411 | // Per C++ core issue 1213, the result is an xvalue if either operand is | ||||
5412 | // a non-lvalue array, and an lvalue otherwise. | ||||
5413 | if (getLangOpts().CPlusPlus11) { | ||||
5414 | for (auto *Op : {LHSExp, RHSExp}) { | ||||
5415 | Op = Op->IgnoreImplicit(); | ||||
5416 | if (Op->getType()->isArrayType() && !Op->isLValue()) | ||||
5417 | VK = VK_XValue; | ||||
5418 | } | ||||
5419 | } | ||||
5420 | |||||
5421 | // Perform default conversions. | ||||
5422 | if (!LHSExp->getType()->getAs<VectorType>()) { | ||||
5423 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); | ||||
5424 | if (Result.isInvalid()) | ||||
5425 | return ExprError(); | ||||
5426 | LHSExp = Result.get(); | ||||
5427 | } | ||||
5428 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); | ||||
5429 | if (Result.isInvalid()) | ||||
5430 | return ExprError(); | ||||
5431 | RHSExp = Result.get(); | ||||
5432 | |||||
5433 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); | ||||
5434 | |||||
5435 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent | ||||
5436 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be | ||||
5437 | // in the subscript position. As a result, we need to derive the array base | ||||
5438 | // and index from the expression types. | ||||
5439 | Expr *BaseExpr, *IndexExpr; | ||||
5440 | QualType ResultType; | ||||
5441 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { | ||||
5442 | BaseExpr = LHSExp; | ||||
5443 | IndexExpr = RHSExp; | ||||
5444 | ResultType = Context.DependentTy; | ||||
5445 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { | ||||
5446 | BaseExpr = LHSExp; | ||||
5447 | IndexExpr = RHSExp; | ||||
5448 | ResultType = PTy->getPointeeType(); | ||||
5449 | } else if (const ObjCObjectPointerType *PTy = | ||||
5450 | LHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5451 | BaseExpr = LHSExp; | ||||
5452 | IndexExpr = RHSExp; | ||||
5453 | |||||
5454 | // Use custom logic if this should be the pseudo-object subscript | ||||
5455 | // expression. | ||||
5456 | if (!LangOpts.isSubscriptPointerArithmetic()) | ||||
5457 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, | ||||
5458 | nullptr); | ||||
5459 | |||||
5460 | ResultType = PTy->getPointeeType(); | ||||
5461 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { | ||||
5462 | // Handle the uncommon case of "123[Ptr]". | ||||
5463 | BaseExpr = RHSExp; | ||||
5464 | IndexExpr = LHSExp; | ||||
5465 | ResultType = PTy->getPointeeType(); | ||||
5466 | } else if (const ObjCObjectPointerType *PTy = | ||||
5467 | RHSTy->getAs<ObjCObjectPointerType>()) { | ||||
5468 | // Handle the uncommon case of "123[Ptr]". | ||||
5469 | BaseExpr = RHSExp; | ||||
5470 | IndexExpr = LHSExp; | ||||
5471 | ResultType = PTy->getPointeeType(); | ||||
5472 | if (!LangOpts.isSubscriptPointerArithmetic()) { | ||||
5473 | Diag(LLoc, diag::err_subscript_nonfragile_interface) | ||||
5474 | << ResultType << BaseExpr->getSourceRange(); | ||||
5475 | return ExprError(); | ||||
5476 | } | ||||
5477 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { | ||||
5478 | BaseExpr = LHSExp; // vectors: V[123] | ||||
5479 | IndexExpr = RHSExp; | ||||
5480 | // We apply C++ DR1213 to vector subscripting too. | ||||
5481 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { | ||||
5482 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); | ||||
5483 | if (Materialized.isInvalid()) | ||||
5484 | return ExprError(); | ||||
5485 | LHSExp = Materialized.get(); | ||||
5486 | } | ||||
5487 | VK = LHSExp->getValueKind(); | ||||
5488 | if (VK != VK_RValue) | ||||
5489 | OK = OK_VectorComponent; | ||||
5490 | |||||
5491 | ResultType = VTy->getElementType(); | ||||
5492 | QualType BaseType = BaseExpr->getType(); | ||||
5493 | Qualifiers BaseQuals = BaseType.getQualifiers(); | ||||
5494 | Qualifiers MemberQuals = ResultType.getQualifiers(); | ||||
5495 | Qualifiers Combined = BaseQuals + MemberQuals; | ||||
5496 | if (Combined != MemberQuals) | ||||
5497 | ResultType = Context.getQualifiedType(ResultType, Combined); | ||||
5498 | } else if (LHSTy->isArrayType()) { | ||||
5499 | // If we see an array that wasn't promoted by | ||||
5500 | // DefaultFunctionArrayLvalueConversion, it must be an array that | ||||
5501 | // wasn't promoted because of the C90 rule that doesn't | ||||
5502 | // allow promoting non-lvalue arrays. Warn, then | ||||
5503 | // force the promotion here. | ||||
5504 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5505 | << LHSExp->getSourceRange(); | ||||
5506 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), | ||||
5507 | CK_ArrayToPointerDecay).get(); | ||||
5508 | LHSTy = LHSExp->getType(); | ||||
5509 | |||||
5510 | BaseExpr = LHSExp; | ||||
5511 | IndexExpr = RHSExp; | ||||
5512 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); | ||||
5513 | } else if (RHSTy->isArrayType()) { | ||||
5514 | // Same as previous, except for 123[f().a] case | ||||
5515 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) | ||||
5516 | << RHSExp->getSourceRange(); | ||||
5517 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), | ||||
5518 | CK_ArrayToPointerDecay).get(); | ||||
5519 | RHSTy = RHSExp->getType(); | ||||
5520 | |||||
5521 | BaseExpr = RHSExp; | ||||
5522 | IndexExpr = LHSExp; | ||||
5523 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); | ||||
5524 | } else { | ||||
5525 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) | ||||
5526 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); | ||||
5527 | } | ||||
5528 | // C99 6.5.2.1p1 | ||||
5529 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) | ||||
5530 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) | ||||
5531 | << IndexExpr->getSourceRange()); | ||||
5532 | |||||
5533 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
5534 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) | ||||
5535 | && !IndexExpr->isTypeDependent()) | ||||
5536 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); | ||||
5537 | |||||
5538 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, | ||||
5539 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object | ||||
5540 | // type. Note that Functions are not objects, and that (in C99 parlance) | ||||
5541 | // incomplete types are not object types. | ||||
5542 | if (ResultType->isFunctionType()) { | ||||
5543 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) | ||||
5544 | << ResultType << BaseExpr->getSourceRange(); | ||||
5545 | return ExprError(); | ||||
5546 | } | ||||
5547 | |||||
5548 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { | ||||
5549 | // GNU extension: subscripting on pointer to void | ||||
5550 | Diag(LLoc, diag::ext_gnu_subscript_void_type) | ||||
5551 | << BaseExpr->getSourceRange(); | ||||
5552 | |||||
5553 | // C forbids expressions of unqualified void type from being l-values. | ||||
5554 | // See IsCForbiddenLValueType. | ||||
5555 | if (!ResultType.hasQualifiers()) VK = VK_RValue; | ||||
5556 | } else if (!ResultType->isDependentType() && | ||||
5557 | RequireCompleteSizedType( | ||||
5558 | LLoc, ResultType, | ||||
5559 | diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) | ||||
5560 | return ExprError(); | ||||
5561 | |||||
5562 | assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5563, __PRETTY_FUNCTION__)) | ||||
5563 | !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType ()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5563, __PRETTY_FUNCTION__)); | ||||
5564 | |||||
5565 | if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && | ||||
5566 | FunctionScopes.size() > 1) { | ||||
5567 | if (auto *TT = | ||||
5568 | LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { | ||||
5569 | for (auto I = FunctionScopes.rbegin(), | ||||
5570 | E = std::prev(FunctionScopes.rend()); | ||||
5571 | I != E; ++I) { | ||||
5572 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); | ||||
5573 | if (CSI == nullptr) | ||||
5574 | break; | ||||
5575 | DeclContext *DC = nullptr; | ||||
5576 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) | ||||
5577 | DC = LSI->CallOperator; | ||||
5578 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) | ||||
5579 | DC = CRSI->TheCapturedDecl; | ||||
5580 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) | ||||
5581 | DC = BSI->TheDecl; | ||||
5582 | if (DC) { | ||||
5583 | if (DC->containsDecl(TT->getDecl())) | ||||
5584 | break; | ||||
5585 | captureVariablyModifiedType( | ||||
5586 | Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); | ||||
5587 | } | ||||
5588 | } | ||||
5589 | } | ||||
5590 | } | ||||
5591 | |||||
5592 | return new (Context) | ||||
5593 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); | ||||
5594 | } | ||||
5595 | |||||
5596 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | ||||
5597 | ParmVarDecl *Param) { | ||||
5598 | if (Param->hasUnparsedDefaultArg()) { | ||||
5599 | // If we've already cleared out the location for the default argument, | ||||
5600 | // that means we're parsing it right now. | ||||
5601 | if (!UnparsedDefaultArgLocs.count(Param)) { | ||||
5602 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; | ||||
5603 | Diag(CallLoc, diag::note_recursive_default_argument_used_here); | ||||
5604 | Param->setInvalidDecl(); | ||||
5605 | return true; | ||||
5606 | } | ||||
5607 | |||||
5608 | Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) | ||||
5609 | << FD << cast<CXXRecordDecl>(FD->getDeclContext()); | ||||
5610 | Diag(UnparsedDefaultArgLocs[Param], | ||||
5611 | diag::note_default_argument_declared_here); | ||||
5612 | return true; | ||||
5613 | } | ||||
5614 | |||||
5615 | if (Param->hasUninstantiatedDefaultArg() && | ||||
5616 | InstantiateDefaultArgument(CallLoc, FD, Param)) | ||||
5617 | return true; | ||||
5618 | |||||
5619 | assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?" ) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5619, __PRETTY_FUNCTION__)); | ||||
5620 | |||||
5621 | // If the default expression creates temporaries, we need to | ||||
5622 | // push them to the current stack of expression temporaries so they'll | ||||
5623 | // be properly destroyed. | ||||
5624 | // FIXME: We should really be rebuilding the default argument with new | ||||
5625 | // bound temporaries; see the comment in PR5810. | ||||
5626 | // We don't need to do that with block decls, though, because | ||||
5627 | // blocks in default argument expression can never capture anything. | ||||
5628 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { | ||||
5629 | // Set the "needs cleanups" bit regardless of whether there are | ||||
5630 | // any explicit objects. | ||||
5631 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); | ||||
5632 | |||||
5633 | // Append all the objects to the cleanup list. Right now, this | ||||
5634 | // should always be a no-op, because blocks in default argument | ||||
5635 | // expressions should never be able to capture anything. | ||||
5636 | assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5637, __PRETTY_FUNCTION__)) | ||||
5637 | "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?" ) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5637, __PRETTY_FUNCTION__)); | ||||
5638 | } | ||||
5639 | |||||
5640 | // We already type-checked the argument, so we know it works. | ||||
5641 | // Just mark all of the declarations in this potentially-evaluated expression | ||||
5642 | // as being "referenced". | ||||
5643 | EnterExpressionEvaluationContext EvalContext( | ||||
5644 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); | ||||
5645 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), | ||||
5646 | /*SkipLocalVariables=*/true); | ||||
5647 | return false; | ||||
5648 | } | ||||
5649 | |||||
5650 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, | ||||
5651 | FunctionDecl *FD, ParmVarDecl *Param) { | ||||
5652 | assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg" ) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5652, __PRETTY_FUNCTION__)); | ||||
5653 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) | ||||
5654 | return ExprError(); | ||||
5655 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); | ||||
5656 | } | ||||
5657 | |||||
5658 | Sema::VariadicCallType | ||||
5659 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, | ||||
5660 | Expr *Fn) { | ||||
5661 | if (Proto && Proto->isVariadic()) { | ||||
5662 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) | ||||
5663 | return VariadicConstructor; | ||||
5664 | else if (Fn && Fn->getType()->isBlockPointerType()) | ||||
5665 | return VariadicBlock; | ||||
5666 | else if (FDecl) { | ||||
5667 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
5668 | if (Method->isInstance()) | ||||
5669 | return VariadicMethod; | ||||
5670 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) | ||||
5671 | return VariadicMethod; | ||||
5672 | return VariadicFunction; | ||||
5673 | } | ||||
5674 | return VariadicDoesNotApply; | ||||
5675 | } | ||||
5676 | |||||
5677 | namespace { | ||||
5678 | class FunctionCallCCC final : public FunctionCallFilterCCC { | ||||
5679 | public: | ||||
5680 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, | ||||
5681 | unsigned NumArgs, MemberExpr *ME) | ||||
5682 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), | ||||
5683 | FunctionName(FuncName) {} | ||||
5684 | |||||
5685 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
5686 | if (!candidate.getCorrectionSpecifier() || | ||||
5687 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { | ||||
5688 | return false; | ||||
5689 | } | ||||
5690 | |||||
5691 | return FunctionCallFilterCCC::ValidateCandidate(candidate); | ||||
5692 | } | ||||
5693 | |||||
5694 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
5695 | return std::make_unique<FunctionCallCCC>(*this); | ||||
5696 | } | ||||
5697 | |||||
5698 | private: | ||||
5699 | const IdentifierInfo *const FunctionName; | ||||
5700 | }; | ||||
5701 | } | ||||
5702 | |||||
5703 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, | ||||
5704 | FunctionDecl *FDecl, | ||||
5705 | ArrayRef<Expr *> Args) { | ||||
5706 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); | ||||
5707 | DeclarationName FuncName = FDecl->getDeclName(); | ||||
5708 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); | ||||
5709 | |||||
5710 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); | ||||
5711 | if (TypoCorrection Corrected = S.CorrectTypo( | ||||
5712 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, | ||||
5713 | S.getScopeForContext(S.CurContext), nullptr, CCC, | ||||
5714 | Sema::CTK_ErrorRecovery)) { | ||||
5715 | if (NamedDecl *ND = Corrected.getFoundDecl()) { | ||||
5716 | if (Corrected.isOverloaded()) { | ||||
5717 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); | ||||
5718 | OverloadCandidateSet::iterator Best; | ||||
5719 | for (NamedDecl *CD : Corrected) { | ||||
5720 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) | ||||
5721 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, | ||||
5722 | OCS); | ||||
5723 | } | ||||
5724 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { | ||||
5725 | case OR_Success: | ||||
5726 | ND = Best->FoundDecl; | ||||
5727 | Corrected.setCorrectionDecl(ND); | ||||
5728 | break; | ||||
5729 | default: | ||||
5730 | break; | ||||
5731 | } | ||||
5732 | } | ||||
5733 | ND = ND->getUnderlyingDecl(); | ||||
5734 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) | ||||
5735 | return Corrected; | ||||
5736 | } | ||||
5737 | } | ||||
5738 | return TypoCorrection(); | ||||
5739 | } | ||||
5740 | |||||
5741 | /// ConvertArgumentsForCall - Converts the arguments specified in | ||||
5742 | /// Args/NumArgs to the parameter types of the function FDecl with | ||||
5743 | /// function prototype Proto. Call is the call expression itself, and | ||||
5744 | /// Fn is the function expression. For a C++ member function, this | ||||
5745 | /// routine does not attempt to convert the object argument. Returns | ||||
5746 | /// true if the call is ill-formed. | ||||
5747 | bool | ||||
5748 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | ||||
5749 | FunctionDecl *FDecl, | ||||
5750 | const FunctionProtoType *Proto, | ||||
5751 | ArrayRef<Expr *> Args, | ||||
5752 | SourceLocation RParenLoc, | ||||
5753 | bool IsExecConfig) { | ||||
5754 | // Bail out early if calling a builtin with custom typechecking. | ||||
5755 | if (FDecl) | ||||
5756 | if (unsigned ID = FDecl->getBuiltinID()) | ||||
5757 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) | ||||
5758 | return false; | ||||
5759 | |||||
5760 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by | ||||
5761 | // assignment, to the types of the corresponding parameter, ... | ||||
5762 | unsigned NumParams = Proto->getNumParams(); | ||||
5763 | bool Invalid = false; | ||||
5764 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; | ||||
5765 | unsigned FnKind = Fn->getType()->isBlockPointerType() | ||||
5766 | ? 1 /* block */ | ||||
5767 | : (IsExecConfig ? 3 /* kernel function (exec config) */ | ||||
5768 | : 0 /* function */); | ||||
5769 | |||||
5770 | // If too few arguments are available (and we don't have default | ||||
5771 | // arguments for the remaining parameters), don't make the call. | ||||
5772 | if (Args.size() < NumParams) { | ||||
5773 | if (Args.size() < MinArgs) { | ||||
5774 | TypoCorrection TC; | ||||
5775 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5776 | unsigned diag_id = | ||||
5777 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5778 | ? diag::err_typecheck_call_too_few_args_suggest | ||||
5779 | : diag::err_typecheck_call_too_few_args_at_least_suggest; | ||||
5780 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs | ||||
5781 | << static_cast<unsigned>(Args.size()) | ||||
5782 | << TC.getCorrectionRange()); | ||||
5783 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) | ||||
5784 | Diag(RParenLoc, | ||||
5785 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5786 | ? diag::err_typecheck_call_too_few_args_one | ||||
5787 | : diag::err_typecheck_call_too_few_args_at_least_one) | ||||
5788 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); | ||||
5789 | else | ||||
5790 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() | ||||
5791 | ? diag::err_typecheck_call_too_few_args | ||||
5792 | : diag::err_typecheck_call_too_few_args_at_least) | ||||
5793 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) | ||||
5794 | << Fn->getSourceRange(); | ||||
5795 | |||||
5796 | // Emit the location of the prototype. | ||||
5797 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5798 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5799 | |||||
5800 | return true; | ||||
5801 | } | ||||
5802 | // We reserve space for the default arguments when we create | ||||
5803 | // the call expression, before calling ConvertArgumentsForCall. | ||||
5804 | assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5805, __PRETTY_FUNCTION__)) | ||||
5805 | "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!" ) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5805, __PRETTY_FUNCTION__)); | ||||
5806 | } | ||||
5807 | |||||
5808 | // If too many are passed and not variadic, error on the extras and drop | ||||
5809 | // them. | ||||
5810 | if (Args.size() > NumParams) { | ||||
5811 | if (!Proto->isVariadic()) { | ||||
5812 | TypoCorrection TC; | ||||
5813 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { | ||||
5814 | unsigned diag_id = | ||||
5815 | MinArgs == NumParams && !Proto->isVariadic() | ||||
5816 | ? diag::err_typecheck_call_too_many_args_suggest | ||||
5817 | : diag::err_typecheck_call_too_many_args_at_most_suggest; | ||||
5818 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams | ||||
5819 | << static_cast<unsigned>(Args.size()) | ||||
5820 | << TC.getCorrectionRange()); | ||||
5821 | } else if (NumParams == 1 && FDecl && | ||||
5822 | FDecl->getParamDecl(0)->getDeclName()) | ||||
5823 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5824 | MinArgs == NumParams | ||||
5825 | ? diag::err_typecheck_call_too_many_args_one | ||||
5826 | : diag::err_typecheck_call_too_many_args_at_most_one) | ||||
5827 | << FnKind << FDecl->getParamDecl(0) | ||||
5828 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() | ||||
5829 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5830 | Args.back()->getEndLoc()); | ||||
5831 | else | ||||
5832 | Diag(Args[NumParams]->getBeginLoc(), | ||||
5833 | MinArgs == NumParams | ||||
5834 | ? diag::err_typecheck_call_too_many_args | ||||
5835 | : diag::err_typecheck_call_too_many_args_at_most) | ||||
5836 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) | ||||
5837 | << Fn->getSourceRange() | ||||
5838 | << SourceRange(Args[NumParams]->getBeginLoc(), | ||||
5839 | Args.back()->getEndLoc()); | ||||
5840 | |||||
5841 | // Emit the location of the prototype. | ||||
5842 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) | ||||
5843 | Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; | ||||
5844 | |||||
5845 | // This deletes the extra arguments. | ||||
5846 | Call->shrinkNumArgs(NumParams); | ||||
5847 | return true; | ||||
5848 | } | ||||
5849 | } | ||||
5850 | SmallVector<Expr *, 8> AllArgs; | ||||
5851 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); | ||||
5852 | |||||
5853 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, | ||||
5854 | AllArgs, CallType); | ||||
5855 | if (Invalid) | ||||
5856 | return true; | ||||
5857 | unsigned TotalNumArgs = AllArgs.size(); | ||||
5858 | for (unsigned i = 0; i < TotalNumArgs; ++i) | ||||
5859 | Call->setArg(i, AllArgs[i]); | ||||
5860 | |||||
5861 | return false; | ||||
5862 | } | ||||
5863 | |||||
5864 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | ||||
5865 | const FunctionProtoType *Proto, | ||||
5866 | unsigned FirstParam, ArrayRef<Expr *> Args, | ||||
5867 | SmallVectorImpl<Expr *> &AllArgs, | ||||
5868 | VariadicCallType CallType, bool AllowExplicit, | ||||
5869 | bool IsListInitialization) { | ||||
5870 | unsigned NumParams = Proto->getNumParams(); | ||||
5871 | bool Invalid = false; | ||||
5872 | size_t ArgIx = 0; | ||||
5873 | // Continue to check argument types (even if we have too few/many args). | ||||
5874 | for (unsigned i = FirstParam; i < NumParams; i++) { | ||||
5875 | QualType ProtoArgType = Proto->getParamType(i); | ||||
5876 | |||||
5877 | Expr *Arg; | ||||
5878 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; | ||||
5879 | if (ArgIx < Args.size()) { | ||||
5880 | Arg = Args[ArgIx++]; | ||||
5881 | |||||
5882 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, | ||||
5883 | diag::err_call_incomplete_argument, Arg)) | ||||
5884 | return true; | ||||
5885 | |||||
5886 | // Strip the unbridged-cast placeholder expression off, if applicable. | ||||
5887 | bool CFAudited = false; | ||||
5888 | if (Arg->getType() == Context.ARCUnbridgedCastTy && | ||||
5889 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5890 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5891 | Arg = stripARCUnbridgedCast(Arg); | ||||
5892 | else if (getLangOpts().ObjCAutoRefCount && | ||||
5893 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && | ||||
5894 | (!Param || !Param->hasAttr<CFConsumedAttr>())) | ||||
5895 | CFAudited = true; | ||||
5896 | |||||
5897 | if (Proto->getExtParameterInfo(i).isNoEscape()) | ||||
5898 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) | ||||
5899 | BE->getBlockDecl()->setDoesNotEscape(); | ||||
5900 | |||||
5901 | InitializedEntity Entity = | ||||
5902 | Param ? InitializedEntity::InitializeParameter(Context, Param, | ||||
5903 | ProtoArgType) | ||||
5904 | : InitializedEntity::InitializeParameter( | ||||
5905 | Context, ProtoArgType, Proto->isParamConsumed(i)); | ||||
5906 | |||||
5907 | // Remember that parameter belongs to a CF audited API. | ||||
5908 | if (CFAudited) | ||||
5909 | Entity.setParameterCFAudited(); | ||||
5910 | |||||
5911 | ExprResult ArgE = PerformCopyInitialization( | ||||
5912 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); | ||||
5913 | if (ArgE.isInvalid()) | ||||
5914 | return true; | ||||
5915 | |||||
5916 | Arg = ArgE.getAs<Expr>(); | ||||
5917 | } else { | ||||
5918 | assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee" ) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 5918, __PRETTY_FUNCTION__)); | ||||
5919 | |||||
5920 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); | ||||
5921 | if (ArgExpr.isInvalid()) | ||||
5922 | return true; | ||||
5923 | |||||
5924 | Arg = ArgExpr.getAs<Expr>(); | ||||
5925 | } | ||||
5926 | |||||
5927 | // Check for array bounds violations for each argument to the call. This | ||||
5928 | // check only triggers warnings when the argument isn't a more complex Expr | ||||
5929 | // with its own checking, such as a BinaryOperator. | ||||
5930 | CheckArrayAccess(Arg); | ||||
5931 | |||||
5932 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). | ||||
5933 | CheckStaticArrayArgument(CallLoc, Param, Arg); | ||||
5934 | |||||
5935 | AllArgs.push_back(Arg); | ||||
5936 | } | ||||
5937 | |||||
5938 | // If this is a variadic call, handle args passed through "...". | ||||
5939 | if (CallType != VariadicDoesNotApply) { | ||||
5940 | // Assume that extern "C" functions with variadic arguments that | ||||
5941 | // return __unknown_anytype aren't *really* variadic. | ||||
5942 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && | ||||
5943 | FDecl->isExternC()) { | ||||
5944 | for (Expr *A : Args.slice(ArgIx)) { | ||||
5945 | QualType paramType; // ignored | ||||
5946 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); | ||||
5947 | Invalid |= arg.isInvalid(); | ||||
5948 | AllArgs.push_back(arg.get()); | ||||
5949 | } | ||||
5950 | |||||
5951 | // Otherwise do argument promotion, (C99 6.5.2.2p7). | ||||
5952 | } else { | ||||
5953 | for (Expr *A : Args.slice(ArgIx)) { | ||||
5954 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); | ||||
5955 | Invalid |= Arg.isInvalid(); | ||||
5956 | AllArgs.push_back(Arg.get()); | ||||
5957 | } | ||||
5958 | } | ||||
5959 | |||||
5960 | // Check for array bounds violations. | ||||
5961 | for (Expr *A : Args.slice(ArgIx)) | ||||
5962 | CheckArrayAccess(A); | ||||
5963 | } | ||||
5964 | return Invalid; | ||||
5965 | } | ||||
5966 | |||||
5967 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { | ||||
5968 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); | ||||
5969 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) | ||||
5970 | TL = DTL.getOriginalLoc(); | ||||
5971 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) | ||||
5972 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) | ||||
5973 | << ATL.getLocalSourceRange(); | ||||
5974 | } | ||||
5975 | |||||
5976 | /// CheckStaticArrayArgument - If the given argument corresponds to a static | ||||
5977 | /// array parameter, check that it is non-null, and that if it is formed by | ||||
5978 | /// array-to-pointer decay, the underlying array is sufficiently large. | ||||
5979 | /// | ||||
5980 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the | ||||
5981 | /// array type derivation, then for each call to the function, the value of the | ||||
5982 | /// corresponding actual argument shall provide access to the first element of | ||||
5983 | /// an array with at least as many elements as specified by the size expression. | ||||
5984 | void | ||||
5985 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, | ||||
5986 | ParmVarDecl *Param, | ||||
5987 | const Expr *ArgExpr) { | ||||
5988 | // Static array parameters are not supported in C++. | ||||
5989 | if (!Param || getLangOpts().CPlusPlus) | ||||
5990 | return; | ||||
5991 | |||||
5992 | QualType OrigTy = Param->getOriginalType(); | ||||
5993 | |||||
5994 | const ArrayType *AT = Context.getAsArrayType(OrigTy); | ||||
5995 | if (!AT || AT->getSizeModifier() != ArrayType::Static) | ||||
5996 | return; | ||||
5997 | |||||
5998 | if (ArgExpr->isNullPointerConstant(Context, | ||||
5999 | Expr::NPC_NeverValueDependent)) { | ||||
6000 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); | ||||
6001 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6002 | return; | ||||
6003 | } | ||||
6004 | |||||
6005 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); | ||||
6006 | if (!CAT) | ||||
6007 | return; | ||||
6008 | |||||
6009 | const ConstantArrayType *ArgCAT = | ||||
6010 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); | ||||
6011 | if (!ArgCAT) | ||||
6012 | return; | ||||
6013 | |||||
6014 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), | ||||
6015 | ArgCAT->getElementType())) { | ||||
6016 | if (ArgCAT->getSize().ult(CAT->getSize())) { | ||||
6017 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6018 | << ArgExpr->getSourceRange() | ||||
6019 | << (unsigned)ArgCAT->getSize().getZExtValue() | ||||
6020 | << (unsigned)CAT->getSize().getZExtValue() << 0; | ||||
6021 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6022 | } | ||||
6023 | return; | ||||
6024 | } | ||||
6025 | |||||
6026 | Optional<CharUnits> ArgSize = | ||||
6027 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); | ||||
6028 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); | ||||
6029 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { | ||||
6030 | Diag(CallLoc, diag::warn_static_array_too_small) | ||||
6031 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() | ||||
6032 | << (unsigned)ParmSize->getQuantity() << 1; | ||||
6033 | DiagnoseCalleeStaticArrayParam(*this, Param); | ||||
6034 | } | ||||
6035 | } | ||||
6036 | |||||
6037 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
6038 | /// to have a function type. | ||||
6039 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); | ||||
6040 | |||||
6041 | /// Is the given type a placeholder that we need to lower out | ||||
6042 | /// immediately during argument processing? | ||||
6043 | static bool isPlaceholderToRemoveAsArg(QualType type) { | ||||
6044 | // Placeholders are never sugared. | ||||
6045 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); | ||||
6046 | if (!placeholder) return false; | ||||
6047 | |||||
6048 | switch (placeholder->getKind()) { | ||||
6049 | // Ignore all the non-placeholder types. | ||||
6050 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
6051 | case BuiltinType::Id: | ||||
6052 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
6053 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
6054 | case BuiltinType::Id: | ||||
6055 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
6056 | // In practice we'll never use this, since all SVE types are sugared | ||||
6057 | // via TypedefTypes rather than exposed directly as BuiltinTypes. | ||||
6058 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
6059 | case BuiltinType::Id: | ||||
6060 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
6061 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
6062 | case BuiltinType::Id: | ||||
6063 | #include "clang/Basic/PPCTypes.def" | ||||
6064 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
6065 | #include "clang/Basic/RISCVVTypes.def" | ||||
6066 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) | ||||
6067 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: | ||||
6068 | #include "clang/AST/BuiltinTypes.def" | ||||
6069 | return false; | ||||
6070 | |||||
6071 | // We cannot lower out overload sets; they might validly be resolved | ||||
6072 | // by the call machinery. | ||||
6073 | case BuiltinType::Overload: | ||||
6074 | return false; | ||||
6075 | |||||
6076 | // Unbridged casts in ARC can be handled in some call positions and | ||||
6077 | // should be left in place. | ||||
6078 | case BuiltinType::ARCUnbridgedCast: | ||||
6079 | return false; | ||||
6080 | |||||
6081 | // Pseudo-objects should be converted as soon as possible. | ||||
6082 | case BuiltinType::PseudoObject: | ||||
6083 | return true; | ||||
6084 | |||||
6085 | // The debugger mode could theoretically but currently does not try | ||||
6086 | // to resolve unknown-typed arguments based on known parameter types. | ||||
6087 | case BuiltinType::UnknownAny: | ||||
6088 | return true; | ||||
6089 | |||||
6090 | // These are always invalid as call arguments and should be reported. | ||||
6091 | case BuiltinType::BoundMember: | ||||
6092 | case BuiltinType::BuiltinFn: | ||||
6093 | case BuiltinType::IncompleteMatrixIdx: | ||||
6094 | case BuiltinType::OMPArraySection: | ||||
6095 | case BuiltinType::OMPArrayShaping: | ||||
6096 | case BuiltinType::OMPIterator: | ||||
6097 | return true; | ||||
6098 | |||||
6099 | } | ||||
6100 | llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6100); | ||||
6101 | } | ||||
6102 | |||||
6103 | /// Check an argument list for placeholders that we won't try to | ||||
6104 | /// handle later. | ||||
6105 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { | ||||
6106 | // Apply this processing to all the arguments at once instead of | ||||
6107 | // dying at the first failure. | ||||
6108 | bool hasInvalid = false; | ||||
6109 | for (size_t i = 0, e = args.size(); i != e; i++) { | ||||
6110 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { | ||||
6111 | ExprResult result = S.CheckPlaceholderExpr(args[i]); | ||||
6112 | if (result.isInvalid()) hasInvalid = true; | ||||
6113 | else args[i] = result.get(); | ||||
6114 | } | ||||
6115 | } | ||||
6116 | return hasInvalid; | ||||
6117 | } | ||||
6118 | |||||
6119 | /// If a builtin function has a pointer argument with no explicit address | ||||
6120 | /// space, then it should be able to accept a pointer to any address | ||||
6121 | /// space as input. In order to do this, we need to replace the | ||||
6122 | /// standard builtin declaration with one that uses the same address space | ||||
6123 | /// as the call. | ||||
6124 | /// | ||||
6125 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. | ||||
6126 | /// it does not contain any pointer arguments without | ||||
6127 | /// an address space qualifer. Otherwise the rewritten | ||||
6128 | /// FunctionDecl is returned. | ||||
6129 | /// TODO: Handle pointer return types. | ||||
6130 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, | ||||
6131 | FunctionDecl *FDecl, | ||||
6132 | MultiExprArg ArgExprs) { | ||||
6133 | |||||
6134 | QualType DeclType = FDecl->getType(); | ||||
6135 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); | ||||
6136 | |||||
6137 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || | ||||
6138 | ArgExprs.size() < FT->getNumParams()) | ||||
6139 | return nullptr; | ||||
6140 | |||||
6141 | bool NeedsNewDecl = false; | ||||
6142 | unsigned i = 0; | ||||
6143 | SmallVector<QualType, 8> OverloadParams; | ||||
6144 | |||||
6145 | for (QualType ParamType : FT->param_types()) { | ||||
6146 | |||||
6147 | // Convert array arguments to pointer to simplify type lookup. | ||||
6148 | ExprResult ArgRes = | ||||
6149 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); | ||||
6150 | if (ArgRes.isInvalid()) | ||||
6151 | return nullptr; | ||||
6152 | Expr *Arg = ArgRes.get(); | ||||
6153 | QualType ArgType = Arg->getType(); | ||||
6154 | if (!ParamType->isPointerType() || | ||||
6155 | ParamType.hasAddressSpace() || | ||||
6156 | !ArgType->isPointerType() || | ||||
6157 | !ArgType->getPointeeType().hasAddressSpace()) { | ||||
6158 | OverloadParams.push_back(ParamType); | ||||
6159 | continue; | ||||
6160 | } | ||||
6161 | |||||
6162 | QualType PointeeType = ParamType->getPointeeType(); | ||||
6163 | if (PointeeType.hasAddressSpace()) | ||||
6164 | continue; | ||||
6165 | |||||
6166 | NeedsNewDecl = true; | ||||
6167 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); | ||||
6168 | |||||
6169 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); | ||||
6170 | OverloadParams.push_back(Context.getPointerType(PointeeType)); | ||||
6171 | } | ||||
6172 | |||||
6173 | if (!NeedsNewDecl) | ||||
6174 | return nullptr; | ||||
6175 | |||||
6176 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6177 | EPI.Variadic = FT->isVariadic(); | ||||
6178 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), | ||||
6179 | OverloadParams, EPI); | ||||
6180 | DeclContext *Parent = FDecl->getParent(); | ||||
6181 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, | ||||
6182 | FDecl->getLocation(), | ||||
6183 | FDecl->getLocation(), | ||||
6184 | FDecl->getIdentifier(), | ||||
6185 | OverloadTy, | ||||
6186 | /*TInfo=*/nullptr, | ||||
6187 | SC_Extern, false, | ||||
6188 | /*hasPrototype=*/true); | ||||
6189 | SmallVector<ParmVarDecl*, 16> Params; | ||||
6190 | FT = cast<FunctionProtoType>(OverloadTy); | ||||
6191 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
6192 | QualType ParamType = FT->getParamType(i); | ||||
6193 | ParmVarDecl *Parm = | ||||
6194 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), | ||||
6195 | SourceLocation(), nullptr, ParamType, | ||||
6196 | /*TInfo=*/nullptr, SC_None, nullptr); | ||||
6197 | Parm->setScopeInfo(0, i); | ||||
6198 | Params.push_back(Parm); | ||||
6199 | } | ||||
6200 | OverloadDecl->setParams(Params); | ||||
6201 | Sema->mergeDeclAttributes(OverloadDecl, FDecl); | ||||
6202 | return OverloadDecl; | ||||
6203 | } | ||||
6204 | |||||
6205 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, | ||||
6206 | FunctionDecl *Callee, | ||||
6207 | MultiExprArg ArgExprs) { | ||||
6208 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and | ||||
6209 | // similar attributes) really don't like it when functions are called with an | ||||
6210 | // invalid number of args. | ||||
6211 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), | ||||
6212 | /*PartialOverloading=*/false) && | ||||
6213 | !Callee->isVariadic()) | ||||
6214 | return; | ||||
6215 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) | ||||
6216 | return; | ||||
6217 | |||||
6218 | if (const EnableIfAttr *Attr = | ||||
6219 | S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { | ||||
6220 | S.Diag(Fn->getBeginLoc(), | ||||
6221 | isa<CXXMethodDecl>(Callee) | ||||
6222 | ? diag::err_ovl_no_viable_member_function_in_call | ||||
6223 | : diag::err_ovl_no_viable_function_in_call) | ||||
6224 | << Callee << Callee->getSourceRange(); | ||||
6225 | S.Diag(Callee->getLocation(), | ||||
6226 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | ||||
6227 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | ||||
6228 | return; | ||||
6229 | } | ||||
6230 | } | ||||
6231 | |||||
6232 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( | ||||
6233 | const UnresolvedMemberExpr *const UME, Sema &S) { | ||||
6234 | |||||
6235 | const auto GetFunctionLevelDCIfCXXClass = | ||||
6236 | [](Sema &S) -> const CXXRecordDecl * { | ||||
6237 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); | ||||
6238 | if (!DC || !DC->getParent()) | ||||
6239 | return nullptr; | ||||
6240 | |||||
6241 | // If the call to some member function was made from within a member | ||||
6242 | // function body 'M' return return 'M's parent. | ||||
6243 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
6244 | return MD->getParent()->getCanonicalDecl(); | ||||
6245 | // else the call was made from within a default member initializer of a | ||||
6246 | // class, so return the class. | ||||
6247 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
6248 | return RD->getCanonicalDecl(); | ||||
6249 | return nullptr; | ||||
6250 | }; | ||||
6251 | // If our DeclContext is neither a member function nor a class (in the | ||||
6252 | // case of a lambda in a default member initializer), we can't have an | ||||
6253 | // enclosing 'this'. | ||||
6254 | |||||
6255 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); | ||||
6256 | if (!CurParentClass) | ||||
6257 | return false; | ||||
6258 | |||||
6259 | // The naming class for implicit member functions call is the class in which | ||||
6260 | // name lookup starts. | ||||
6261 | const CXXRecordDecl *const NamingClass = | ||||
6262 | UME->getNamingClass()->getCanonicalDecl(); | ||||
6263 | assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access" ) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6263, __PRETTY_FUNCTION__)); | ||||
6264 | |||||
6265 | // If the unresolved member functions were found in a 'naming class' that is | ||||
6266 | // related (either the same or derived from) to the class that contains the | ||||
6267 | // member function that itself contained the implicit member access. | ||||
6268 | |||||
6269 | return CurParentClass == NamingClass || | ||||
6270 | CurParentClass->isDerivedFrom(NamingClass); | ||||
6271 | } | ||||
6272 | |||||
6273 | static void | ||||
6274 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6275 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { | ||||
6276 | |||||
6277 | if (!UME) | ||||
6278 | return; | ||||
6279 | |||||
6280 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); | ||||
6281 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't | ||||
6282 | // already been captured, or if this is an implicit member function call (if | ||||
6283 | // it isn't, an attempt to capture 'this' should already have been made). | ||||
6284 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || | ||||
6285 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) | ||||
6286 | return; | ||||
6287 | |||||
6288 | // Check if the naming class in which the unresolved members were found is | ||||
6289 | // related (same as or is a base of) to the enclosing class. | ||||
6290 | |||||
6291 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) | ||||
6292 | return; | ||||
6293 | |||||
6294 | |||||
6295 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); | ||||
6296 | // If the enclosing function is not dependent, then this lambda is | ||||
6297 | // capture ready, so if we can capture this, do so. | ||||
6298 | if (!EnclosingFunctionCtx->isDependentContext()) { | ||||
6299 | // If the current lambda and all enclosing lambdas can capture 'this' - | ||||
6300 | // then go ahead and capture 'this' (since our unresolved overload set | ||||
6301 | // contains at least one non-static member function). | ||||
6302 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) | ||||
6303 | S.CheckCXXThisCapture(CallLoc); | ||||
6304 | } else if (S.CurContext->isDependentContext()) { | ||||
6305 | // ... since this is an implicit member reference, that might potentially | ||||
6306 | // involve a 'this' capture, mark 'this' for potential capture in | ||||
6307 | // enclosing lambdas. | ||||
6308 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) | ||||
6309 | CurLSI->addPotentialThisCapture(CallLoc); | ||||
6310 | } | ||||
6311 | } | ||||
6312 | |||||
6313 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6314 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6315 | Expr *ExecConfig) { | ||||
6316 | ExprResult Call = | ||||
6317 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6318 | /*IsExecConfig=*/false, /*AllowRecovery=*/true); | ||||
6319 | if (Call.isInvalid()) | ||||
6320 | return Call; | ||||
6321 | |||||
6322 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier | ||||
6323 | // language modes. | ||||
6324 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { | ||||
6325 | if (ULE->hasExplicitTemplateArgs() && | ||||
6326 | ULE->decls_begin() == ULE->decls_end()) { | ||||
6327 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 | ||||
6328 | ? diag::warn_cxx17_compat_adl_only_template_id | ||||
6329 | : diag::ext_adl_only_template_id) | ||||
6330 | << ULE->getName(); | ||||
6331 | } | ||||
6332 | } | ||||
6333 | |||||
6334 | if (LangOpts.OpenMP) | ||||
6335 | Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, | ||||
6336 | ExecConfig); | ||||
6337 | |||||
6338 | return Call; | ||||
6339 | } | ||||
6340 | |||||
6341 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. | ||||
6342 | /// This provides the location of the left/right parens and a list of comma | ||||
6343 | /// locations. | ||||
6344 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, | ||||
6345 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | ||||
6346 | Expr *ExecConfig, bool IsExecConfig, | ||||
6347 | bool AllowRecovery) { | ||||
6348 | // Since this might be a postfix expression, get rid of ParenListExprs. | ||||
6349 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); | ||||
6350 | if (Result.isInvalid()) return ExprError(); | ||||
6351 | Fn = Result.get(); | ||||
6352 | |||||
6353 | if (checkArgsForPlaceholders(*this, ArgExprs)) | ||||
6354 | return ExprError(); | ||||
6355 | |||||
6356 | if (getLangOpts().CPlusPlus) { | ||||
6357 | // If this is a pseudo-destructor expression, build the call immediately. | ||||
6358 | if (isa<CXXPseudoDestructorExpr>(Fn)) { | ||||
6359 | if (!ArgExprs.empty()) { | ||||
6360 | // Pseudo-destructor calls should not have any arguments. | ||||
6361 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) | ||||
6362 | << FixItHint::CreateRemoval( | ||||
6363 | SourceRange(ArgExprs.front()->getBeginLoc(), | ||||
6364 | ArgExprs.back()->getEndLoc())); | ||||
6365 | } | ||||
6366 | |||||
6367 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, | ||||
6368 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6369 | } | ||||
6370 | if (Fn->getType() == Context.PseudoObjectTy) { | ||||
6371 | ExprResult result = CheckPlaceholderExpr(Fn); | ||||
6372 | if (result.isInvalid()) return ExprError(); | ||||
6373 | Fn = result.get(); | ||||
6374 | } | ||||
6375 | |||||
6376 | // Determine whether this is a dependent call inside a C++ template, | ||||
6377 | // in which case we won't do any semantic analysis now. | ||||
6378 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { | ||||
6379 | if (ExecConfig) { | ||||
6380 | return CUDAKernelCallExpr::Create( | ||||
6381 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, | ||||
6382 | Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6383 | } else { | ||||
6384 | |||||
6385 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( | ||||
6386 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), | ||||
6387 | Fn->getBeginLoc()); | ||||
6388 | |||||
6389 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6390 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6391 | } | ||||
6392 | } | ||||
6393 | |||||
6394 | // Determine whether this is a call to an object (C++ [over.call.object]). | ||||
6395 | if (Fn->getType()->isRecordType()) | ||||
6396 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, | ||||
6397 | RParenLoc); | ||||
6398 | |||||
6399 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6400 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6401 | if (result.isInvalid()) return ExprError(); | ||||
6402 | Fn = result.get(); | ||||
6403 | } | ||||
6404 | |||||
6405 | if (Fn->getType() == Context.BoundMemberTy) { | ||||
6406 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6407 | RParenLoc, AllowRecovery); | ||||
6408 | } | ||||
6409 | } | ||||
6410 | |||||
6411 | // Check for overloaded calls. This can happen even in C due to extensions. | ||||
6412 | if (Fn->getType() == Context.OverloadTy) { | ||||
6413 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); | ||||
6414 | |||||
6415 | // We aren't supposed to apply this logic if there's an '&' involved. | ||||
6416 | if (!find.HasFormOfMemberPointer) { | ||||
6417 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) | ||||
6418 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, | ||||
6419 | VK_RValue, RParenLoc, CurFPFeatureOverrides()); | ||||
6420 | OverloadExpr *ovl = find.Expression; | ||||
6421 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) | ||||
6422 | return BuildOverloadedCallExpr( | ||||
6423 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, | ||||
6424 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); | ||||
6425 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, | ||||
6426 | RParenLoc, AllowRecovery); | ||||
6427 | } | ||||
6428 | } | ||||
6429 | |||||
6430 | // If we're directly calling a function, get the appropriate declaration. | ||||
6431 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6432 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); | ||||
6433 | if (result.isInvalid()) return ExprError(); | ||||
6434 | Fn = result.get(); | ||||
6435 | } | ||||
6436 | |||||
6437 | Expr *NakedFn = Fn->IgnoreParens(); | ||||
6438 | |||||
6439 | bool CallingNDeclIndirectly = false; | ||||
6440 | NamedDecl *NDecl = nullptr; | ||||
6441 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { | ||||
6442 | if (UnOp->getOpcode() == UO_AddrOf) { | ||||
6443 | CallingNDeclIndirectly = true; | ||||
6444 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); | ||||
6445 | } | ||||
6446 | } | ||||
6447 | |||||
6448 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { | ||||
6449 | NDecl = DRE->getDecl(); | ||||
6450 | |||||
6451 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); | ||||
6452 | if (FDecl && FDecl->getBuiltinID()) { | ||||
6453 | // Rewrite the function decl for this builtin by replacing parameters | ||||
6454 | // with no explicit address space with the address space of the arguments | ||||
6455 | // in ArgExprs. | ||||
6456 | if ((FDecl = | ||||
6457 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { | ||||
6458 | NDecl = FDecl; | ||||
6459 | Fn = DeclRefExpr::Create( | ||||
6460 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, | ||||
6461 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, | ||||
6462 | nullptr, DRE->isNonOdrUse()); | ||||
6463 | } | ||||
6464 | } | ||||
6465 | } else if (isa<MemberExpr>(NakedFn)) | ||||
6466 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); | ||||
6467 | |||||
6468 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { | ||||
6469 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( | ||||
6470 | FD, /*Complain=*/true, Fn->getBeginLoc())) | ||||
6471 | return ExprError(); | ||||
6472 | |||||
6473 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) | ||||
6474 | return ExprError(); | ||||
6475 | |||||
6476 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); | ||||
6477 | } | ||||
6478 | |||||
6479 | if (Context.isDependenceAllowed() && | ||||
6480 | (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { | ||||
6481 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6481, __PRETTY_FUNCTION__)); | ||||
6482 | assert((Fn->containsErrors() ||(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6485, __PRETTY_FUNCTION__)) | ||||
6483 | llvm::any_of(ArgExprs,(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6485, __PRETTY_FUNCTION__)) | ||||
6484 | [](clang::Expr *E) { return E->containsErrors(); })) &&(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6485, __PRETTY_FUNCTION__)) | ||||
6485 | "should only occur in error-recovery path.")(((Fn->containsErrors() || llvm::any_of(ArgExprs, [](clang ::Expr *E) { return E->containsErrors(); })) && "should only occur in error-recovery path." ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6485, __PRETTY_FUNCTION__)); | ||||
6486 | QualType ReturnType = | ||||
6487 | llvm::isa_and_nonnull<FunctionDecl>(NDecl) | ||||
6488 | ? cast<FunctionDecl>(NDecl)->getCallResultType() | ||||
6489 | : Context.DependentTy; | ||||
6490 | return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, | ||||
6491 | Expr::getValueKindForType(ReturnType), RParenLoc, | ||||
6492 | CurFPFeatureOverrides()); | ||||
6493 | } | ||||
6494 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, | ||||
6495 | ExecConfig, IsExecConfig); | ||||
6496 | } | ||||
6497 | |||||
6498 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. | ||||
6499 | /// | ||||
6500 | /// __builtin_astype( value, dst type ) | ||||
6501 | /// | ||||
6502 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6503 | SourceLocation BuiltinLoc, | ||||
6504 | SourceLocation RParenLoc) { | ||||
6505 | ExprValueKind VK = VK_RValue; | ||||
6506 | ExprObjectKind OK = OK_Ordinary; | ||||
6507 | QualType DstTy = GetTypeFromParser(ParsedDestTy); | ||||
6508 | QualType SrcTy = E->getType(); | ||||
6509 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) | ||||
6510 | return ExprError(Diag(BuiltinLoc, | ||||
6511 | diag::err_invalid_astype_of_different_size) | ||||
6512 | << DstTy | ||||
6513 | << SrcTy | ||||
6514 | << E->getSourceRange()); | ||||
6515 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); | ||||
6516 | } | ||||
6517 | |||||
6518 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the | ||||
6519 | /// provided arguments. | ||||
6520 | /// | ||||
6521 | /// __builtin_convertvector( value, dst type ) | ||||
6522 | /// | ||||
6523 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | ||||
6524 | SourceLocation BuiltinLoc, | ||||
6525 | SourceLocation RParenLoc) { | ||||
6526 | TypeSourceInfo *TInfo; | ||||
6527 | GetTypeFromParser(ParsedDestTy, &TInfo); | ||||
6528 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); | ||||
6529 | } | ||||
6530 | |||||
6531 | /// BuildResolvedCallExpr - Build a call to a resolved expression, | ||||
6532 | /// i.e. an expression not of \p OverloadTy. The expression should | ||||
6533 | /// unary-convert to an expression of function-pointer or | ||||
6534 | /// block-pointer type. | ||||
6535 | /// | ||||
6536 | /// \param NDecl the declaration being called, if available | ||||
6537 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, | ||||
6538 | SourceLocation LParenLoc, | ||||
6539 | ArrayRef<Expr *> Args, | ||||
6540 | SourceLocation RParenLoc, Expr *Config, | ||||
6541 | bool IsExecConfig, ADLCallKind UsesADL) { | ||||
6542 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); | ||||
| |||||
6543 | unsigned BuiltinID = (FDecl
| ||||
6544 | |||||
6545 | // Functions with 'interrupt' attribute cannot be called directly. | ||||
6546 | if (FDecl
| ||||
6547 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); | ||||
6548 | return ExprError(); | ||||
6549 | } | ||||
6550 | |||||
6551 | // Interrupt handlers don't save off the VFP regs automatically on ARM, | ||||
6552 | // so there's some risk when calling out to non-interrupt handler functions | ||||
6553 | // that the callee might not preserve them. This is easy to diagnose here, | ||||
6554 | // but can be very challenging to debug. | ||||
6555 | if (auto *Caller = getCurFunctionDecl()) | ||||
6556 | if (Caller->hasAttr<ARMInterruptAttr>()) { | ||||
6557 | bool VFP = Context.getTargetInfo().hasFeature("vfp"); | ||||
6558 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) | ||||
6559 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); | ||||
6560 | } | ||||
6561 | |||||
6562 | // Promote the function operand. | ||||
6563 | // We special-case function promotion here because we only allow promoting | ||||
6564 | // builtin functions to function pointers in the callee of a call. | ||||
6565 | ExprResult Result; | ||||
6566 | QualType ResultTy; | ||||
6567 | if (BuiltinID
| ||||
6568 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { | ||||
6569 | // Extract the return type from the (builtin) function pointer type. | ||||
6570 | // FIXME Several builtins still have setType in | ||||
6571 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in | ||||
6572 | // Builtins.def to ensure they are correct before removing setType calls. | ||||
6573 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); | ||||
6574 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); | ||||
6575 | ResultTy = FDecl->getCallResultType(); | ||||
6576 | } else { | ||||
6577 | Result = CallExprUnaryConversions(Fn); | ||||
6578 | ResultTy = Context.BoolTy; | ||||
6579 | } | ||||
6580 | if (Result.isInvalid()) | ||||
6581 | return ExprError(); | ||||
6582 | Fn = Result.get(); | ||||
6583 | |||||
6584 | // Check for a valid function type, but only if it is not a builtin which | ||||
6585 | // requires custom type checking. These will be handled by | ||||
6586 | // CheckBuiltinFunctionCall below just after creation of the call expression. | ||||
6587 | const FunctionType *FuncT = nullptr; | ||||
6588 | if (!BuiltinID
| ||||
6589 | retry: | ||||
6590 | if (const PointerType *PT
| ||||
6591 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall | ||||
6592 | // have type pointer to function". | ||||
6593 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); | ||||
6594 | if (!FuncT) | ||||
6595 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6596 | << Fn->getType() << Fn->getSourceRange()); | ||||
6597 | } else if (const BlockPointerType *BPT = | ||||
6598 | Fn->getType()->getAs<BlockPointerType>()) { | ||||
6599 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); | ||||
6600 | } else { | ||||
6601 | // Handle calls to expressions of unknown-any type. | ||||
6602 | if (Fn->getType() == Context.UnknownAnyTy) { | ||||
6603 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); | ||||
6604 | if (rewrite.isInvalid()) | ||||
6605 | return ExprError(); | ||||
6606 | Fn = rewrite.get(); | ||||
6607 | goto retry; | ||||
6608 | } | ||||
6609 | |||||
6610 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) | ||||
6611 | << Fn->getType() << Fn->getSourceRange()); | ||||
6612 | } | ||||
6613 | } | ||||
6614 | |||||
6615 | // Get the number of parameters in the function prototype, if any. | ||||
6616 | // We will allocate space for max(Args.size(), NumParams) arguments | ||||
6617 | // in the call expression. | ||||
6618 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); | ||||
6619 | unsigned NumParams = Proto
| ||||
6620 | |||||
6621 | CallExpr *TheCall; | ||||
6622 | if (Config) { | ||||
6623 | assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6624, __PRETTY_FUNCTION__)) | ||||
6624 | "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL" ) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6624, __PRETTY_FUNCTION__)); | ||||
6625 | TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), | ||||
6626 | Args, ResultTy, VK_RValue, RParenLoc, | ||||
6627 | CurFPFeatureOverrides(), NumParams); | ||||
6628 | } else { | ||||
6629 | TheCall = | ||||
6630 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||
6631 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6632 | } | ||||
6633 | |||||
6634 | if (!Context.isDependenceAllowed()) { | ||||
6635 | // Forget about the nulled arguments since typo correction | ||||
6636 | // do not handle them well. | ||||
6637 | TheCall->shrinkNumArgs(Args.size()); | ||||
6638 | // C cannot always handle TypoExpr nodes in builtin calls and direct | ||||
6639 | // function calls as their argument checking don't necessarily handle | ||||
6640 | // dependent types properly, so make sure any TypoExprs have been | ||||
6641 | // dealt with. | ||||
6642 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); | ||||
6643 | if (!Result.isUsable()) return ExprError(); | ||||
6644 | CallExpr *TheOldCall = TheCall; | ||||
6645 | TheCall = dyn_cast<CallExpr>(Result.get()); | ||||
6646 | bool CorrectedTypos = TheCall != TheOldCall; | ||||
6647 | if (!TheCall) return Result; | ||||
6648 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); | ||||
6649 | |||||
6650 | // A new call expression node was created if some typos were corrected. | ||||
6651 | // However it may not have been constructed with enough storage. In this | ||||
6652 | // case, rebuild the node with enough storage. The waste of space is | ||||
6653 | // immaterial since this only happens when some typos were corrected. | ||||
6654 | if (CorrectedTypos && Args.size() < NumParams) { | ||||
6655 | if (Config) | ||||
6656 | TheCall = CUDAKernelCallExpr::Create( | ||||
6657 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, | ||||
6658 | RParenLoc, CurFPFeatureOverrides(), NumParams); | ||||
6659 | else | ||||
6660 | TheCall = | ||||
6661 | CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, | ||||
6662 | CurFPFeatureOverrides(), NumParams, UsesADL); | ||||
6663 | } | ||||
6664 | // We can now handle the nulled arguments for the default arguments. | ||||
6665 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); | ||||
6666 | } | ||||
6667 | |||||
6668 | // Bail out early if calling a builtin with custom type checking. | ||||
6669 | if (BuiltinID
| ||||
6670 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6671 | |||||
6672 | if (getLangOpts().CUDA) { | ||||
6673 | if (Config
| ||||
6674 | // CUDA: Kernel calls must be to global functions | ||||
6675 | if (FDecl
| ||||
6676 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) | ||||
6677 | << FDecl << Fn->getSourceRange()); | ||||
6678 | |||||
6679 | // CUDA: Kernel function must have 'void' return type | ||||
6680 | if (!FuncT->getReturnType()->isVoidType() && | ||||
| |||||
6681 | !FuncT->getReturnType()->getAs<AutoType>() && | ||||
6682 | !FuncT->getReturnType()->isInstantiationDependentType()) | ||||
6683 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) | ||||
6684 | << Fn->getType() << Fn->getSourceRange()); | ||||
6685 | } else { | ||||
6686 | // CUDA: Calls to global functions must be configured | ||||
6687 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) | ||||
6688 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) | ||||
6689 | << FDecl << Fn->getSourceRange()); | ||||
6690 | } | ||||
6691 | } | ||||
6692 | |||||
6693 | // Check for a valid return type | ||||
6694 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, | ||||
6695 | FDecl)) | ||||
6696 | return ExprError(); | ||||
6697 | |||||
6698 | // We know the result type of the call, set it. | ||||
6699 | TheCall->setType(FuncT->getCallResultType(Context)); | ||||
6700 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); | ||||
6701 | |||||
6702 | if (Proto) { | ||||
6703 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, | ||||
6704 | IsExecConfig)) | ||||
6705 | return ExprError(); | ||||
6706 | } else { | ||||
6707 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6707, __PRETTY_FUNCTION__)); | ||||
6708 | |||||
6709 | if (FDecl) { | ||||
6710 | // Check if we have too few/too many template arguments, based | ||||
6711 | // on our knowledge of the function definition. | ||||
6712 | const FunctionDecl *Def = nullptr; | ||||
6713 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { | ||||
6714 | Proto = Def->getType()->getAs<FunctionProtoType>(); | ||||
6715 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) | ||||
6716 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) | ||||
6717 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); | ||||
6718 | } | ||||
6719 | |||||
6720 | // If the function we're calling isn't a function prototype, but we have | ||||
6721 | // a function prototype from a prior declaratiom, use that prototype. | ||||
6722 | if (!FDecl->hasPrototype()) | ||||
6723 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); | ||||
6724 | } | ||||
6725 | |||||
6726 | // Promote the arguments (C99 6.5.2.2p6). | ||||
6727 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6728 | Expr *Arg = Args[i]; | ||||
6729 | |||||
6730 | if (Proto && i < Proto->getNumParams()) { | ||||
6731 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
6732 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); | ||||
6733 | ExprResult ArgE = | ||||
6734 | PerformCopyInitialization(Entity, SourceLocation(), Arg); | ||||
6735 | if (ArgE.isInvalid()) | ||||
6736 | return true; | ||||
6737 | |||||
6738 | Arg = ArgE.getAs<Expr>(); | ||||
6739 | |||||
6740 | } else { | ||||
6741 | ExprResult ArgE = DefaultArgumentPromotion(Arg); | ||||
6742 | |||||
6743 | if (ArgE.isInvalid()) | ||||
6744 | return true; | ||||
6745 | |||||
6746 | Arg = ArgE.getAs<Expr>(); | ||||
6747 | } | ||||
6748 | |||||
6749 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), | ||||
6750 | diag::err_call_incomplete_argument, Arg)) | ||||
6751 | return ExprError(); | ||||
6752 | |||||
6753 | TheCall->setArg(i, Arg); | ||||
6754 | } | ||||
6755 | } | ||||
6756 | |||||
6757 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) | ||||
6758 | if (!Method->isStatic()) | ||||
6759 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) | ||||
6760 | << Fn->getSourceRange()); | ||||
6761 | |||||
6762 | // Check for sentinels | ||||
6763 | if (NDecl) | ||||
6764 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); | ||||
6765 | |||||
6766 | // Warn for unions passing across security boundary (CMSE). | ||||
6767 | if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { | ||||
6768 | for (unsigned i = 0, e = Args.size(); i != e; i++) { | ||||
6769 | if (const auto *RT = | ||||
6770 | dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { | ||||
6771 | if (RT->getDecl()->isOrContainsUnion()) | ||||
6772 | Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) | ||||
6773 | << 0 << i; | ||||
6774 | } | ||||
6775 | } | ||||
6776 | } | ||||
6777 | |||||
6778 | // Do special checking on direct calls to functions. | ||||
6779 | if (FDecl) { | ||||
6780 | if (CheckFunctionCall(FDecl, TheCall, Proto)) | ||||
6781 | return ExprError(); | ||||
6782 | |||||
6783 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); | ||||
6784 | |||||
6785 | if (BuiltinID) | ||||
6786 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); | ||||
6787 | } else if (NDecl) { | ||||
6788 | if (CheckPointerCall(NDecl, TheCall, Proto)) | ||||
6789 | return ExprError(); | ||||
6790 | } else { | ||||
6791 | if (CheckOtherCall(TheCall, Proto)) | ||||
6792 | return ExprError(); | ||||
6793 | } | ||||
6794 | |||||
6795 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); | ||||
6796 | } | ||||
6797 | |||||
6798 | ExprResult | ||||
6799 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, | ||||
6800 | SourceLocation RParenLoc, Expr *InitExpr) { | ||||
6801 | assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast <void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6801, __PRETTY_FUNCTION__)); | ||||
6802 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 6802, __PRETTY_FUNCTION__)); | ||||
6803 | |||||
6804 | TypeSourceInfo *TInfo; | ||||
6805 | QualType literalType = GetTypeFromParser(Ty, &TInfo); | ||||
6806 | if (!TInfo) | ||||
6807 | TInfo = Context.getTrivialTypeSourceInfo(literalType); | ||||
6808 | |||||
6809 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); | ||||
6810 | } | ||||
6811 | |||||
6812 | ExprResult | ||||
6813 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, | ||||
6814 | SourceLocation RParenLoc, Expr *LiteralExpr) { | ||||
6815 | QualType literalType = TInfo->getType(); | ||||
6816 | |||||
6817 | if (literalType->isArrayType()) { | ||||
6818 | if (RequireCompleteSizedType( | ||||
6819 | LParenLoc, Context.getBaseElementType(literalType), | ||||
6820 | diag::err_array_incomplete_or_sizeless_type, | ||||
6821 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
6822 | return ExprError(); | ||||
6823 | if (literalType->isVariableArrayType()) | ||||
6824 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) | ||||
6825 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); | ||||
6826 | } else if (!literalType->isDependentType() && | ||||
6827 | RequireCompleteType(LParenLoc, literalType, | ||||
6828 | diag::err_typecheck_decl_incomplete_type, | ||||
6829 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) | ||||
6830 | return ExprError(); | ||||
6831 | |||||
6832 | InitializedEntity Entity | ||||
6833 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); | ||||
6834 | InitializationKind Kind | ||||
6835 | = InitializationKind::CreateCStyleCast(LParenLoc, | ||||
6836 | SourceRange(LParenLoc, RParenLoc), | ||||
6837 | /*InitList=*/true); | ||||
6838 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); | ||||
6839 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, | ||||
6840 | &literalType); | ||||
6841 | if (Result.isInvalid()) | ||||
6842 | return ExprError(); | ||||
6843 | LiteralExpr = Result.get(); | ||||
6844 | |||||
6845 | bool isFileScope = !CurContext->isFunctionOrMethod(); | ||||
6846 | |||||
6847 | // In C, compound literals are l-values for some reason. | ||||
6848 | // For GCC compatibility, in C++, file-scope array compound literals with | ||||
6849 | // constant initializers are also l-values, and compound literals are | ||||
6850 | // otherwise prvalues. | ||||
6851 | // | ||||
6852 | // (GCC also treats C++ list-initialized file-scope array prvalues with | ||||
6853 | // constant initializers as l-values, but that's non-conforming, so we don't | ||||
6854 | // follow it there.) | ||||
6855 | // | ||||
6856 | // FIXME: It would be better to handle the lvalue cases as materializing and | ||||
6857 | // lifetime-extending a temporary object, but our materialized temporaries | ||||
6858 | // representation only supports lifetime extension from a variable, not "out | ||||
6859 | // of thin air". | ||||
6860 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer | ||||
6861 | // is bound to the result of applying array-to-pointer decay to the compound | ||||
6862 | // literal. | ||||
6863 | // FIXME: GCC supports compound literals of reference type, which should | ||||
6864 | // obviously have a value kind derived from the kind of reference involved. | ||||
6865 | ExprValueKind VK = | ||||
6866 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) | ||||
6867 | ? VK_RValue | ||||
6868 | : VK_LValue; | ||||
6869 | |||||
6870 | if (isFileScope) | ||||
6871 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) | ||||
6872 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { | ||||
6873 | Expr *Init = ILE->getInit(i); | ||||
6874 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); | ||||
6875 | } | ||||
6876 | |||||
6877 | auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, | ||||
6878 | VK, LiteralExpr, isFileScope); | ||||
6879 | if (isFileScope) { | ||||
6880 | if (!LiteralExpr->isTypeDependent() && | ||||
6881 | !LiteralExpr->isValueDependent() && | ||||
6882 | !literalType->isDependentType()) // C99 6.5.2.5p3 | ||||
6883 | if (CheckForConstantInitializer(LiteralExpr, literalType)) | ||||
6884 | return ExprError(); | ||||
6885 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && | ||||
6886 | literalType.getAddressSpace() != LangAS::Default) { | ||||
6887 | // Embedded-C extensions to C99 6.5.2.5: | ||||
6888 | // "If the compound literal occurs inside the body of a function, the | ||||
6889 | // type name shall not be qualified by an address-space qualifier." | ||||
6890 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) | ||||
6891 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); | ||||
6892 | return ExprError(); | ||||
6893 | } | ||||
6894 | |||||
6895 | if (!isFileScope && !getLangOpts().CPlusPlus) { | ||||
6896 | // Compound literals that have automatic storage duration are destroyed at | ||||
6897 | // the end of the scope in C; in C++, they're just temporaries. | ||||
6898 | |||||
6899 | // Emit diagnostics if it is or contains a C union type that is non-trivial | ||||
6900 | // to destruct. | ||||
6901 | if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) | ||||
6902 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
6903 | NTCUC_CompoundLiteral, NTCUK_Destruct); | ||||
6904 | |||||
6905 | // Diagnose jumps that enter or exit the lifetime of the compound literal. | ||||
6906 | if (literalType.isDestructedType()) { | ||||
6907 | Cleanup.setExprNeedsCleanups(true); | ||||
6908 | ExprCleanupObjects.push_back(E); | ||||
6909 | getCurFunction()->setHasBranchProtectedScope(); | ||||
6910 | } | ||||
6911 | } | ||||
6912 | |||||
6913 | if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
6914 | E->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
6915 | checkNonTrivialCUnionInInitializer(E->getInitializer(), | ||||
6916 | E->getInitializer()->getExprLoc()); | ||||
6917 | |||||
6918 | return MaybeBindToTemporary(E); | ||||
6919 | } | ||||
6920 | |||||
6921 | ExprResult | ||||
6922 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
6923 | SourceLocation RBraceLoc) { | ||||
6924 | // Only produce each kind of designated initialization diagnostic once. | ||||
6925 | SourceLocation FirstDesignator; | ||||
6926 | bool DiagnosedArrayDesignator = false; | ||||
6927 | bool DiagnosedNestedDesignator = false; | ||||
6928 | bool DiagnosedMixedDesignator = false; | ||||
6929 | |||||
6930 | // Check that any designated initializers are syntactically valid in the | ||||
6931 | // current language mode. | ||||
6932 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
6933 | if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { | ||||
6934 | if (FirstDesignator.isInvalid()) | ||||
6935 | FirstDesignator = DIE->getBeginLoc(); | ||||
6936 | |||||
6937 | if (!getLangOpts().CPlusPlus) | ||||
6938 | break; | ||||
6939 | |||||
6940 | if (!DiagnosedNestedDesignator && DIE->size() > 1) { | ||||
6941 | DiagnosedNestedDesignator = true; | ||||
6942 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) | ||||
6943 | << DIE->getDesignatorsSourceRange(); | ||||
6944 | } | ||||
6945 | |||||
6946 | for (auto &Desig : DIE->designators()) { | ||||
6947 | if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { | ||||
6948 | DiagnosedArrayDesignator = true; | ||||
6949 | Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) | ||||
6950 | << Desig.getSourceRange(); | ||||
6951 | } | ||||
6952 | } | ||||
6953 | |||||
6954 | if (!DiagnosedMixedDesignator && | ||||
6955 | !isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
6956 | DiagnosedMixedDesignator = true; | ||||
6957 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
6958 | << DIE->getSourceRange(); | ||||
6959 | Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
6960 | << InitArgList[0]->getSourceRange(); | ||||
6961 | } | ||||
6962 | } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && | ||||
6963 | isa<DesignatedInitExpr>(InitArgList[0])) { | ||||
6964 | DiagnosedMixedDesignator = true; | ||||
6965 | auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); | ||||
6966 | Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) | ||||
6967 | << DIE->getSourceRange(); | ||||
6968 | Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) | ||||
6969 | << InitArgList[I]->getSourceRange(); | ||||
6970 | } | ||||
6971 | } | ||||
6972 | |||||
6973 | if (FirstDesignator.isValid()) { | ||||
6974 | // Only diagnose designated initiaization as a C++20 extension if we didn't | ||||
6975 | // already diagnose use of (non-C++20) C99 designator syntax. | ||||
6976 | if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && | ||||
6977 | !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { | ||||
6978 | Diag(FirstDesignator, getLangOpts().CPlusPlus20 | ||||
6979 | ? diag::warn_cxx17_compat_designated_init | ||||
6980 | : diag::ext_cxx_designated_init); | ||||
6981 | } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { | ||||
6982 | Diag(FirstDesignator, diag::ext_designated_init); | ||||
6983 | } | ||||
6984 | } | ||||
6985 | |||||
6986 | return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); | ||||
6987 | } | ||||
6988 | |||||
6989 | ExprResult | ||||
6990 | Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, | ||||
6991 | SourceLocation RBraceLoc) { | ||||
6992 | // Semantic analysis for initializers is done by ActOnDeclarator() and | ||||
6993 | // CheckInitializer() - it requires knowledge of the object being initialized. | ||||
6994 | |||||
6995 | // Immediately handle non-overload placeholders. Overloads can be | ||||
6996 | // resolved contextually, but everything else here can't. | ||||
6997 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { | ||||
6998 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { | ||||
6999 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); | ||||
7000 | |||||
7001 | // Ignore failures; dropping the entire initializer list because | ||||
7002 | // of one failure would be terrible for indexing/etc. | ||||
7003 | if (result.isInvalid()) continue; | ||||
7004 | |||||
7005 | InitArgList[I] = result.get(); | ||||
7006 | } | ||||
7007 | } | ||||
7008 | |||||
7009 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, | ||||
7010 | RBraceLoc); | ||||
7011 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. | ||||
7012 | return E; | ||||
7013 | } | ||||
7014 | |||||
7015 | /// Do an explicit extend of the given block pointer if we're in ARC. | ||||
7016 | void Sema::maybeExtendBlockObject(ExprResult &E) { | ||||
7017 | assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast <void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7017, __PRETTY_FUNCTION__)); | ||||
7018 | assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail ("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7018, __PRETTY_FUNCTION__)); | ||||
7019 | |||||
7020 | // Only do this in an r-value context. | ||||
7021 | if (!getLangOpts().ObjCAutoRefCount) return; | ||||
7022 | |||||
7023 | E = ImplicitCastExpr::Create( | ||||
7024 | Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), | ||||
7025 | /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); | ||||
7026 | Cleanup.setExprNeedsCleanups(true); | ||||
7027 | } | ||||
7028 | |||||
7029 | /// Prepare a conversion of the given expression to an ObjC object | ||||
7030 | /// pointer type. | ||||
7031 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { | ||||
7032 | QualType type = E.get()->getType(); | ||||
7033 | if (type->isObjCObjectPointerType()) { | ||||
7034 | return CK_BitCast; | ||||
7035 | } else if (type->isBlockPointerType()) { | ||||
7036 | maybeExtendBlockObject(E); | ||||
7037 | return CK_BlockPointerToObjCPointerCast; | ||||
7038 | } else { | ||||
7039 | assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail ("type->isPointerType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7039, __PRETTY_FUNCTION__)); | ||||
7040 | return CK_CPointerToObjCPointerCast; | ||||
7041 | } | ||||
7042 | } | ||||
7043 | |||||
7044 | /// Prepares for a scalar cast, performing all the necessary stages | ||||
7045 | /// except the final cast and returning the kind required. | ||||
7046 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { | ||||
7047 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. | ||||
7048 | // Also, callers should have filtered out the invalid cases with | ||||
7049 | // pointers. Everything else should be possible. | ||||
7050 | |||||
7051 | QualType SrcTy = Src.get()->getType(); | ||||
7052 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) | ||||
7053 | return CK_NoOp; | ||||
7054 | |||||
7055 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { | ||||
7056 | case Type::STK_MemberPointer: | ||||
7057 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7057); | ||||
7058 | |||||
7059 | case Type::STK_CPointer: | ||||
7060 | case Type::STK_BlockPointer: | ||||
7061 | case Type::STK_ObjCObjectPointer: | ||||
7062 | switch (DestTy->getScalarTypeKind()) { | ||||
7063 | case Type::STK_CPointer: { | ||||
7064 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); | ||||
7065 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); | ||||
7066 | if (SrcAS != DestAS) | ||||
7067 | return CK_AddressSpaceConversion; | ||||
7068 | if (Context.hasCvrSimilarType(SrcTy, DestTy)) | ||||
7069 | return CK_NoOp; | ||||
7070 | return CK_BitCast; | ||||
7071 | } | ||||
7072 | case Type::STK_BlockPointer: | ||||
7073 | return (SrcKind == Type::STK_BlockPointer | ||||
7074 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); | ||||
7075 | case Type::STK_ObjCObjectPointer: | ||||
7076 | if (SrcKind == Type::STK_ObjCObjectPointer) | ||||
7077 | return CK_BitCast; | ||||
7078 | if (SrcKind == Type::STK_CPointer) | ||||
7079 | return CK_CPointerToObjCPointerCast; | ||||
7080 | maybeExtendBlockObject(Src); | ||||
7081 | return CK_BlockPointerToObjCPointerCast; | ||||
7082 | case Type::STK_Bool: | ||||
7083 | return CK_PointerToBoolean; | ||||
7084 | case Type::STK_Integral: | ||||
7085 | return CK_PointerToIntegral; | ||||
7086 | case Type::STK_Floating: | ||||
7087 | case Type::STK_FloatingComplex: | ||||
7088 | case Type::STK_IntegralComplex: | ||||
7089 | case Type::STK_MemberPointer: | ||||
7090 | case Type::STK_FixedPoint: | ||||
7091 | llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7091); | ||||
7092 | } | ||||
7093 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7093); | ||||
7094 | |||||
7095 | case Type::STK_FixedPoint: | ||||
7096 | switch (DestTy->getScalarTypeKind()) { | ||||
7097 | case Type::STK_FixedPoint: | ||||
7098 | return CK_FixedPointCast; | ||||
7099 | case Type::STK_Bool: | ||||
7100 | return CK_FixedPointToBoolean; | ||||
7101 | case Type::STK_Integral: | ||||
7102 | return CK_FixedPointToIntegral; | ||||
7103 | case Type::STK_Floating: | ||||
7104 | return CK_FixedPointToFloating; | ||||
7105 | case Type::STK_IntegralComplex: | ||||
7106 | case Type::STK_FloatingComplex: | ||||
7107 | Diag(Src.get()->getExprLoc(), | ||||
7108 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7109 | << DestTy; | ||||
7110 | return CK_IntegralCast; | ||||
7111 | case Type::STK_CPointer: | ||||
7112 | case Type::STK_ObjCObjectPointer: | ||||
7113 | case Type::STK_BlockPointer: | ||||
7114 | case Type::STK_MemberPointer: | ||||
7115 | llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7115); | ||||
7116 | } | ||||
7117 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7117); | ||||
7118 | |||||
7119 | case Type::STK_Bool: // casting from bool is like casting from an integer | ||||
7120 | case Type::STK_Integral: | ||||
7121 | switch (DestTy->getScalarTypeKind()) { | ||||
7122 | case Type::STK_CPointer: | ||||
7123 | case Type::STK_ObjCObjectPointer: | ||||
7124 | case Type::STK_BlockPointer: | ||||
7125 | if (Src.get()->isNullPointerConstant(Context, | ||||
7126 | Expr::NPC_ValueDependentIsNull)) | ||||
7127 | return CK_NullToPointer; | ||||
7128 | return CK_IntegralToPointer; | ||||
7129 | case Type::STK_Bool: | ||||
7130 | return CK_IntegralToBoolean; | ||||
7131 | case Type::STK_Integral: | ||||
7132 | return CK_IntegralCast; | ||||
7133 | case Type::STK_Floating: | ||||
7134 | return CK_IntegralToFloating; | ||||
7135 | case Type::STK_IntegralComplex: | ||||
7136 | Src = ImpCastExprToType(Src.get(), | ||||
7137 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7138 | CK_IntegralCast); | ||||
7139 | return CK_IntegralRealToComplex; | ||||
7140 | case Type::STK_FloatingComplex: | ||||
7141 | Src = ImpCastExprToType(Src.get(), | ||||
7142 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7143 | CK_IntegralToFloating); | ||||
7144 | return CK_FloatingRealToComplex; | ||||
7145 | case Type::STK_MemberPointer: | ||||
7146 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7146); | ||||
7147 | case Type::STK_FixedPoint: | ||||
7148 | return CK_IntegralToFixedPoint; | ||||
7149 | } | ||||
7150 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7150); | ||||
7151 | |||||
7152 | case Type::STK_Floating: | ||||
7153 | switch (DestTy->getScalarTypeKind()) { | ||||
7154 | case Type::STK_Floating: | ||||
7155 | return CK_FloatingCast; | ||||
7156 | case Type::STK_Bool: | ||||
7157 | return CK_FloatingToBoolean; | ||||
7158 | case Type::STK_Integral: | ||||
7159 | return CK_FloatingToIntegral; | ||||
7160 | case Type::STK_FloatingComplex: | ||||
7161 | Src = ImpCastExprToType(Src.get(), | ||||
7162 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7163 | CK_FloatingCast); | ||||
7164 | return CK_FloatingRealToComplex; | ||||
7165 | case Type::STK_IntegralComplex: | ||||
7166 | Src = ImpCastExprToType(Src.get(), | ||||
7167 | DestTy->castAs<ComplexType>()->getElementType(), | ||||
7168 | CK_FloatingToIntegral); | ||||
7169 | return CK_IntegralRealToComplex; | ||||
7170 | case Type::STK_CPointer: | ||||
7171 | case Type::STK_ObjCObjectPointer: | ||||
7172 | case Type::STK_BlockPointer: | ||||
7173 | llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7173); | ||||
7174 | case Type::STK_MemberPointer: | ||||
7175 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7175); | ||||
7176 | case Type::STK_FixedPoint: | ||||
7177 | return CK_FloatingToFixedPoint; | ||||
7178 | } | ||||
7179 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7179); | ||||
7180 | |||||
7181 | case Type::STK_FloatingComplex: | ||||
7182 | switch (DestTy->getScalarTypeKind()) { | ||||
7183 | case Type::STK_FloatingComplex: | ||||
7184 | return CK_FloatingComplexCast; | ||||
7185 | case Type::STK_IntegralComplex: | ||||
7186 | return CK_FloatingComplexToIntegralComplex; | ||||
7187 | case Type::STK_Floating: { | ||||
7188 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7189 | if (Context.hasSameType(ET, DestTy)) | ||||
7190 | return CK_FloatingComplexToReal; | ||||
7191 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); | ||||
7192 | return CK_FloatingCast; | ||||
7193 | } | ||||
7194 | case Type::STK_Bool: | ||||
7195 | return CK_FloatingComplexToBoolean; | ||||
7196 | case Type::STK_Integral: | ||||
7197 | Src = ImpCastExprToType(Src.get(), | ||||
7198 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7199 | CK_FloatingComplexToReal); | ||||
7200 | return CK_FloatingToIntegral; | ||||
7201 | case Type::STK_CPointer: | ||||
7202 | case Type::STK_ObjCObjectPointer: | ||||
7203 | case Type::STK_BlockPointer: | ||||
7204 | llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7204); | ||||
7205 | case Type::STK_MemberPointer: | ||||
7206 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7206); | ||||
7207 | case Type::STK_FixedPoint: | ||||
7208 | Diag(Src.get()->getExprLoc(), | ||||
7209 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7210 | << SrcTy; | ||||
7211 | return CK_IntegralCast; | ||||
7212 | } | ||||
7213 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7213); | ||||
7214 | |||||
7215 | case Type::STK_IntegralComplex: | ||||
7216 | switch (DestTy->getScalarTypeKind()) { | ||||
7217 | case Type::STK_FloatingComplex: | ||||
7218 | return CK_IntegralComplexToFloatingComplex; | ||||
7219 | case Type::STK_IntegralComplex: | ||||
7220 | return CK_IntegralComplexCast; | ||||
7221 | case Type::STK_Integral: { | ||||
7222 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); | ||||
7223 | if (Context.hasSameType(ET, DestTy)) | ||||
7224 | return CK_IntegralComplexToReal; | ||||
7225 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); | ||||
7226 | return CK_IntegralCast; | ||||
7227 | } | ||||
7228 | case Type::STK_Bool: | ||||
7229 | return CK_IntegralComplexToBoolean; | ||||
7230 | case Type::STK_Floating: | ||||
7231 | Src = ImpCastExprToType(Src.get(), | ||||
7232 | SrcTy->castAs<ComplexType>()->getElementType(), | ||||
7233 | CK_IntegralComplexToReal); | ||||
7234 | return CK_IntegralToFloating; | ||||
7235 | case Type::STK_CPointer: | ||||
7236 | case Type::STK_ObjCObjectPointer: | ||||
7237 | case Type::STK_BlockPointer: | ||||
7238 | llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7238); | ||||
7239 | case Type::STK_MemberPointer: | ||||
7240 | llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7240); | ||||
7241 | case Type::STK_FixedPoint: | ||||
7242 | Diag(Src.get()->getExprLoc(), | ||||
7243 | diag::err_unimplemented_conversion_with_fixed_point_type) | ||||
7244 | << SrcTy; | ||||
7245 | return CK_IntegralCast; | ||||
7246 | } | ||||
7247 | llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7247); | ||||
7248 | } | ||||
7249 | |||||
7250 | llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7250); | ||||
7251 | } | ||||
7252 | |||||
7253 | static bool breakDownVectorType(QualType type, uint64_t &len, | ||||
7254 | QualType &eltType) { | ||||
7255 | // Vectors are simple. | ||||
7256 | if (const VectorType *vecType = type->getAs<VectorType>()) { | ||||
7257 | len = vecType->getNumElements(); | ||||
7258 | eltType = vecType->getElementType(); | ||||
7259 | assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) : __assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7259, __PRETTY_FUNCTION__)); | ||||
7260 | return true; | ||||
7261 | } | ||||
7262 | |||||
7263 | // We allow lax conversion to and from non-vector types, but only if | ||||
7264 | // they're real types (i.e. non-complex, non-pointer scalar types). | ||||
7265 | if (!type->isRealType()) return false; | ||||
7266 | |||||
7267 | len = 1; | ||||
7268 | eltType = type; | ||||
7269 | return true; | ||||
7270 | } | ||||
7271 | |||||
7272 | /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the | ||||
7273 | /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) | ||||
7274 | /// allowed? | ||||
7275 | /// | ||||
7276 | /// This will also return false if the two given types do not make sense from | ||||
7277 | /// the perspective of SVE bitcasts. | ||||
7278 | bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { | ||||
7279 | assert(srcTy->isVectorType() || destTy->isVectorType())((srcTy->isVectorType() || destTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("srcTy->isVectorType() || destTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7279, __PRETTY_FUNCTION__)); | ||||
7280 | |||||
7281 | auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { | ||||
7282 | if (!FirstType->isSizelessBuiltinType()) | ||||
7283 | return false; | ||||
7284 | |||||
7285 | const auto *VecTy = SecondType->getAs<VectorType>(); | ||||
7286 | return VecTy && | ||||
7287 | VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; | ||||
7288 | }; | ||||
7289 | |||||
7290 | return ValidScalableConversion(srcTy, destTy) || | ||||
7291 | ValidScalableConversion(destTy, srcTy); | ||||
7292 | } | ||||
7293 | |||||
7294 | /// Are the two types lax-compatible vector types? That is, given | ||||
7295 | /// that one of them is a vector, do they have equal storage sizes, | ||||
7296 | /// where the storage size is the number of elements times the element | ||||
7297 | /// size? | ||||
7298 | /// | ||||
7299 | /// This will also return false if either of the types is neither a | ||||
7300 | /// vector nor a real type. | ||||
7301 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { | ||||
7302 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7302, __PRETTY_FUNCTION__)); | ||||
7303 | |||||
7304 | // Disallow lax conversions between scalars and ExtVectors (these | ||||
7305 | // conversions are allowed for other vector types because common headers | ||||
7306 | // depend on them). Most scalar OP ExtVector cases are handled by the | ||||
7307 | // splat path anyway, which does what we want (convert, not bitcast). | ||||
7308 | // What this rules out for ExtVectors is crazy things like char4*float. | ||||
7309 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; | ||||
7310 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; | ||||
7311 | |||||
7312 | uint64_t srcLen, destLen; | ||||
7313 | QualType srcEltTy, destEltTy; | ||||
7314 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; | ||||
7315 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; | ||||
7316 | |||||
7317 | // ASTContext::getTypeSize will return the size rounded up to a | ||||
7318 | // power of 2, so instead of using that, we need to use the raw | ||||
7319 | // element size multiplied by the element count. | ||||
7320 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); | ||||
7321 | uint64_t destEltSize = Context.getTypeSize(destEltTy); | ||||
7322 | |||||
7323 | return (srcLen * srcEltSize == destLen * destEltSize); | ||||
7324 | } | ||||
7325 | |||||
7326 | /// Is this a legal conversion between two types, one of which is | ||||
7327 | /// known to be a vector type? | ||||
7328 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { | ||||
7329 | assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast <void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7329, __PRETTY_FUNCTION__)); | ||||
7330 | |||||
7331 | switch (Context.getLangOpts().getLaxVectorConversions()) { | ||||
7332 | case LangOptions::LaxVectorConversionKind::None: | ||||
7333 | return false; | ||||
7334 | |||||
7335 | case LangOptions::LaxVectorConversionKind::Integer: | ||||
7336 | if (!srcTy->isIntegralOrEnumerationType()) { | ||||
7337 | auto *Vec = srcTy->getAs<VectorType>(); | ||||
7338 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7339 | return false; | ||||
7340 | } | ||||
7341 | if (!destTy->isIntegralOrEnumerationType()) { | ||||
7342 | auto *Vec = destTy->getAs<VectorType>(); | ||||
7343 | if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) | ||||
7344 | return false; | ||||
7345 | } | ||||
7346 | // OK, integer (vector) -> integer (vector) bitcast. | ||||
7347 | break; | ||||
7348 | |||||
7349 | case LangOptions::LaxVectorConversionKind::All: | ||||
7350 | break; | ||||
7351 | } | ||||
7352 | |||||
7353 | return areLaxCompatibleVectorTypes(srcTy, destTy); | ||||
7354 | } | ||||
7355 | |||||
7356 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | ||||
7357 | CastKind &Kind) { | ||||
7358 | assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!" ) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7358, __PRETTY_FUNCTION__)); | ||||
7359 | |||||
7360 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { | ||||
7361 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) | ||||
7362 | return Diag(R.getBegin(), | ||||
7363 | Ty->isVectorType() ? | ||||
7364 | diag::err_invalid_conversion_between_vectors : | ||||
7365 | diag::err_invalid_conversion_between_vector_and_integer) | ||||
7366 | << VectorTy << Ty << R; | ||||
7367 | } else | ||||
7368 | return Diag(R.getBegin(), | ||||
7369 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7370 | << VectorTy << Ty << R; | ||||
7371 | |||||
7372 | Kind = CK_BitCast; | ||||
7373 | return false; | ||||
7374 | } | ||||
7375 | |||||
7376 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { | ||||
7377 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); | ||||
7378 | |||||
7379 | if (DestElemTy == SplattedExpr->getType()) | ||||
7380 | return SplattedExpr; | ||||
7381 | |||||
7382 | assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7383, __PRETTY_FUNCTION__)) | ||||
7383 | DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7383, __PRETTY_FUNCTION__)); | ||||
7384 | |||||
7385 | CastKind CK; | ||||
7386 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { | ||||
7387 | // OpenCL requires that we convert `true` boolean expressions to -1, but | ||||
7388 | // only when splatting vectors. | ||||
7389 | if (DestElemTy->isFloatingType()) { | ||||
7390 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast | ||||
7391 | // in two steps: boolean to signed integral, then to floating. | ||||
7392 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, | ||||
7393 | CK_BooleanToSignedIntegral); | ||||
7394 | SplattedExpr = CastExprRes.get(); | ||||
7395 | CK = CK_IntegralToFloating; | ||||
7396 | } else { | ||||
7397 | CK = CK_BooleanToSignedIntegral; | ||||
7398 | } | ||||
7399 | } else { | ||||
7400 | ExprResult CastExprRes = SplattedExpr; | ||||
7401 | CK = PrepareScalarCast(CastExprRes, DestElemTy); | ||||
7402 | if (CastExprRes.isInvalid()) | ||||
7403 | return ExprError(); | ||||
7404 | SplattedExpr = CastExprRes.get(); | ||||
7405 | } | ||||
7406 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); | ||||
7407 | } | ||||
7408 | |||||
7409 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, | ||||
7410 | Expr *CastExpr, CastKind &Kind) { | ||||
7411 | assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!" ) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7411, __PRETTY_FUNCTION__)); | ||||
7412 | |||||
7413 | QualType SrcTy = CastExpr->getType(); | ||||
7414 | |||||
7415 | // If SrcTy is a VectorType, the total size must match to explicitly cast to | ||||
7416 | // an ExtVectorType. | ||||
7417 | // In OpenCL, casts between vectors of different types are not allowed. | ||||
7418 | // (See OpenCL 6.2). | ||||
7419 | if (SrcTy->isVectorType()) { | ||||
7420 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || | ||||
7421 | (getLangOpts().OpenCL && | ||||
7422 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { | ||||
7423 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) | ||||
7424 | << DestTy << SrcTy << R; | ||||
7425 | return ExprError(); | ||||
7426 | } | ||||
7427 | Kind = CK_BitCast; | ||||
7428 | return CastExpr; | ||||
7429 | } | ||||
7430 | |||||
7431 | // All non-pointer scalars can be cast to ExtVector type. The appropriate | ||||
7432 | // conversion will take place first from scalar to elt type, and then | ||||
7433 | // splat from elt type to vector. | ||||
7434 | if (SrcTy->isPointerType()) | ||||
7435 | return Diag(R.getBegin(), | ||||
7436 | diag::err_invalid_conversion_between_vector_and_scalar) | ||||
7437 | << DestTy << SrcTy << R; | ||||
7438 | |||||
7439 | Kind = CK_VectorSplat; | ||||
7440 | return prepareVectorSplat(DestTy, CastExpr); | ||||
7441 | } | ||||
7442 | |||||
7443 | ExprResult | ||||
7444 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | ||||
7445 | Declarator &D, ParsedType &Ty, | ||||
7446 | SourceLocation RParenLoc, Expr *CastExpr) { | ||||
7447 | assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7448, __PRETTY_FUNCTION__)) | ||||
7448 | "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr") ? static_cast<void > (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7448, __PRETTY_FUNCTION__)); | ||||
7449 | |||||
7450 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); | ||||
7451 | if (D.isInvalidType()) | ||||
7452 | return ExprError(); | ||||
7453 | |||||
7454 | if (getLangOpts().CPlusPlus) { | ||||
7455 | // Check that there are no default arguments (C++ only). | ||||
7456 | CheckExtraCXXDefaultArguments(D); | ||||
7457 | } else { | ||||
7458 | // Make sure any TypoExprs have been dealt with. | ||||
7459 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); | ||||
7460 | if (!Res.isUsable()) | ||||
7461 | return ExprError(); | ||||
7462 | CastExpr = Res.get(); | ||||
7463 | } | ||||
7464 | |||||
7465 | checkUnusedDeclAttributes(D); | ||||
7466 | |||||
7467 | QualType castType = castTInfo->getType(); | ||||
7468 | Ty = CreateParsedType(castType, castTInfo); | ||||
7469 | |||||
7470 | bool isVectorLiteral = false; | ||||
7471 | |||||
7472 | // Check for an altivec or OpenCL literal, | ||||
7473 | // i.e. all the elements are integer constants. | ||||
7474 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); | ||||
7475 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); | ||||
7476 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) | ||||
7477 | && castType->isVectorType() && (PE || PLE)) { | ||||
7478 | if (PLE && PLE->getNumExprs() == 0) { | ||||
7479 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); | ||||
7480 | return ExprError(); | ||||
7481 | } | ||||
7482 | if (PE || PLE->getNumExprs() == 1) { | ||||
7483 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); | ||||
7484 | if (!E->isTypeDependent() && !E->getType()->isVectorType()) | ||||
7485 | isVectorLiteral = true; | ||||
7486 | } | ||||
7487 | else | ||||
7488 | isVectorLiteral = true; | ||||
7489 | } | ||||
7490 | |||||
7491 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' | ||||
7492 | // then handle it as such. | ||||
7493 | if (isVectorLiteral) | ||||
7494 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); | ||||
7495 | |||||
7496 | // If the Expr being casted is a ParenListExpr, handle it specially. | ||||
7497 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a | ||||
7498 | // sequence of BinOp comma operators. | ||||
7499 | if (isa<ParenListExpr>(CastExpr)) { | ||||
7500 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); | ||||
7501 | if (Result.isInvalid()) return ExprError(); | ||||
7502 | CastExpr = Result.get(); | ||||
7503 | } | ||||
7504 | |||||
7505 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && | ||||
7506 | !getSourceManager().isInSystemMacro(LParenLoc)) | ||||
7507 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); | ||||
7508 | |||||
7509 | CheckTollFreeBridgeCast(castType, CastExpr); | ||||
7510 | |||||
7511 | CheckObjCBridgeRelatedCast(castType, CastExpr); | ||||
7512 | |||||
7513 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); | ||||
7514 | |||||
7515 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); | ||||
7516 | } | ||||
7517 | |||||
7518 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, | ||||
7519 | SourceLocation RParenLoc, Expr *E, | ||||
7520 | TypeSourceInfo *TInfo) { | ||||
7521 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7522, __PRETTY_FUNCTION__)) | ||||
7522 | "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && "Expected paren or paren list expression") ? static_cast< void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7522, __PRETTY_FUNCTION__)); | ||||
7523 | |||||
7524 | Expr **exprs; | ||||
7525 | unsigned numExprs; | ||||
7526 | Expr *subExpr; | ||||
7527 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; | ||||
7528 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { | ||||
7529 | LiteralLParenLoc = PE->getLParenLoc(); | ||||
7530 | LiteralRParenLoc = PE->getRParenLoc(); | ||||
7531 | exprs = PE->getExprs(); | ||||
7532 | numExprs = PE->getNumExprs(); | ||||
7533 | } else { // isa<ParenExpr> by assertion at function entrance | ||||
7534 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); | ||||
7535 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); | ||||
7536 | subExpr = cast<ParenExpr>(E)->getSubExpr(); | ||||
7537 | exprs = &subExpr; | ||||
7538 | numExprs = 1; | ||||
7539 | } | ||||
7540 | |||||
7541 | QualType Ty = TInfo->getType(); | ||||
7542 | assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast <void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 7542, __PRETTY_FUNCTION__)); | ||||
7543 | |||||
7544 | SmallVector<Expr *, 8> initExprs; | ||||
7545 | const VectorType *VTy = Ty->castAs<VectorType>(); | ||||
7546 | unsigned numElems = VTy->getNumElements(); | ||||
7547 | |||||
7548 | // '(...)' form of vector initialization in AltiVec: the number of | ||||
7549 | // initializers must be one or must match the size of the vector. | ||||
7550 | // If a single value is specified in the initializer then it will be | ||||
7551 | // replicated to all the components of the vector | ||||
7552 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { | ||||
7553 | // The number of initializers must be one or must match the size of the | ||||
7554 | // vector. If a single value is specified in the initializer then it will | ||||
7555 | // be replicated to all the components of the vector | ||||
7556 | if (numExprs == 1) { | ||||
7557 | QualType ElemTy = VTy->getElementType(); | ||||
7558 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7559 | if (Literal.isInvalid()) | ||||
7560 | return ExprError(); | ||||
7561 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7562 | PrepareScalarCast(Literal, ElemTy)); | ||||
7563 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7564 | } | ||||
7565 | else if (numExprs < numElems) { | ||||
7566 | Diag(E->getExprLoc(), | ||||
7567 | diag::err_incorrect_number_of_vector_initializers); | ||||
7568 | return ExprError(); | ||||
7569 | } | ||||
7570 | else | ||||
7571 | initExprs.append(exprs, exprs + numExprs); | ||||
7572 | } | ||||
7573 | else { | ||||
7574 | // For OpenCL, when the number of initializers is a single value, | ||||
7575 | // it will be replicated to all components of the vector. | ||||
7576 | if (getLangOpts().OpenCL && | ||||
7577 | VTy->getVectorKind() == VectorType::GenericVector && | ||||
7578 | numExprs == 1) { | ||||
7579 | QualType ElemTy = VTy->getElementType(); | ||||
7580 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); | ||||
7581 | if (Literal.isInvalid()) | ||||
7582 | return ExprError(); | ||||
7583 | Literal = ImpCastExprToType(Literal.get(), ElemTy, | ||||
7584 | PrepareScalarCast(Literal, ElemTy)); | ||||
7585 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); | ||||
7586 | } | ||||
7587 | |||||
7588 | initExprs.append(exprs, exprs + numExprs); | ||||
7589 | } | ||||
7590 | // FIXME: This means that pretty-printing the final AST will produce curly | ||||
7591 | // braces instead of the original commas. | ||||
7592 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, | ||||
7593 | initExprs, LiteralRParenLoc); | ||||
7594 | initE->setType(Ty); | ||||
7595 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); | ||||
7596 | } | ||||
7597 | |||||
7598 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn | ||||
7599 | /// the ParenListExpr into a sequence of comma binary operators. | ||||
7600 | ExprResult | ||||
7601 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { | ||||
7602 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); | ||||
7603 | if (!E) | ||||
7604 | return OrigExpr; | ||||
7605 | |||||
7606 | ExprResult Result(E->getExpr(0)); | ||||
7607 | |||||
7608 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) | ||||
7609 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), | ||||
7610 | E->getExpr(i)); | ||||
7611 | |||||
7612 | if (Result.isInvalid()) return ExprError(); | ||||
7613 | |||||
7614 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); | ||||
7615 | } | ||||
7616 | |||||
7617 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, | ||||
7618 | SourceLocation R, | ||||
7619 | MultiExprArg Val) { | ||||
7620 | return ParenListExpr::Create(Context, L, Val, R); | ||||
7621 | } | ||||
7622 | |||||
7623 | /// Emit a specialized diagnostic when one expression is a null pointer | ||||
7624 | /// constant and the other is not a pointer. Returns true if a diagnostic is | ||||
7625 | /// emitted. | ||||
7626 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | ||||
7627 | SourceLocation QuestionLoc) { | ||||
7628 | Expr *NullExpr = LHSExpr; | ||||
7629 | Expr *NonPointerExpr = RHSExpr; | ||||
7630 | Expr::NullPointerConstantKind NullKind = | ||||
7631 | NullExpr->isNullPointerConstant(Context, | ||||
7632 | Expr::NPC_ValueDependentIsNotNull); | ||||
7633 | |||||
7634 | if (NullKind == Expr::NPCK_NotNull) { | ||||
7635 | NullExpr = RHSExpr; | ||||
7636 | NonPointerExpr = LHSExpr; | ||||
7637 | NullKind = | ||||
7638 | NullExpr->isNullPointerConstant(Context, | ||||
7639 | Expr::NPC_ValueDependentIsNotNull); | ||||
7640 | } | ||||
7641 | |||||
7642 | if (NullKind == Expr::NPCK_NotNull) | ||||
7643 | return false; | ||||
7644 | |||||
7645 | if (NullKind == Expr::NPCK_ZeroExpression) | ||||
7646 | return false; | ||||
7647 | |||||
7648 | if (NullKind == Expr::NPCK_ZeroLiteral) { | ||||
7649 | // In this case, check to make sure that we got here from a "NULL" | ||||
7650 | // string in the source code. | ||||
7651 | NullExpr = NullExpr->IgnoreParenImpCasts(); | ||||
7652 | SourceLocation loc = NullExpr->getExprLoc(); | ||||
7653 | if (!findMacroSpelling(loc, "NULL")) | ||||
7654 | return false; | ||||
7655 | } | ||||
7656 | |||||
7657 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); | ||||
7658 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) | ||||
7659 | << NonPointerExpr->getType() << DiagType | ||||
7660 | << NonPointerExpr->getSourceRange(); | ||||
7661 | return true; | ||||
7662 | } | ||||
7663 | |||||
7664 | /// Return false if the condition expression is valid, true otherwise. | ||||
7665 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { | ||||
7666 | QualType CondTy = Cond->getType(); | ||||
7667 | |||||
7668 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. | ||||
7669 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { | ||||
7670 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
7671 | << CondTy << Cond->getSourceRange(); | ||||
7672 | return true; | ||||
7673 | } | ||||
7674 | |||||
7675 | // C99 6.5.15p2 | ||||
7676 | if (CondTy->isScalarType()) return false; | ||||
7677 | |||||
7678 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) | ||||
7679 | << CondTy << Cond->getSourceRange(); | ||||
7680 | return true; | ||||
7681 | } | ||||
7682 | |||||
7683 | /// Handle when one or both operands are void type. | ||||
7684 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, | ||||
7685 | ExprResult &RHS) { | ||||
7686 | Expr *LHSExpr = LHS.get(); | ||||
7687 | Expr *RHSExpr = RHS.get(); | ||||
7688 | |||||
7689 | if (!LHSExpr->getType()->isVoidType()) | ||||
7690 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7691 | << RHSExpr->getSourceRange(); | ||||
7692 | if (!RHSExpr->getType()->isVoidType()) | ||||
7693 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) | ||||
7694 | << LHSExpr->getSourceRange(); | ||||
7695 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7696 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); | ||||
7697 | return S.Context.VoidTy; | ||||
7698 | } | ||||
7699 | |||||
7700 | /// Return false if the NullExpr can be promoted to PointerTy, | ||||
7701 | /// true otherwise. | ||||
7702 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, | ||||
7703 | QualType PointerTy) { | ||||
7704 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || | ||||
7705 | !NullExpr.get()->isNullPointerConstant(S.Context, | ||||
7706 | Expr::NPC_ValueDependentIsNull)) | ||||
7707 | return true; | ||||
7708 | |||||
7709 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); | ||||
7710 | return false; | ||||
7711 | } | ||||
7712 | |||||
7713 | /// Checks compatibility between two pointers and return the resulting | ||||
7714 | /// type. | ||||
7715 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, | ||||
7716 | ExprResult &RHS, | ||||
7717 | SourceLocation Loc) { | ||||
7718 | QualType LHSTy = LHS.get()->getType(); | ||||
7719 | QualType RHSTy = RHS.get()->getType(); | ||||
7720 | |||||
7721 | if (S.Context.hasSameType(LHSTy, RHSTy)) { | ||||
7722 | // Two identical pointers types are always compatible. | ||||
7723 | return LHSTy; | ||||
7724 | } | ||||
7725 | |||||
7726 | QualType lhptee, rhptee; | ||||
7727 | |||||
7728 | // Get the pointee types. | ||||
7729 | bool IsBlockPointer = false; | ||||
7730 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { | ||||
7731 | lhptee = LHSBTy->getPointeeType(); | ||||
7732 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); | ||||
7733 | IsBlockPointer = true; | ||||
7734 | } else { | ||||
7735 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7736 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7737 | } | ||||
7738 | |||||
7739 | // C99 6.5.15p6: If both operands are pointers to compatible types or to | ||||
7740 | // differently qualified versions of compatible types, the result type is | ||||
7741 | // a pointer to an appropriately qualified version of the composite | ||||
7742 | // type. | ||||
7743 | |||||
7744 | // Only CVR-qualifiers exist in the standard, and the differently-qualified | ||||
7745 | // clause doesn't make sense for our extensions. E.g. address space 2 should | ||||
7746 | // be incompatible with address space 3: they may live on different devices or | ||||
7747 | // anything. | ||||
7748 | Qualifiers lhQual = lhptee.getQualifiers(); | ||||
7749 | Qualifiers rhQual = rhptee.getQualifiers(); | ||||
7750 | |||||
7751 | LangAS ResultAddrSpace = LangAS::Default; | ||||
7752 | LangAS LAddrSpace = lhQual.getAddressSpace(); | ||||
7753 | LangAS RAddrSpace = rhQual.getAddressSpace(); | ||||
7754 | |||||
7755 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address | ||||
7756 | // spaces is disallowed. | ||||
7757 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) | ||||
7758 | ResultAddrSpace = LAddrSpace; | ||||
7759 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) | ||||
7760 | ResultAddrSpace = RAddrSpace; | ||||
7761 | else { | ||||
7762 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
7763 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() | ||||
7764 | << RHS.get()->getSourceRange(); | ||||
7765 | return QualType(); | ||||
7766 | } | ||||
7767 | |||||
7768 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); | ||||
7769 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; | ||||
7770 | lhQual.removeCVRQualifiers(); | ||||
7771 | rhQual.removeCVRQualifiers(); | ||||
7772 | |||||
7773 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers | ||||
7774 | // (C99 6.7.3) for address spaces. We assume that the check should behave in | ||||
7775 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two | ||||
7776 | // qual types are compatible iff | ||||
7777 | // * corresponded types are compatible | ||||
7778 | // * CVR qualifiers are equal | ||||
7779 | // * address spaces are equal | ||||
7780 | // Thus for conditional operator we merge CVR and address space unqualified | ||||
7781 | // pointees and if there is a composite type we return a pointer to it with | ||||
7782 | // merged qualifiers. | ||||
7783 | LHSCastKind = | ||||
7784 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
7785 | RHSCastKind = | ||||
7786 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; | ||||
7787 | lhQual.removeAddressSpace(); | ||||
7788 | rhQual.removeAddressSpace(); | ||||
7789 | |||||
7790 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); | ||||
7791 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); | ||||
7792 | |||||
7793 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); | ||||
7794 | |||||
7795 | if (CompositeTy.isNull()) { | ||||
7796 | // In this situation, we assume void* type. No especially good | ||||
7797 | // reason, but this is what gcc does, and we do have to pick | ||||
7798 | // to get a consistent AST. | ||||
7799 | QualType incompatTy; | ||||
7800 | incompatTy = S.Context.getPointerType( | ||||
7801 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); | ||||
7802 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); | ||||
7803 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); | ||||
7804 | |||||
7805 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room | ||||
7806 | // for casts between types with incompatible address space qualifiers. | ||||
7807 | // For the following code the compiler produces casts between global and | ||||
7808 | // local address spaces of the corresponded innermost pointees: | ||||
7809 | // local int *global *a; | ||||
7810 | // global int *global *b; | ||||
7811 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. | ||||
7812 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) | ||||
7813 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
7814 | << RHS.get()->getSourceRange(); | ||||
7815 | |||||
7816 | return incompatTy; | ||||
7817 | } | ||||
7818 | |||||
7819 | // The pointer types are compatible. | ||||
7820 | // In case of OpenCL ResultTy should have the address space qualifier | ||||
7821 | // which is a superset of address spaces of both the 2nd and the 3rd | ||||
7822 | // operands of the conditional operator. | ||||
7823 | QualType ResultTy = [&, ResultAddrSpace]() { | ||||
7824 | if (S.getLangOpts().OpenCL) { | ||||
7825 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); | ||||
7826 | CompositeQuals.setAddressSpace(ResultAddrSpace); | ||||
7827 | return S.Context | ||||
7828 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) | ||||
7829 | .withCVRQualifiers(MergedCVRQual); | ||||
7830 | } | ||||
7831 | return CompositeTy.withCVRQualifiers(MergedCVRQual); | ||||
7832 | }(); | ||||
7833 | if (IsBlockPointer) | ||||
7834 | ResultTy = S.Context.getBlockPointerType(ResultTy); | ||||
7835 | else | ||||
7836 | ResultTy = S.Context.getPointerType(ResultTy); | ||||
7837 | |||||
7838 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); | ||||
7839 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); | ||||
7840 | return ResultTy; | ||||
7841 | } | ||||
7842 | |||||
7843 | /// Return the resulting type when the operands are both block pointers. | ||||
7844 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, | ||||
7845 | ExprResult &LHS, | ||||
7846 | ExprResult &RHS, | ||||
7847 | SourceLocation Loc) { | ||||
7848 | QualType LHSTy = LHS.get()->getType(); | ||||
7849 | QualType RHSTy = RHS.get()->getType(); | ||||
7850 | |||||
7851 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { | ||||
7852 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { | ||||
7853 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); | ||||
7854 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
7855 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
7856 | return destType; | ||||
7857 | } | ||||
7858 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) | ||||
7859 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
7860 | << RHS.get()->getSourceRange(); | ||||
7861 | return QualType(); | ||||
7862 | } | ||||
7863 | |||||
7864 | // We have 2 block pointer types. | ||||
7865 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
7866 | } | ||||
7867 | |||||
7868 | /// Return the resulting type when the operands are both pointers. | ||||
7869 | static QualType | ||||
7870 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, | ||||
7871 | ExprResult &RHS, | ||||
7872 | SourceLocation Loc) { | ||||
7873 | // get the pointer types | ||||
7874 | QualType LHSTy = LHS.get()->getType(); | ||||
7875 | QualType RHSTy = RHS.get()->getType(); | ||||
7876 | |||||
7877 | // get the "pointed to" types | ||||
7878 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7879 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
7880 | |||||
7881 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) | ||||
7882 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { | ||||
7883 | // Figure out necessary qualifiers (C99 6.5.15p6) | ||||
7884 | QualType destPointee | ||||
7885 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
7886 | QualType destType = S.Context.getPointerType(destPointee); | ||||
7887 | // Add qualifiers if necessary. | ||||
7888 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
7889 | // Promote to void*. | ||||
7890 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
7891 | return destType; | ||||
7892 | } | ||||
7893 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { | ||||
7894 | QualType destPointee | ||||
7895 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
7896 | QualType destType = S.Context.getPointerType(destPointee); | ||||
7897 | // Add qualifiers if necessary. | ||||
7898 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
7899 | // Promote to void*. | ||||
7900 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
7901 | return destType; | ||||
7902 | } | ||||
7903 | |||||
7904 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); | ||||
7905 | } | ||||
7906 | |||||
7907 | /// Return false if the first expression is not an integer and the second | ||||
7908 | /// expression is not a pointer, true otherwise. | ||||
7909 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, | ||||
7910 | Expr* PointerExpr, SourceLocation Loc, | ||||
7911 | bool IsIntFirstExpr) { | ||||
7912 | if (!PointerExpr->getType()->isPointerType() || | ||||
7913 | !Int.get()->getType()->isIntegerType()) | ||||
7914 | return false; | ||||
7915 | |||||
7916 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; | ||||
7917 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); | ||||
7918 | |||||
7919 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) | ||||
7920 | << Expr1->getType() << Expr2->getType() | ||||
7921 | << Expr1->getSourceRange() << Expr2->getSourceRange(); | ||||
7922 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), | ||||
7923 | CK_IntegralToPointer); | ||||
7924 | return true; | ||||
7925 | } | ||||
7926 | |||||
7927 | /// Simple conversion between integer and floating point types. | ||||
7928 | /// | ||||
7929 | /// Used when handling the OpenCL conditional operator where the | ||||
7930 | /// condition is a vector while the other operands are scalar. | ||||
7931 | /// | ||||
7932 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar | ||||
7933 | /// types are either integer or floating type. Between the two | ||||
7934 | /// operands, the type with the higher rank is defined as the "result | ||||
7935 | /// type". The other operand needs to be promoted to the same type. No | ||||
7936 | /// other type promotion is allowed. We cannot use | ||||
7937 | /// UsualArithmeticConversions() for this purpose, since it always | ||||
7938 | /// promotes promotable types. | ||||
7939 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, | ||||
7940 | ExprResult &RHS, | ||||
7941 | SourceLocation QuestionLoc) { | ||||
7942 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
7943 | if (LHS.isInvalid()) | ||||
7944 | return QualType(); | ||||
7945 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
7946 | if (RHS.isInvalid()) | ||||
7947 | return QualType(); | ||||
7948 | |||||
7949 | // For conversion purposes, we ignore any qualifiers. | ||||
7950 | // For example, "const float" and "float" are equivalent. | ||||
7951 | QualType LHSType = | ||||
7952 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); | ||||
7953 | QualType RHSType = | ||||
7954 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); | ||||
7955 | |||||
7956 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { | ||||
7957 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
7958 | << LHSType << LHS.get()->getSourceRange(); | ||||
7959 | return QualType(); | ||||
7960 | } | ||||
7961 | |||||
7962 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { | ||||
7963 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) | ||||
7964 | << RHSType << RHS.get()->getSourceRange(); | ||||
7965 | return QualType(); | ||||
7966 | } | ||||
7967 | |||||
7968 | // If both types are identical, no conversion is needed. | ||||
7969 | if (LHSType == RHSType) | ||||
7970 | return LHSType; | ||||
7971 | |||||
7972 | // Now handle "real" floating types (i.e. float, double, long double). | ||||
7973 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) | ||||
7974 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, | ||||
7975 | /*IsCompAssign = */ false); | ||||
7976 | |||||
7977 | // Finally, we have two differing integer types. | ||||
7978 | return handleIntegerConversion<doIntegralCast, doIntegralCast> | ||||
7979 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); | ||||
7980 | } | ||||
7981 | |||||
7982 | /// Convert scalar operands to a vector that matches the | ||||
7983 | /// condition in length. | ||||
7984 | /// | ||||
7985 | /// Used when handling the OpenCL conditional operator where the | ||||
7986 | /// condition is a vector while the other operands are scalar. | ||||
7987 | /// | ||||
7988 | /// We first compute the "result type" for the scalar operands | ||||
7989 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted | ||||
7990 | /// into a vector of that type where the length matches the condition | ||||
7991 | /// vector type. s6.11.6 requires that the element types of the result | ||||
7992 | /// and the condition must have the same number of bits. | ||||
7993 | static QualType | ||||
7994 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
7995 | QualType CondTy, SourceLocation QuestionLoc) { | ||||
7996 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); | ||||
7997 | if (ResTy.isNull()) return QualType(); | ||||
7998 | |||||
7999 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8000 | assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8000, __PRETTY_FUNCTION__)); | ||||
8001 | |||||
8002 | // Determine the vector result type | ||||
8003 | unsigned NumElements = CV->getNumElements(); | ||||
8004 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); | ||||
8005 | |||||
8006 | // Ensure that all types have the same number of bits | ||||
8007 | if (S.Context.getTypeSize(CV->getElementType()) | ||||
8008 | != S.Context.getTypeSize(ResTy)) { | ||||
8009 | // Since VectorTy is created internally, it does not pretty print | ||||
8010 | // with an OpenCL name. Instead, we just print a description. | ||||
8011 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); | ||||
8012 | SmallString<64> Str; | ||||
8013 | llvm::raw_svector_ostream OS(Str); | ||||
8014 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; | ||||
8015 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8016 | << CondTy << OS.str(); | ||||
8017 | return QualType(); | ||||
8018 | } | ||||
8019 | |||||
8020 | // Convert operands to the vector result type | ||||
8021 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); | ||||
8022 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); | ||||
8023 | |||||
8024 | return VectorTy; | ||||
8025 | } | ||||
8026 | |||||
8027 | /// Return false if this is a valid OpenCL condition vector | ||||
8028 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, | ||||
8029 | SourceLocation QuestionLoc) { | ||||
8030 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of | ||||
8031 | // integral type. | ||||
8032 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); | ||||
8033 | assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8033, __PRETTY_FUNCTION__)); | ||||
8034 | QualType EleTy = CondTy->getElementType(); | ||||
8035 | if (EleTy->isIntegerType()) return false; | ||||
8036 | |||||
8037 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) | ||||
8038 | << Cond->getType() << Cond->getSourceRange(); | ||||
8039 | return true; | ||||
8040 | } | ||||
8041 | |||||
8042 | /// Return false if the vector condition type and the vector | ||||
8043 | /// result type are compatible. | ||||
8044 | /// | ||||
8045 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same | ||||
8046 | /// number of elements, and their element types have the same number | ||||
8047 | /// of bits. | ||||
8048 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, | ||||
8049 | SourceLocation QuestionLoc) { | ||||
8050 | const VectorType *CV = CondTy->getAs<VectorType>(); | ||||
8051 | const VectorType *RV = VecResTy->getAs<VectorType>(); | ||||
8052 | assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail ("CV && RV", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8052, __PRETTY_FUNCTION__)); | ||||
8053 | |||||
8054 | if (CV->getNumElements() != RV->getNumElements()) { | ||||
8055 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) | ||||
8056 | << CondTy << VecResTy; | ||||
8057 | return true; | ||||
8058 | } | ||||
8059 | |||||
8060 | QualType CVE = CV->getElementType(); | ||||
8061 | QualType RVE = RV->getElementType(); | ||||
8062 | |||||
8063 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { | ||||
8064 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) | ||||
8065 | << CondTy << VecResTy; | ||||
8066 | return true; | ||||
8067 | } | ||||
8068 | |||||
8069 | return false; | ||||
8070 | } | ||||
8071 | |||||
8072 | /// Return the resulting type for the conditional operator in | ||||
8073 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 | ||||
8074 | /// s6.3.i) when the condition is a vector type. | ||||
8075 | static QualType | ||||
8076 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, | ||||
8077 | ExprResult &LHS, ExprResult &RHS, | ||||
8078 | SourceLocation QuestionLoc) { | ||||
8079 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); | ||||
8080 | if (Cond.isInvalid()) | ||||
8081 | return QualType(); | ||||
8082 | QualType CondTy = Cond.get()->getType(); | ||||
8083 | |||||
8084 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) | ||||
8085 | return QualType(); | ||||
8086 | |||||
8087 | // If either operand is a vector then find the vector type of the | ||||
8088 | // result as specified in OpenCL v1.1 s6.3.i. | ||||
8089 | if (LHS.get()->getType()->isVectorType() || | ||||
8090 | RHS.get()->getType()->isVectorType()) { | ||||
8091 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, | ||||
8092 | /*isCompAssign*/false, | ||||
8093 | /*AllowBothBool*/true, | ||||
8094 | /*AllowBoolConversions*/false); | ||||
8095 | if (VecResTy.isNull()) return QualType(); | ||||
8096 | // The result type must match the condition type as specified in | ||||
8097 | // OpenCL v1.1 s6.11.6. | ||||
8098 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) | ||||
8099 | return QualType(); | ||||
8100 | return VecResTy; | ||||
8101 | } | ||||
8102 | |||||
8103 | // Both operands are scalar. | ||||
8104 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); | ||||
8105 | } | ||||
8106 | |||||
8107 | /// Return true if the Expr is block type | ||||
8108 | static bool checkBlockType(Sema &S, const Expr *E) { | ||||
8109 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
8110 | QualType Ty = CE->getCallee()->getType(); | ||||
8111 | if (Ty->isBlockPointerType()) { | ||||
8112 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); | ||||
8113 | return true; | ||||
8114 | } | ||||
8115 | } | ||||
8116 | return false; | ||||
8117 | } | ||||
8118 | |||||
8119 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. | ||||
8120 | /// In that case, LHS = cond. | ||||
8121 | /// C99 6.5.15 | ||||
8122 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | ||||
8123 | ExprResult &RHS, ExprValueKind &VK, | ||||
8124 | ExprObjectKind &OK, | ||||
8125 | SourceLocation QuestionLoc) { | ||||
8126 | |||||
8127 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); | ||||
8128 | if (!LHSResult.isUsable()) return QualType(); | ||||
8129 | LHS = LHSResult; | ||||
8130 | |||||
8131 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); | ||||
8132 | if (!RHSResult.isUsable()) return QualType(); | ||||
8133 | RHS = RHSResult; | ||||
8134 | |||||
8135 | // C++ is sufficiently different to merit its own checker. | ||||
8136 | if (getLangOpts().CPlusPlus) | ||||
8137 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); | ||||
8138 | |||||
8139 | VK = VK_RValue; | ||||
8140 | OK = OK_Ordinary; | ||||
8141 | |||||
8142 | if (Context.isDependenceAllowed() && | ||||
8143 | (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || | ||||
8144 | RHS.get()->isTypeDependent())) { | ||||
8145 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8145, __PRETTY_FUNCTION__)); | ||||
8146 | assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8148, __PRETTY_FUNCTION__)) | ||||
8147 | RHS.get()->containsErrors()) &&(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8148, __PRETTY_FUNCTION__)) | ||||
8148 | "should only occur in error-recovery path.")(((Cond.get()->containsErrors() || LHS.get()->containsErrors () || RHS.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(Cond.get()->containsErrors() || LHS.get()->containsErrors() || RHS.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8148, __PRETTY_FUNCTION__)); | ||||
8149 | return Context.DependentTy; | ||||
8150 | } | ||||
8151 | |||||
8152 | // The OpenCL operator with a vector condition is sufficiently | ||||
8153 | // different to merit its own checker. | ||||
8154 | if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || | ||||
8155 | Cond.get()->getType()->isExtVectorType()) | ||||
8156 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); | ||||
8157 | |||||
8158 | // First, check the condition. | ||||
8159 | Cond = UsualUnaryConversions(Cond.get()); | ||||
8160 | if (Cond.isInvalid()) | ||||
8161 | return QualType(); | ||||
8162 | if (checkCondition(*this, Cond.get(), QuestionLoc)) | ||||
8163 | return QualType(); | ||||
8164 | |||||
8165 | // Now check the two expressions. | ||||
8166 | if (LHS.get()->getType()->isVectorType() || | ||||
8167 | RHS.get()->getType()->isVectorType()) | ||||
8168 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | ||||
8169 | /*AllowBothBool*/true, | ||||
8170 | /*AllowBoolConversions*/false); | ||||
8171 | |||||
8172 | QualType ResTy = | ||||
8173 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | ||||
8174 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8175 | return QualType(); | ||||
8176 | |||||
8177 | QualType LHSTy = LHS.get()->getType(); | ||||
8178 | QualType RHSTy = RHS.get()->getType(); | ||||
8179 | |||||
8180 | // Diagnose attempts to convert between __float128 and long double where | ||||
8181 | // such conversions currently can't be handled. | ||||
8182 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { | ||||
8183 | Diag(QuestionLoc, | ||||
8184 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy | ||||
8185 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8186 | return QualType(); | ||||
8187 | } | ||||
8188 | |||||
8189 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary | ||||
8190 | // selection operator (?:). | ||||
8191 | if (getLangOpts().OpenCL && | ||||
8192 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { | ||||
8193 | return QualType(); | ||||
8194 | } | ||||
8195 | |||||
8196 | // If both operands have arithmetic type, do the usual arithmetic conversions | ||||
8197 | // to find a common type: C99 6.5.15p3,5. | ||||
8198 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { | ||||
8199 | // Disallow invalid arithmetic conversions, such as those between ExtInts of | ||||
8200 | // different sizes, or between ExtInts and other types. | ||||
8201 | if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { | ||||
8202 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8203 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8204 | << RHS.get()->getSourceRange(); | ||||
8205 | return QualType(); | ||||
8206 | } | ||||
8207 | |||||
8208 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | ||||
8209 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | ||||
8210 | |||||
8211 | return ResTy; | ||||
8212 | } | ||||
8213 | |||||
8214 | // And if they're both bfloat (which isn't arithmetic), that's fine too. | ||||
8215 | if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { | ||||
8216 | return LHSTy; | ||||
8217 | } | ||||
8218 | |||||
8219 | // If both operands are the same structure or union type, the result is that | ||||
8220 | // type. | ||||
8221 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 | ||||
8222 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) | ||||
8223 | if (LHSRT->getDecl() == RHSRT->getDecl()) | ||||
8224 | // "If both the operands have structure or union type, the result has | ||||
8225 | // that type." This implies that CV qualifiers are dropped. | ||||
8226 | return LHSTy.getUnqualifiedType(); | ||||
8227 | // FIXME: Type of conditional expression must be complete in C mode. | ||||
8228 | } | ||||
8229 | |||||
8230 | // C99 6.5.15p5: "If both operands have void type, the result has void type." | ||||
8231 | // The following || allows only one side to be void (a GCC-ism). | ||||
8232 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { | ||||
8233 | return checkConditionalVoidType(*this, LHS, RHS); | ||||
8234 | } | ||||
8235 | |||||
8236 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has | ||||
8237 | // the type of the other operand." | ||||
8238 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; | ||||
8239 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; | ||||
8240 | |||||
8241 | // All objective-c pointer type analysis is done here. | ||||
8242 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, | ||||
8243 | QuestionLoc); | ||||
8244 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
8245 | return QualType(); | ||||
8246 | if (!compositeType.isNull()) | ||||
8247 | return compositeType; | ||||
8248 | |||||
8249 | |||||
8250 | // Handle block pointer types. | ||||
8251 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) | ||||
8252 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, | ||||
8253 | QuestionLoc); | ||||
8254 | |||||
8255 | // Check constraints for C object pointers types (C99 6.5.15p3,6). | ||||
8256 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) | ||||
8257 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, | ||||
8258 | QuestionLoc); | ||||
8259 | |||||
8260 | // GCC compatibility: soften pointer/integer mismatch. Note that | ||||
8261 | // null pointers have been filtered out by this point. | ||||
8262 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, | ||||
8263 | /*IsIntFirstExpr=*/true)) | ||||
8264 | return RHSTy; | ||||
8265 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, | ||||
8266 | /*IsIntFirstExpr=*/false)) | ||||
8267 | return LHSTy; | ||||
8268 | |||||
8269 | // Allow ?: operations in which both operands have the same | ||||
8270 | // built-in sizeless type. | ||||
8271 | if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) | ||||
8272 | return LHSTy; | ||||
8273 | |||||
8274 | // Emit a better diagnostic if one of the expressions is a null pointer | ||||
8275 | // constant and the other is not a pointer type. In this case, the user most | ||||
8276 | // likely forgot to take the address of the other expression. | ||||
8277 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | ||||
8278 | return QualType(); | ||||
8279 | |||||
8280 | // Otherwise, the operands are not compatible. | ||||
8281 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | ||||
8282 | << LHSTy << RHSTy << LHS.get()->getSourceRange() | ||||
8283 | << RHS.get()->getSourceRange(); | ||||
8284 | return QualType(); | ||||
8285 | } | ||||
8286 | |||||
8287 | /// FindCompositeObjCPointerType - Helper method to find composite type of | ||||
8288 | /// two objective-c pointer types of the two input expressions. | ||||
8289 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | ||||
8290 | SourceLocation QuestionLoc) { | ||||
8291 | QualType LHSTy = LHS.get()->getType(); | ||||
8292 | QualType RHSTy = RHS.get()->getType(); | ||||
8293 | |||||
8294 | // Handle things like Class and struct objc_class*. Here we case the result | ||||
8295 | // to the pseudo-builtin, because that will be implicitly cast back to the | ||||
8296 | // redefinition type if an attempt is made to access its fields. | ||||
8297 | if (LHSTy->isObjCClassType() && | ||||
8298 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8299 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8300 | return LHSTy; | ||||
8301 | } | ||||
8302 | if (RHSTy->isObjCClassType() && | ||||
8303 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { | ||||
8304 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8305 | return RHSTy; | ||||
8306 | } | ||||
8307 | // And the same for struct objc_object* / id | ||||
8308 | if (LHSTy->isObjCIdType() && | ||||
8309 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8310 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); | ||||
8311 | return LHSTy; | ||||
8312 | } | ||||
8313 | if (RHSTy->isObjCIdType() && | ||||
8314 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { | ||||
8315 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); | ||||
8316 | return RHSTy; | ||||
8317 | } | ||||
8318 | // And the same for struct objc_selector* / SEL | ||||
8319 | if (Context.isObjCSelType(LHSTy) && | ||||
8320 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8321 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); | ||||
8322 | return LHSTy; | ||||
8323 | } | ||||
8324 | if (Context.isObjCSelType(RHSTy) && | ||||
8325 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { | ||||
8326 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); | ||||
8327 | return RHSTy; | ||||
8328 | } | ||||
8329 | // Check constraints for Objective-C object pointers types. | ||||
8330 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8331 | |||||
8332 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { | ||||
8333 | // Two identical object pointer types are always compatible. | ||||
8334 | return LHSTy; | ||||
8335 | } | ||||
8336 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); | ||||
8337 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); | ||||
8338 | QualType compositeType = LHSTy; | ||||
8339 | |||||
8340 | // If both operands are interfaces and either operand can be | ||||
8341 | // assigned to the other, use that type as the composite | ||||
8342 | // type. This allows | ||||
8343 | // xxx ? (A*) a : (B*) b | ||||
8344 | // where B is a subclass of A. | ||||
8345 | // | ||||
8346 | // Additionally, as for assignment, if either type is 'id' | ||||
8347 | // allow silent coercion. Finally, if the types are | ||||
8348 | // incompatible then make sure to use 'id' as the composite | ||||
8349 | // type so the result is acceptable for sending messages to. | ||||
8350 | |||||
8351 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. | ||||
8352 | // It could return the composite type. | ||||
8353 | if (!(compositeType = | ||||
8354 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { | ||||
8355 | // Nothing more to do. | ||||
8356 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { | ||||
8357 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; | ||||
8358 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { | ||||
8359 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; | ||||
8360 | } else if ((LHSOPT->isObjCQualifiedIdType() || | ||||
8361 | RHSOPT->isObjCQualifiedIdType()) && | ||||
8362 | Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, | ||||
8363 | true)) { | ||||
8364 | // Need to handle "id<xx>" explicitly. | ||||
8365 | // GCC allows qualified id and any Objective-C type to devolve to | ||||
8366 | // id. Currently localizing to here until clear this should be | ||||
8367 | // part of ObjCQualifiedIdTypesAreCompatible. | ||||
8368 | compositeType = Context.getObjCIdType(); | ||||
8369 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { | ||||
8370 | compositeType = Context.getObjCIdType(); | ||||
8371 | } else { | ||||
8372 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) | ||||
8373 | << LHSTy << RHSTy | ||||
8374 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8375 | QualType incompatTy = Context.getObjCIdType(); | ||||
8376 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); | ||||
8377 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); | ||||
8378 | return incompatTy; | ||||
8379 | } | ||||
8380 | // The object pointer types are compatible. | ||||
8381 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); | ||||
8382 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); | ||||
8383 | return compositeType; | ||||
8384 | } | ||||
8385 | // Check Objective-C object pointer types and 'void *' | ||||
8386 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { | ||||
8387 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8388 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8389 | // so these types are not compatible. | ||||
8390 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8391 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8392 | LHS = RHS = true; | ||||
8393 | return QualType(); | ||||
8394 | } | ||||
8395 | QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8396 | QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8397 | QualType destPointee | ||||
8398 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); | ||||
8399 | QualType destType = Context.getPointerType(destPointee); | ||||
8400 | // Add qualifiers if necessary. | ||||
8401 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); | ||||
8402 | // Promote to void*. | ||||
8403 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); | ||||
8404 | return destType; | ||||
8405 | } | ||||
8406 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { | ||||
8407 | if (getLangOpts().ObjCAutoRefCount) { | ||||
8408 | // ARC forbids the implicit conversion of object pointers to 'void *', | ||||
8409 | // so these types are not compatible. | ||||
8410 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy | ||||
8411 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
8412 | LHS = RHS = true; | ||||
8413 | return QualType(); | ||||
8414 | } | ||||
8415 | QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8416 | QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); | ||||
8417 | QualType destPointee | ||||
8418 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); | ||||
8419 | QualType destType = Context.getPointerType(destPointee); | ||||
8420 | // Add qualifiers if necessary. | ||||
8421 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); | ||||
8422 | // Promote to void*. | ||||
8423 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); | ||||
8424 | return destType; | ||||
8425 | } | ||||
8426 | return QualType(); | ||||
8427 | } | ||||
8428 | |||||
8429 | /// SuggestParentheses - Emit a note with a fixit hint that wraps | ||||
8430 | /// ParenRange in parentheses. | ||||
8431 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, | ||||
8432 | const PartialDiagnostic &Note, | ||||
8433 | SourceRange ParenRange) { | ||||
8434 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); | ||||
8435 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && | ||||
8436 | EndLoc.isValid()) { | ||||
8437 | Self.Diag(Loc, Note) | ||||
8438 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") | ||||
8439 | << FixItHint::CreateInsertion(EndLoc, ")"); | ||||
8440 | } else { | ||||
8441 | // We can't display the parentheses, so just show the bare note. | ||||
8442 | Self.Diag(Loc, Note) << ParenRange; | ||||
8443 | } | ||||
8444 | } | ||||
8445 | |||||
8446 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { | ||||
8447 | return BinaryOperator::isAdditiveOp(Opc) || | ||||
8448 | BinaryOperator::isMultiplicativeOp(Opc) || | ||||
8449 | BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; | ||||
8450 | // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and | ||||
8451 | // not any of the logical operators. Bitwise-xor is commonly used as a | ||||
8452 | // logical-xor because there is no logical-xor operator. The logical | ||||
8453 | // operators, including uses of xor, have a high false positive rate for | ||||
8454 | // precedence warnings. | ||||
8455 | } | ||||
8456 | |||||
8457 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary | ||||
8458 | /// expression, either using a built-in or overloaded operator, | ||||
8459 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side | ||||
8460 | /// expression. | ||||
8461 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, | ||||
8462 | Expr **RHSExprs) { | ||||
8463 | // Don't strip parenthesis: we should not warn if E is in parenthesis. | ||||
8464 | E = E->IgnoreImpCasts(); | ||||
8465 | E = E->IgnoreConversionOperatorSingleStep(); | ||||
8466 | E = E->IgnoreImpCasts(); | ||||
8467 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { | ||||
8468 | E = MTE->getSubExpr(); | ||||
8469 | E = E->IgnoreImpCasts(); | ||||
8470 | } | ||||
8471 | |||||
8472 | // Built-in binary operator. | ||||
8473 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { | ||||
8474 | if (IsArithmeticOp(OP->getOpcode())) { | ||||
8475 | *Opcode = OP->getOpcode(); | ||||
8476 | *RHSExprs = OP->getRHS(); | ||||
8477 | return true; | ||||
8478 | } | ||||
8479 | } | ||||
8480 | |||||
8481 | // Overloaded operator. | ||||
8482 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
8483 | if (Call->getNumArgs() != 2) | ||||
8484 | return false; | ||||
8485 | |||||
8486 | // Make sure this is really a binary operator that is safe to pass into | ||||
8487 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. | ||||
8488 | OverloadedOperatorKind OO = Call->getOperator(); | ||||
8489 | if (OO < OO_Plus || OO > OO_Arrow || | ||||
8490 | OO == OO_PlusPlus || OO == OO_MinusMinus) | ||||
8491 | return false; | ||||
8492 | |||||
8493 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); | ||||
8494 | if (IsArithmeticOp(OpKind)) { | ||||
8495 | *Opcode = OpKind; | ||||
8496 | *RHSExprs = Call->getArg(1); | ||||
8497 | return true; | ||||
8498 | } | ||||
8499 | } | ||||
8500 | |||||
8501 | return false; | ||||
8502 | } | ||||
8503 | |||||
8504 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type | ||||
8505 | /// or is a logical expression such as (x==y) which has int type, but is | ||||
8506 | /// commonly interpreted as boolean. | ||||
8507 | static bool ExprLooksBoolean(Expr *E) { | ||||
8508 | E = E->IgnoreParenImpCasts(); | ||||
8509 | |||||
8510 | if (E->getType()->isBooleanType()) | ||||
8511 | return true; | ||||
8512 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) | ||||
8513 | return OP->isComparisonOp() || OP->isLogicalOp(); | ||||
8514 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) | ||||
8515 | return OP->getOpcode() == UO_LNot; | ||||
8516 | if (E->getType()->isPointerType()) | ||||
8517 | return true; | ||||
8518 | // FIXME: What about overloaded operator calls returning "unspecified boolean | ||||
8519 | // type"s (commonly pointer-to-members)? | ||||
8520 | |||||
8521 | return false; | ||||
8522 | } | ||||
8523 | |||||
8524 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator | ||||
8525 | /// and binary operator are mixed in a way that suggests the programmer assumed | ||||
8526 | /// the conditional operator has higher precedence, for example: | ||||
8527 | /// "int x = a + someBinaryCondition ? 1 : 2". | ||||
8528 | static void DiagnoseConditionalPrecedence(Sema &Self, | ||||
8529 | SourceLocation OpLoc, | ||||
8530 | Expr *Condition, | ||||
8531 | Expr *LHSExpr, | ||||
8532 | Expr *RHSExpr) { | ||||
8533 | BinaryOperatorKind CondOpcode; | ||||
8534 | Expr *CondRHS; | ||||
8535 | |||||
8536 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) | ||||
8537 | return; | ||||
8538 | if (!ExprLooksBoolean(CondRHS)) | ||||
8539 | return; | ||||
8540 | |||||
8541 | // The condition is an arithmetic binary expression, with a right- | ||||
8542 | // hand side that looks boolean, so warn. | ||||
8543 | |||||
8544 | unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) | ||||
8545 | ? diag::warn_precedence_bitwise_conditional | ||||
8546 | : diag::warn_precedence_conditional; | ||||
8547 | |||||
8548 | Self.Diag(OpLoc, DiagID) | ||||
8549 | << Condition->getSourceRange() | ||||
8550 | << BinaryOperator::getOpcodeStr(CondOpcode); | ||||
8551 | |||||
8552 | SuggestParentheses( | ||||
8553 | Self, OpLoc, | ||||
8554 | Self.PDiag(diag::note_precedence_silence) | ||||
8555 | << BinaryOperator::getOpcodeStr(CondOpcode), | ||||
8556 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); | ||||
8557 | |||||
8558 | SuggestParentheses(Self, OpLoc, | ||||
8559 | Self.PDiag(diag::note_precedence_conditional_first), | ||||
8560 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
8561 | } | ||||
8562 | |||||
8563 | /// Compute the nullability of a conditional expression. | ||||
8564 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, | ||||
8565 | QualType LHSTy, QualType RHSTy, | ||||
8566 | ASTContext &Ctx) { | ||||
8567 | if (!ResTy->isAnyPointerType()) | ||||
8568 | return ResTy; | ||||
8569 | |||||
8570 | auto GetNullability = [&Ctx](QualType Ty) { | ||||
8571 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); | ||||
8572 | if (Kind) { | ||||
8573 | // For our purposes, treat _Nullable_result as _Nullable. | ||||
8574 | if (*Kind == NullabilityKind::NullableResult) | ||||
8575 | return NullabilityKind::Nullable; | ||||
8576 | return *Kind; | ||||
8577 | } | ||||
8578 | return NullabilityKind::Unspecified; | ||||
8579 | }; | ||||
8580 | |||||
8581 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); | ||||
8582 | NullabilityKind MergedKind; | ||||
8583 | |||||
8584 | // Compute nullability of a binary conditional expression. | ||||
8585 | if (IsBin) { | ||||
8586 | if (LHSKind == NullabilityKind::NonNull) | ||||
8587 | MergedKind = NullabilityKind::NonNull; | ||||
8588 | else | ||||
8589 | MergedKind = RHSKind; | ||||
8590 | // Compute nullability of a normal conditional expression. | ||||
8591 | } else { | ||||
8592 | if (LHSKind == NullabilityKind::Nullable || | ||||
8593 | RHSKind == NullabilityKind::Nullable) | ||||
8594 | MergedKind = NullabilityKind::Nullable; | ||||
8595 | else if (LHSKind == NullabilityKind::NonNull) | ||||
8596 | MergedKind = RHSKind; | ||||
8597 | else if (RHSKind == NullabilityKind::NonNull) | ||||
8598 | MergedKind = LHSKind; | ||||
8599 | else | ||||
8600 | MergedKind = NullabilityKind::Unspecified; | ||||
8601 | } | ||||
8602 | |||||
8603 | // Return if ResTy already has the correct nullability. | ||||
8604 | if (GetNullability(ResTy) == MergedKind) | ||||
8605 | return ResTy; | ||||
8606 | |||||
8607 | // Strip all nullability from ResTy. | ||||
8608 | while (ResTy->getNullability(Ctx)) | ||||
8609 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); | ||||
8610 | |||||
8611 | // Create a new AttributedType with the new nullability kind. | ||||
8612 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); | ||||
8613 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); | ||||
8614 | } | ||||
8615 | |||||
8616 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | ||||
8617 | /// in the case of a the GNU conditional expr extension. | ||||
8618 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, | ||||
8619 | SourceLocation ColonLoc, | ||||
8620 | Expr *CondExpr, Expr *LHSExpr, | ||||
8621 | Expr *RHSExpr) { | ||||
8622 | if (!Context.isDependenceAllowed()) { | ||||
8623 | // C cannot handle TypoExpr nodes in the condition because it | ||||
8624 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
8625 | // been dealt with before checking the operands. | ||||
8626 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); | ||||
8627 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); | ||||
8628 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); | ||||
8629 | |||||
8630 | if (!CondResult.isUsable()) | ||||
8631 | return ExprError(); | ||||
8632 | |||||
8633 | if (LHSExpr) { | ||||
8634 | if (!LHSResult.isUsable()) | ||||
8635 | return ExprError(); | ||||
8636 | } | ||||
8637 | |||||
8638 | if (!RHSResult.isUsable()) | ||||
8639 | return ExprError(); | ||||
8640 | |||||
8641 | CondExpr = CondResult.get(); | ||||
8642 | LHSExpr = LHSResult.get(); | ||||
8643 | RHSExpr = RHSResult.get(); | ||||
8644 | } | ||||
8645 | |||||
8646 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS | ||||
8647 | // was the condition. | ||||
8648 | OpaqueValueExpr *opaqueValue = nullptr; | ||||
8649 | Expr *commonExpr = nullptr; | ||||
8650 | if (!LHSExpr) { | ||||
8651 | commonExpr = CondExpr; | ||||
8652 | // Lower out placeholder types first. This is important so that we don't | ||||
8653 | // try to capture a placeholder. This happens in few cases in C++; such | ||||
8654 | // as Objective-C++'s dictionary subscripting syntax. | ||||
8655 | if (commonExpr->hasPlaceholderType()) { | ||||
8656 | ExprResult result = CheckPlaceholderExpr(commonExpr); | ||||
8657 | if (!result.isUsable()) return ExprError(); | ||||
8658 | commonExpr = result.get(); | ||||
8659 | } | ||||
8660 | // We usually want to apply unary conversions *before* saving, except | ||||
8661 | // in the special case of a C++ l-value conditional. | ||||
8662 | if (!(getLangOpts().CPlusPlus | ||||
8663 | && !commonExpr->isTypeDependent() | ||||
8664 | && commonExpr->getValueKind() == RHSExpr->getValueKind() | ||||
8665 | && commonExpr->isGLValue() | ||||
8666 | && commonExpr->isOrdinaryOrBitFieldObject() | ||||
8667 | && RHSExpr->isOrdinaryOrBitFieldObject() | ||||
8668 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { | ||||
8669 | ExprResult commonRes = UsualUnaryConversions(commonExpr); | ||||
8670 | if (commonRes.isInvalid()) | ||||
8671 | return ExprError(); | ||||
8672 | commonExpr = commonRes.get(); | ||||
8673 | } | ||||
8674 | |||||
8675 | // If the common expression is a class or array prvalue, materialize it | ||||
8676 | // so that we can safely refer to it multiple times. | ||||
8677 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || | ||||
8678 | commonExpr->getType()->isArrayType())) { | ||||
8679 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); | ||||
8680 | if (MatExpr.isInvalid()) | ||||
8681 | return ExprError(); | ||||
8682 | commonExpr = MatExpr.get(); | ||||
8683 | } | ||||
8684 | |||||
8685 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), | ||||
8686 | commonExpr->getType(), | ||||
8687 | commonExpr->getValueKind(), | ||||
8688 | commonExpr->getObjectKind(), | ||||
8689 | commonExpr); | ||||
8690 | LHSExpr = CondExpr = opaqueValue; | ||||
8691 | } | ||||
8692 | |||||
8693 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); | ||||
8694 | ExprValueKind VK = VK_RValue; | ||||
8695 | ExprObjectKind OK = OK_Ordinary; | ||||
8696 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; | ||||
8697 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, | ||||
8698 | VK, OK, QuestionLoc); | ||||
8699 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || | ||||
8700 | RHS.isInvalid()) | ||||
8701 | return ExprError(); | ||||
8702 | |||||
8703 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), | ||||
8704 | RHS.get()); | ||||
8705 | |||||
8706 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); | ||||
8707 | |||||
8708 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, | ||||
8709 | Context); | ||||
8710 | |||||
8711 | if (!commonExpr) | ||||
8712 | return new (Context) | ||||
8713 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, | ||||
8714 | RHS.get(), result, VK, OK); | ||||
8715 | |||||
8716 | return new (Context) BinaryConditionalOperator( | ||||
8717 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, | ||||
8718 | ColonLoc, result, VK, OK); | ||||
8719 | } | ||||
8720 | |||||
8721 | // Check if we have a conversion between incompatible cmse function pointer | ||||
8722 | // types, that is, a conversion between a function pointer with the | ||||
8723 | // cmse_nonsecure_call attribute and one without. | ||||
8724 | static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, | ||||
8725 | QualType ToType) { | ||||
8726 | if (const auto *ToFn = | ||||
8727 | dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { | ||||
8728 | if (const auto *FromFn = | ||||
8729 | dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { | ||||
8730 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | ||||
8731 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | ||||
8732 | |||||
8733 | return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); | ||||
8734 | } | ||||
8735 | } | ||||
8736 | return false; | ||||
8737 | } | ||||
8738 | |||||
8739 | // checkPointerTypesForAssignment - This is a very tricky routine (despite | ||||
8740 | // being closely modeled after the C99 spec:-). The odd characteristic of this | ||||
8741 | // routine is it effectively iqnores the qualifiers on the top level pointee. | ||||
8742 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. | ||||
8743 | // FIXME: add a couple examples in this comment. | ||||
8744 | static Sema::AssignConvertType | ||||
8745 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { | ||||
8746 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8746, __PRETTY_FUNCTION__)); | ||||
8747 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8747, __PRETTY_FUNCTION__)); | ||||
8748 | |||||
8749 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
8750 | const Type *lhptee, *rhptee; | ||||
8751 | Qualifiers lhq, rhq; | ||||
8752 | std::tie(lhptee, lhq) = | ||||
8753 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); | ||||
8754 | std::tie(rhptee, rhq) = | ||||
8755 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); | ||||
8756 | |||||
8757 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
8758 | |||||
8759 | // C99 6.5.16.1p1: This following citation is common to constraints | ||||
8760 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the | ||||
8761 | // qualifiers of the type *pointed to* by the right; | ||||
8762 | |||||
8763 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. | ||||
8764 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && | ||||
8765 | lhq.compatiblyIncludesObjCLifetime(rhq)) { | ||||
8766 | // Ignore lifetime for further calculation. | ||||
8767 | lhq.removeObjCLifetime(); | ||||
8768 | rhq.removeObjCLifetime(); | ||||
8769 | } | ||||
8770 | |||||
8771 | if (!lhq.compatiblyIncludes(rhq)) { | ||||
8772 | // Treat address-space mismatches as fatal. | ||||
8773 | if (!lhq.isAddressSpaceSupersetOf(rhq)) | ||||
8774 | return Sema::IncompatiblePointerDiscardsQualifiers; | ||||
8775 | |||||
8776 | // It's okay to add or remove GC or lifetime qualifiers when converting to | ||||
8777 | // and from void*. | ||||
8778 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() | ||||
8779 | .compatiblyIncludes( | ||||
8780 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) | ||||
8781 | && (lhptee->isVoidType() || rhptee->isVoidType())) | ||||
8782 | ; // keep old | ||||
8783 | |||||
8784 | // Treat lifetime mismatches as fatal. | ||||
8785 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) | ||||
8786 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; | ||||
8787 | |||||
8788 | // For GCC/MS compatibility, other qualifier mismatches are treated | ||||
8789 | // as still compatible in C. | ||||
8790 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
8791 | } | ||||
8792 | |||||
8793 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or | ||||
8794 | // incomplete type and the other is a pointer to a qualified or unqualified | ||||
8795 | // version of void... | ||||
8796 | if (lhptee->isVoidType()) { | ||||
8797 | if (rhptee->isIncompleteOrObjectType()) | ||||
8798 | return ConvTy; | ||||
8799 | |||||
8800 | // As an extension, we allow cast to/from void* to function pointer. | ||||
8801 | assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8801, __PRETTY_FUNCTION__)); | ||||
8802 | return Sema::FunctionVoidPointer; | ||||
8803 | } | ||||
8804 | |||||
8805 | if (rhptee->isVoidType()) { | ||||
8806 | if (lhptee->isIncompleteOrObjectType()) | ||||
8807 | return ConvTy; | ||||
8808 | |||||
8809 | // As an extension, we allow cast to/from void* to function pointer. | ||||
8810 | assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8810, __PRETTY_FUNCTION__)); | ||||
8811 | return Sema::FunctionVoidPointer; | ||||
8812 | } | ||||
8813 | |||||
8814 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or | ||||
8815 | // unqualified versions of compatible types, ... | ||||
8816 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); | ||||
8817 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { | ||||
8818 | // Check if the pointee types are compatible ignoring the sign. | ||||
8819 | // We explicitly check for char so that we catch "char" vs | ||||
8820 | // "unsigned char" on systems where "char" is unsigned. | ||||
8821 | if (lhptee->isCharType()) | ||||
8822 | ltrans = S.Context.UnsignedCharTy; | ||||
8823 | else if (lhptee->hasSignedIntegerRepresentation()) | ||||
8824 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); | ||||
8825 | |||||
8826 | if (rhptee->isCharType()) | ||||
8827 | rtrans = S.Context.UnsignedCharTy; | ||||
8828 | else if (rhptee->hasSignedIntegerRepresentation()) | ||||
8829 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); | ||||
8830 | |||||
8831 | if (ltrans == rtrans) { | ||||
8832 | // Types are compatible ignoring the sign. Qualifier incompatibility | ||||
8833 | // takes priority over sign incompatibility because the sign | ||||
8834 | // warning can be disabled. | ||||
8835 | if (ConvTy != Sema::Compatible) | ||||
8836 | return ConvTy; | ||||
8837 | |||||
8838 | return Sema::IncompatiblePointerSign; | ||||
8839 | } | ||||
8840 | |||||
8841 | // If we are a multi-level pointer, it's possible that our issue is simply | ||||
8842 | // one of qualification - e.g. char ** -> const char ** is not allowed. If | ||||
8843 | // the eventual target type is the same and the pointers have the same | ||||
8844 | // level of indirection, this must be the issue. | ||||
8845 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { | ||||
8846 | do { | ||||
8847 | std::tie(lhptee, lhq) = | ||||
8848 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); | ||||
8849 | std::tie(rhptee, rhq) = | ||||
8850 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); | ||||
8851 | |||||
8852 | // Inconsistent address spaces at this point is invalid, even if the | ||||
8853 | // address spaces would be compatible. | ||||
8854 | // FIXME: This doesn't catch address space mismatches for pointers of | ||||
8855 | // different nesting levels, like: | ||||
8856 | // __local int *** a; | ||||
8857 | // int ** b = a; | ||||
8858 | // It's not clear how to actually determine when such pointers are | ||||
8859 | // invalidly incompatible. | ||||
8860 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) | ||||
8861 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; | ||||
8862 | |||||
8863 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); | ||||
8864 | |||||
8865 | if (lhptee == rhptee) | ||||
8866 | return Sema::IncompatibleNestedPointerQualifiers; | ||||
8867 | } | ||||
8868 | |||||
8869 | // General pointer incompatibility takes priority over qualifiers. | ||||
8870 | if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) | ||||
8871 | return Sema::IncompatibleFunctionPointer; | ||||
8872 | return Sema::IncompatiblePointer; | ||||
8873 | } | ||||
8874 | if (!S.getLangOpts().CPlusPlus && | ||||
8875 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) | ||||
8876 | return Sema::IncompatibleFunctionPointer; | ||||
8877 | if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) | ||||
8878 | return Sema::IncompatibleFunctionPointer; | ||||
8879 | return ConvTy; | ||||
8880 | } | ||||
8881 | |||||
8882 | /// checkBlockPointerTypesForAssignment - This routine determines whether two | ||||
8883 | /// block pointer types are compatible or whether a block and normal pointer | ||||
8884 | /// are compatible. It is more restrict than comparing two function pointer | ||||
8885 | // types. | ||||
8886 | static Sema::AssignConvertType | ||||
8887 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
8888 | QualType RHSType) { | ||||
8889 | assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8889, __PRETTY_FUNCTION__)); | ||||
8890 | assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8890, __PRETTY_FUNCTION__)); | ||||
8891 | |||||
8892 | QualType lhptee, rhptee; | ||||
8893 | |||||
8894 | // get the "pointed to" type (ignoring qualifiers at the top level) | ||||
8895 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); | ||||
8896 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); | ||||
8897 | |||||
8898 | // In C++, the types have to match exactly. | ||||
8899 | if (S.getLangOpts().CPlusPlus) | ||||
8900 | return Sema::IncompatibleBlockPointer; | ||||
8901 | |||||
8902 | Sema::AssignConvertType ConvTy = Sema::Compatible; | ||||
8903 | |||||
8904 | // For blocks we enforce that qualifiers are identical. | ||||
8905 | Qualifiers LQuals = lhptee.getLocalQualifiers(); | ||||
8906 | Qualifiers RQuals = rhptee.getLocalQualifiers(); | ||||
8907 | if (S.getLangOpts().OpenCL) { | ||||
8908 | LQuals.removeAddressSpace(); | ||||
8909 | RQuals.removeAddressSpace(); | ||||
8910 | } | ||||
8911 | if (LQuals != RQuals) | ||||
8912 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; | ||||
8913 | |||||
8914 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block | ||||
8915 | // assignment. | ||||
8916 | // The current behavior is similar to C++ lambdas. A block might be | ||||
8917 | // assigned to a variable iff its return type and parameters are compatible | ||||
8918 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of | ||||
8919 | // an assignment. Presumably it should behave in way that a function pointer | ||||
8920 | // assignment does in C, so for each parameter and return type: | ||||
8921 | // * CVR and address space of LHS should be a superset of CVR and address | ||||
8922 | // space of RHS. | ||||
8923 | // * unqualified types should be compatible. | ||||
8924 | if (S.getLangOpts().OpenCL) { | ||||
8925 | if (!S.Context.typesAreBlockPointerCompatible( | ||||
8926 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), | ||||
8927 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) | ||||
8928 | return Sema::IncompatibleBlockPointer; | ||||
8929 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) | ||||
8930 | return Sema::IncompatibleBlockPointer; | ||||
8931 | |||||
8932 | return ConvTy; | ||||
8933 | } | ||||
8934 | |||||
8935 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types | ||||
8936 | /// for assignment compatibility. | ||||
8937 | static Sema::AssignConvertType | ||||
8938 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, | ||||
8939 | QualType RHSType) { | ||||
8940 | assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8940, __PRETTY_FUNCTION__)); | ||||
8941 | assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!" ) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 8941, __PRETTY_FUNCTION__)); | ||||
8942 | |||||
8943 | if (LHSType->isObjCBuiltinType()) { | ||||
8944 | // Class is not compatible with ObjC object pointers. | ||||
8945 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && | ||||
8946 | !RHSType->isObjCQualifiedClassType()) | ||||
8947 | return Sema::IncompatiblePointer; | ||||
8948 | return Sema::Compatible; | ||||
8949 | } | ||||
8950 | if (RHSType->isObjCBuiltinType()) { | ||||
8951 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && | ||||
8952 | !LHSType->isObjCQualifiedClassType()) | ||||
8953 | return Sema::IncompatiblePointer; | ||||
8954 | return Sema::Compatible; | ||||
8955 | } | ||||
8956 | QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8957 | QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); | ||||
8958 | |||||
8959 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && | ||||
8960 | // make an exception for id<P> | ||||
8961 | !LHSType->isObjCQualifiedIdType()) | ||||
8962 | return Sema::CompatiblePointerDiscardsQualifiers; | ||||
8963 | |||||
8964 | if (S.Context.typesAreCompatible(LHSType, RHSType)) | ||||
8965 | return Sema::Compatible; | ||||
8966 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) | ||||
8967 | return Sema::IncompatibleObjCQualifiedId; | ||||
8968 | return Sema::IncompatiblePointer; | ||||
8969 | } | ||||
8970 | |||||
8971 | Sema::AssignConvertType | ||||
8972 | Sema::CheckAssignmentConstraints(SourceLocation Loc, | ||||
8973 | QualType LHSType, QualType RHSType) { | ||||
8974 | // Fake up an opaque expression. We don't actually care about what | ||||
8975 | // cast operations are required, so if CheckAssignmentConstraints | ||||
8976 | // adds casts to this they'll be wasted, but fortunately that doesn't | ||||
8977 | // usually happen on valid code. | ||||
8978 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); | ||||
8979 | ExprResult RHSPtr = &RHSExpr; | ||||
8980 | CastKind K; | ||||
8981 | |||||
8982 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); | ||||
8983 | } | ||||
8984 | |||||
8985 | /// This helper function returns true if QT is a vector type that has element | ||||
8986 | /// type ElementType. | ||||
8987 | static bool isVector(QualType QT, QualType ElementType) { | ||||
8988 | if (const VectorType *VT = QT->getAs<VectorType>()) | ||||
8989 | return VT->getElementType().getCanonicalType() == ElementType; | ||||
8990 | return false; | ||||
8991 | } | ||||
8992 | |||||
8993 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently | ||||
8994 | /// has code to accommodate several GCC extensions when type checking | ||||
8995 | /// pointers. Here are some objectionable examples that GCC considers warnings: | ||||
8996 | /// | ||||
8997 | /// int a, *pint; | ||||
8998 | /// short *pshort; | ||||
8999 | /// struct foo *pfoo; | ||||
9000 | /// | ||||
9001 | /// pint = pshort; // warning: assignment from incompatible pointer type | ||||
9002 | /// a = pint; // warning: assignment makes integer from pointer without a cast | ||||
9003 | /// pint = a; // warning: assignment makes pointer from integer without a cast | ||||
9004 | /// pint = pfoo; // warning: assignment from incompatible pointer type | ||||
9005 | /// | ||||
9006 | /// As a result, the code for dealing with pointers is more complex than the | ||||
9007 | /// C99 spec dictates. | ||||
9008 | /// | ||||
9009 | /// Sets 'Kind' for any result kind except Incompatible. | ||||
9010 | Sema::AssignConvertType | ||||
9011 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, | ||||
9012 | CastKind &Kind, bool ConvertRHS) { | ||||
9013 | QualType RHSType = RHS.get()->getType(); | ||||
9014 | QualType OrigLHSType = LHSType; | ||||
9015 | |||||
9016 | // Get canonical types. We're not formatting these types, just comparing | ||||
9017 | // them. | ||||
9018 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); | ||||
9019 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); | ||||
9020 | |||||
9021 | // Common case: no conversion required. | ||||
9022 | if (LHSType == RHSType) { | ||||
9023 | Kind = CK_NoOp; | ||||
9024 | return Compatible; | ||||
9025 | } | ||||
9026 | |||||
9027 | // If we have an atomic type, try a non-atomic assignment, then just add an | ||||
9028 | // atomic qualification step. | ||||
9029 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { | ||||
9030 | Sema::AssignConvertType result = | ||||
9031 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); | ||||
9032 | if (result != Compatible) | ||||
9033 | return result; | ||||
9034 | if (Kind != CK_NoOp && ConvertRHS) | ||||
9035 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); | ||||
9036 | Kind = CK_NonAtomicToAtomic; | ||||
9037 | return Compatible; | ||||
9038 | } | ||||
9039 | |||||
9040 | // If the left-hand side is a reference type, then we are in a | ||||
9041 | // (rare!) case where we've allowed the use of references in C, | ||||
9042 | // e.g., as a parameter type in a built-in function. In this case, | ||||
9043 | // just make sure that the type referenced is compatible with the | ||||
9044 | // right-hand side type. The caller is responsible for adjusting | ||||
9045 | // LHSType so that the resulting expression does not have reference | ||||
9046 | // type. | ||||
9047 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { | ||||
9048 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { | ||||
9049 | Kind = CK_LValueBitCast; | ||||
9050 | return Compatible; | ||||
9051 | } | ||||
9052 | return Incompatible; | ||||
9053 | } | ||||
9054 | |||||
9055 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type | ||||
9056 | // to the same ExtVector type. | ||||
9057 | if (LHSType->isExtVectorType()) { | ||||
9058 | if (RHSType->isExtVectorType()) | ||||
9059 | return Incompatible; | ||||
9060 | if (RHSType->isArithmeticType()) { | ||||
9061 | // CK_VectorSplat does T -> vector T, so first cast to the element type. | ||||
9062 | if (ConvertRHS) | ||||
9063 | RHS = prepareVectorSplat(LHSType, RHS.get()); | ||||
9064 | Kind = CK_VectorSplat; | ||||
9065 | return Compatible; | ||||
9066 | } | ||||
9067 | } | ||||
9068 | |||||
9069 | // Conversions to or from vector type. | ||||
9070 | if (LHSType->isVectorType() || RHSType->isVectorType()) { | ||||
9071 | if (LHSType->isVectorType() && RHSType->isVectorType()) { | ||||
9072 | // Allow assignments of an AltiVec vector type to an equivalent GCC | ||||
9073 | // vector type and vice versa | ||||
9074 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9075 | Kind = CK_BitCast; | ||||
9076 | return Compatible; | ||||
9077 | } | ||||
9078 | |||||
9079 | // If we are allowing lax vector conversions, and LHS and RHS are both | ||||
9080 | // vectors, the total size only needs to be the same. This is a bitcast; | ||||
9081 | // no bits are changed but the result type is different. | ||||
9082 | if (isLaxVectorConversion(RHSType, LHSType)) { | ||||
9083 | Kind = CK_BitCast; | ||||
9084 | return IncompatibleVectors; | ||||
9085 | } | ||||
9086 | } | ||||
9087 | |||||
9088 | // When the RHS comes from another lax conversion (e.g. binops between | ||||
9089 | // scalars and vectors) the result is canonicalized as a vector. When the | ||||
9090 | // LHS is also a vector, the lax is allowed by the condition above. Handle | ||||
9091 | // the case where LHS is a scalar. | ||||
9092 | if (LHSType->isScalarType()) { | ||||
9093 | const VectorType *VecType = RHSType->getAs<VectorType>(); | ||||
9094 | if (VecType && VecType->getNumElements() == 1 && | ||||
9095 | isLaxVectorConversion(RHSType, LHSType)) { | ||||
9096 | ExprResult *VecExpr = &RHS; | ||||
9097 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); | ||||
9098 | Kind = CK_BitCast; | ||||
9099 | return Compatible; | ||||
9100 | } | ||||
9101 | } | ||||
9102 | |||||
9103 | // Allow assignments between fixed-length and sizeless SVE vectors. | ||||
9104 | if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || | ||||
9105 | (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) | ||||
9106 | if (Context.areCompatibleSveTypes(LHSType, RHSType) || | ||||
9107 | Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { | ||||
9108 | Kind = CK_BitCast; | ||||
9109 | return Compatible; | ||||
9110 | } | ||||
9111 | |||||
9112 | return Incompatible; | ||||
9113 | } | ||||
9114 | |||||
9115 | // Diagnose attempts to convert between __float128 and long double where | ||||
9116 | // such conversions currently can't be handled. | ||||
9117 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) | ||||
9118 | return Incompatible; | ||||
9119 | |||||
9120 | // Disallow assigning a _Complex to a real type in C++ mode since it simply | ||||
9121 | // discards the imaginary part. | ||||
9122 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && | ||||
9123 | !LHSType->getAs<ComplexType>()) | ||||
9124 | return Incompatible; | ||||
9125 | |||||
9126 | // Arithmetic conversions. | ||||
9127 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && | ||||
9128 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { | ||||
9129 | if (ConvertRHS) | ||||
9130 | Kind = PrepareScalarCast(RHS, LHSType); | ||||
9131 | return Compatible; | ||||
9132 | } | ||||
9133 | |||||
9134 | // Conversions to normal pointers. | ||||
9135 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { | ||||
9136 | // U* -> T* | ||||
9137 | if (isa<PointerType>(RHSType)) { | ||||
9138 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9139 | LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); | ||||
9140 | if (AddrSpaceL != AddrSpaceR) | ||||
9141 | Kind = CK_AddressSpaceConversion; | ||||
9142 | else if (Context.hasCvrSimilarType(RHSType, LHSType)) | ||||
9143 | Kind = CK_NoOp; | ||||
9144 | else | ||||
9145 | Kind = CK_BitCast; | ||||
9146 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9147 | } | ||||
9148 | |||||
9149 | // int -> T* | ||||
9150 | if (RHSType->isIntegerType()) { | ||||
9151 | Kind = CK_IntegralToPointer; // FIXME: null? | ||||
9152 | return IntToPointer; | ||||
9153 | } | ||||
9154 | |||||
9155 | // C pointers are not compatible with ObjC object pointers, | ||||
9156 | // with two exceptions: | ||||
9157 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9158 | // - conversions to void* | ||||
9159 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9160 | Kind = CK_BitCast; | ||||
9161 | return Compatible; | ||||
9162 | } | ||||
9163 | |||||
9164 | // - conversions from 'Class' to the redefinition type | ||||
9165 | if (RHSType->isObjCClassType() && | ||||
9166 | Context.hasSameType(LHSType, | ||||
9167 | Context.getObjCClassRedefinitionType())) { | ||||
9168 | Kind = CK_BitCast; | ||||
9169 | return Compatible; | ||||
9170 | } | ||||
9171 | |||||
9172 | Kind = CK_BitCast; | ||||
9173 | return IncompatiblePointer; | ||||
9174 | } | ||||
9175 | |||||
9176 | // U^ -> void* | ||||
9177 | if (RHSType->getAs<BlockPointerType>()) { | ||||
9178 | if (LHSPointer->getPointeeType()->isVoidType()) { | ||||
9179 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); | ||||
9180 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9181 | ->getPointeeType() | ||||
9182 | .getAddressSpace(); | ||||
9183 | Kind = | ||||
9184 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9185 | return Compatible; | ||||
9186 | } | ||||
9187 | } | ||||
9188 | |||||
9189 | return Incompatible; | ||||
9190 | } | ||||
9191 | |||||
9192 | // Conversions to block pointers. | ||||
9193 | if (isa<BlockPointerType>(LHSType)) { | ||||
9194 | // U^ -> T^ | ||||
9195 | if (RHSType->isBlockPointerType()) { | ||||
9196 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() | ||||
9197 | ->getPointeeType() | ||||
9198 | .getAddressSpace(); | ||||
9199 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() | ||||
9200 | ->getPointeeType() | ||||
9201 | .getAddressSpace(); | ||||
9202 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | ||||
9203 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9204 | } | ||||
9205 | |||||
9206 | // int or null -> T^ | ||||
9207 | if (RHSType->isIntegerType()) { | ||||
9208 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9209 | return IntToBlockPointer; | ||||
9210 | } | ||||
9211 | |||||
9212 | // id -> T^ | ||||
9213 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { | ||||
9214 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9215 | return Compatible; | ||||
9216 | } | ||||
9217 | |||||
9218 | // void* -> T^ | ||||
9219 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) | ||||
9220 | if (RHSPT->getPointeeType()->isVoidType()) { | ||||
9221 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
9222 | return Compatible; | ||||
9223 | } | ||||
9224 | |||||
9225 | return Incompatible; | ||||
9226 | } | ||||
9227 | |||||
9228 | // Conversions to Objective-C pointers. | ||||
9229 | if (isa<ObjCObjectPointerType>(LHSType)) { | ||||
9230 | // A* -> B* | ||||
9231 | if (RHSType->isObjCObjectPointerType()) { | ||||
9232 | Kind = CK_BitCast; | ||||
9233 | Sema::AssignConvertType result = | ||||
9234 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); | ||||
9235 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9236 | result == Compatible && | ||||
9237 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) | ||||
9238 | result = IncompatibleObjCWeakRef; | ||||
9239 | return result; | ||||
9240 | } | ||||
9241 | |||||
9242 | // int or null -> A* | ||||
9243 | if (RHSType->isIntegerType()) { | ||||
9244 | Kind = CK_IntegralToPointer; // FIXME: null | ||||
9245 | return IntToPointer; | ||||
9246 | } | ||||
9247 | |||||
9248 | // In general, C pointers are not compatible with ObjC object pointers, | ||||
9249 | // with two exceptions: | ||||
9250 | if (isa<PointerType>(RHSType)) { | ||||
9251 | Kind = CK_CPointerToObjCPointerCast; | ||||
9252 | |||||
9253 | // - conversions from 'void*' | ||||
9254 | if (RHSType->isVoidPointerType()) { | ||||
9255 | return Compatible; | ||||
9256 | } | ||||
9257 | |||||
9258 | // - conversions to 'Class' from its redefinition type | ||||
9259 | if (LHSType->isObjCClassType() && | ||||
9260 | Context.hasSameType(RHSType, | ||||
9261 | Context.getObjCClassRedefinitionType())) { | ||||
9262 | return Compatible; | ||||
9263 | } | ||||
9264 | |||||
9265 | return IncompatiblePointer; | ||||
9266 | } | ||||
9267 | |||||
9268 | // Only under strict condition T^ is compatible with an Objective-C pointer. | ||||
9269 | if (RHSType->isBlockPointerType() && | ||||
9270 | LHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
9271 | if (ConvertRHS) | ||||
9272 | maybeExtendBlockObject(RHS); | ||||
9273 | Kind = CK_BlockPointerToObjCPointerCast; | ||||
9274 | return Compatible; | ||||
9275 | } | ||||
9276 | |||||
9277 | return Incompatible; | ||||
9278 | } | ||||
9279 | |||||
9280 | // Conversions from pointers that are not covered by the above. | ||||
9281 | if (isa<PointerType>(RHSType)) { | ||||
9282 | // T* -> _Bool | ||||
9283 | if (LHSType == Context.BoolTy) { | ||||
9284 | Kind = CK_PointerToBoolean; | ||||
9285 | return Compatible; | ||||
9286 | } | ||||
9287 | |||||
9288 | // T* -> int | ||||
9289 | if (LHSType->isIntegerType()) { | ||||
9290 | Kind = CK_PointerToIntegral; | ||||
9291 | return PointerToInt; | ||||
9292 | } | ||||
9293 | |||||
9294 | return Incompatible; | ||||
9295 | } | ||||
9296 | |||||
9297 | // Conversions from Objective-C pointers that are not covered by the above. | ||||
9298 | if (isa<ObjCObjectPointerType>(RHSType)) { | ||||
9299 | // T* -> _Bool | ||||
9300 | if (LHSType == Context.BoolTy) { | ||||
9301 | Kind = CK_PointerToBoolean; | ||||
9302 | return Compatible; | ||||
9303 | } | ||||
9304 | |||||
9305 | // T* -> int | ||||
9306 | if (LHSType->isIntegerType()) { | ||||
9307 | Kind = CK_PointerToIntegral; | ||||
9308 | return PointerToInt; | ||||
9309 | } | ||||
9310 | |||||
9311 | return Incompatible; | ||||
9312 | } | ||||
9313 | |||||
9314 | // struct A -> struct B | ||||
9315 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { | ||||
9316 | if (Context.typesAreCompatible(LHSType, RHSType)) { | ||||
9317 | Kind = CK_NoOp; | ||||
9318 | return Compatible; | ||||
9319 | } | ||||
9320 | } | ||||
9321 | |||||
9322 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { | ||||
9323 | Kind = CK_IntToOCLSampler; | ||||
9324 | return Compatible; | ||||
9325 | } | ||||
9326 | |||||
9327 | return Incompatible; | ||||
9328 | } | ||||
9329 | |||||
9330 | /// Constructs a transparent union from an expression that is | ||||
9331 | /// used to initialize the transparent union. | ||||
9332 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, | ||||
9333 | ExprResult &EResult, QualType UnionType, | ||||
9334 | FieldDecl *Field) { | ||||
9335 | // Build an initializer list that designates the appropriate member | ||||
9336 | // of the transparent union. | ||||
9337 | Expr *E = EResult.get(); | ||||
9338 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), | ||||
9339 | E, SourceLocation()); | ||||
9340 | Initializer->setType(UnionType); | ||||
9341 | Initializer->setInitializedFieldInUnion(Field); | ||||
9342 | |||||
9343 | // Build a compound literal constructing a value of the transparent | ||||
9344 | // union type from this initializer list. | ||||
9345 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); | ||||
9346 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, | ||||
9347 | VK_RValue, Initializer, false); | ||||
9348 | } | ||||
9349 | |||||
9350 | Sema::AssignConvertType | ||||
9351 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, | ||||
9352 | ExprResult &RHS) { | ||||
9353 | QualType RHSType = RHS.get()->getType(); | ||||
9354 | |||||
9355 | // If the ArgType is a Union type, we want to handle a potential | ||||
9356 | // transparent_union GCC extension. | ||||
9357 | const RecordType *UT = ArgType->getAsUnionType(); | ||||
9358 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | ||||
9359 | return Incompatible; | ||||
9360 | |||||
9361 | // The field to initialize within the transparent union. | ||||
9362 | RecordDecl *UD = UT->getDecl(); | ||||
9363 | FieldDecl *InitField = nullptr; | ||||
9364 | // It's compatible if the expression matches any of the fields. | ||||
9365 | for (auto *it : UD->fields()) { | ||||
9366 | if (it->getType()->isPointerType()) { | ||||
9367 | // If the transparent union contains a pointer type, we allow: | ||||
9368 | // 1) void pointer | ||||
9369 | // 2) null pointer constant | ||||
9370 | if (RHSType->isPointerType()) | ||||
9371 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | ||||
9372 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); | ||||
9373 | InitField = it; | ||||
9374 | break; | ||||
9375 | } | ||||
9376 | |||||
9377 | if (RHS.get()->isNullPointerConstant(Context, | ||||
9378 | Expr::NPC_ValueDependentIsNull)) { | ||||
9379 | RHS = ImpCastExprToType(RHS.get(), it->getType(), | ||||
9380 | CK_NullToPointer); | ||||
9381 | InitField = it; | ||||
9382 | break; | ||||
9383 | } | ||||
9384 | } | ||||
9385 | |||||
9386 | CastKind Kind; | ||||
9387 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) | ||||
9388 | == Compatible) { | ||||
9389 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); | ||||
9390 | InitField = it; | ||||
9391 | break; | ||||
9392 | } | ||||
9393 | } | ||||
9394 | |||||
9395 | if (!InitField) | ||||
9396 | return Incompatible; | ||||
9397 | |||||
9398 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); | ||||
9399 | return Compatible; | ||||
9400 | } | ||||
9401 | |||||
9402 | Sema::AssignConvertType | ||||
9403 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, | ||||
9404 | bool Diagnose, | ||||
9405 | bool DiagnoseCFAudited, | ||||
9406 | bool ConvertRHS) { | ||||
9407 | // We need to be able to tell the caller whether we diagnosed a problem, if | ||||
9408 | // they ask us to issue diagnostics. | ||||
9409 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 9409, __PRETTY_FUNCTION__)); | ||||
9410 | |||||
9411 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, | ||||
9412 | // we can't avoid *all* modifications at the moment, so we need some somewhere | ||||
9413 | // to put the updated value. | ||||
9414 | ExprResult LocalRHS = CallerRHS; | ||||
9415 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; | ||||
9416 | |||||
9417 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { | ||||
9418 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { | ||||
9419 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||
9420 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
9421 | Diag(RHS.get()->getExprLoc(), | ||||
9422 | diag::warn_noderef_to_dereferenceable_pointer) | ||||
9423 | << RHS.get()->getSourceRange(); | ||||
9424 | } | ||||
9425 | } | ||||
9426 | } | ||||
9427 | |||||
9428 | if (getLangOpts().CPlusPlus) { | ||||
9429 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { | ||||
9430 | // C++ 5.17p3: If the left operand is not of class type, the | ||||
9431 | // expression is implicitly converted (C++ 4) to the | ||||
9432 | // cv-unqualified type of the left operand. | ||||
9433 | QualType RHSType = RHS.get()->getType(); | ||||
9434 | if (Diagnose) { | ||||
9435 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9436 | AA_Assigning); | ||||
9437 | } else { | ||||
9438 | ImplicitConversionSequence ICS = | ||||
9439 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9440 | /*SuppressUserConversions=*/false, | ||||
9441 | AllowedExplicit::None, | ||||
9442 | /*InOverloadResolution=*/false, | ||||
9443 | /*CStyle=*/false, | ||||
9444 | /*AllowObjCWritebackConversion=*/false); | ||||
9445 | if (ICS.isFailure()) | ||||
9446 | return Incompatible; | ||||
9447 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), | ||||
9448 | ICS, AA_Assigning); | ||||
9449 | } | ||||
9450 | if (RHS.isInvalid()) | ||||
9451 | return Incompatible; | ||||
9452 | Sema::AssignConvertType result = Compatible; | ||||
9453 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9454 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) | ||||
9455 | result = IncompatibleObjCWeakRef; | ||||
9456 | return result; | ||||
9457 | } | ||||
9458 | |||||
9459 | // FIXME: Currently, we fall through and treat C++ classes like C | ||||
9460 | // structures. | ||||
9461 | // FIXME: We also fall through for atomics; not sure what should | ||||
9462 | // happen there, though. | ||||
9463 | } else if (RHS.get()->getType() == Context.OverloadTy) { | ||||
9464 | // As a set of extensions to C, we support overloading on functions. These | ||||
9465 | // functions need to be resolved here. | ||||
9466 | DeclAccessPair DAP; | ||||
9467 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( | ||||
9468 | RHS.get(), LHSType, /*Complain=*/false, DAP)) | ||||
9469 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); | ||||
9470 | else | ||||
9471 | return Incompatible; | ||||
9472 | } | ||||
9473 | |||||
9474 | // C99 6.5.16.1p1: the left operand is a pointer and the right is | ||||
9475 | // a null pointer constant. | ||||
9476 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || | ||||
9477 | LHSType->isBlockPointerType()) && | ||||
9478 | RHS.get()->isNullPointerConstant(Context, | ||||
9479 | Expr::NPC_ValueDependentIsNull)) { | ||||
9480 | if (Diagnose || ConvertRHS) { | ||||
9481 | CastKind Kind; | ||||
9482 | CXXCastPath Path; | ||||
9483 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, | ||||
9484 | /*IgnoreBaseAccess=*/false, Diagnose); | ||||
9485 | if (ConvertRHS) | ||||
9486 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); | ||||
9487 | } | ||||
9488 | return Compatible; | ||||
9489 | } | ||||
9490 | |||||
9491 | // OpenCL queue_t type assignment. | ||||
9492 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( | ||||
9493 | Context, Expr::NPC_ValueDependentIsNull)) { | ||||
9494 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
9495 | return Compatible; | ||||
9496 | } | ||||
9497 | |||||
9498 | // This check seems unnatural, however it is necessary to ensure the proper | ||||
9499 | // conversion of functions/arrays. If the conversion were done for all | ||||
9500 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary | ||||
9501 | // expressions that suppress this implicit conversion (&, sizeof). | ||||
9502 | // | ||||
9503 | // Suppress this for references: C++ 8.5.3p5. | ||||
9504 | if (!LHSType->isReferenceType()) { | ||||
9505 | // FIXME: We potentially allocate here even if ConvertRHS is false. | ||||
9506 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); | ||||
9507 | if (RHS.isInvalid()) | ||||
9508 | return Incompatible; | ||||
9509 | } | ||||
9510 | CastKind Kind; | ||||
9511 | Sema::AssignConvertType result = | ||||
9512 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); | ||||
9513 | |||||
9514 | // C99 6.5.16.1p2: The value of the right operand is converted to the | ||||
9515 | // type of the assignment expression. | ||||
9516 | // CheckAssignmentConstraints allows the left-hand side to be a reference, | ||||
9517 | // so that we can use references in built-in functions even in C. | ||||
9518 | // The getNonReferenceType() call makes sure that the resulting expression | ||||
9519 | // does not have reference type. | ||||
9520 | if (result != Incompatible && RHS.get()->getType() != LHSType) { | ||||
9521 | QualType Ty = LHSType.getNonLValueExprType(Context); | ||||
9522 | Expr *E = RHS.get(); | ||||
9523 | |||||
9524 | // Check for various Objective-C errors. If we are not reporting | ||||
9525 | // diagnostics and just checking for errors, e.g., during overload | ||||
9526 | // resolution, return Incompatible to indicate the failure. | ||||
9527 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
9528 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, | ||||
9529 | Diagnose, DiagnoseCFAudited) != ACR_okay) { | ||||
9530 | if (!Diagnose) | ||||
9531 | return Incompatible; | ||||
9532 | } | ||||
9533 | if (getLangOpts().ObjC && | ||||
9534 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, | ||||
9535 | E->getType(), E, Diagnose) || | ||||
9536 | CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { | ||||
9537 | if (!Diagnose) | ||||
9538 | return Incompatible; | ||||
9539 | // Replace the expression with a corrected version and continue so we | ||||
9540 | // can find further errors. | ||||
9541 | RHS = E; | ||||
9542 | return Compatible; | ||||
9543 | } | ||||
9544 | |||||
9545 | if (ConvertRHS) | ||||
9546 | RHS = ImpCastExprToType(E, Ty, Kind); | ||||
9547 | } | ||||
9548 | |||||
9549 | return result; | ||||
9550 | } | ||||
9551 | |||||
9552 | namespace { | ||||
9553 | /// The original operand to an operator, prior to the application of the usual | ||||
9554 | /// arithmetic conversions and converting the arguments of a builtin operator | ||||
9555 | /// candidate. | ||||
9556 | struct OriginalOperand { | ||||
9557 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { | ||||
9558 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) | ||||
9559 | Op = MTE->getSubExpr(); | ||||
9560 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) | ||||
9561 | Op = BTE->getSubExpr(); | ||||
9562 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { | ||||
9563 | Orig = ICE->getSubExprAsWritten(); | ||||
9564 | Conversion = ICE->getConversionFunction(); | ||||
9565 | } | ||||
9566 | } | ||||
9567 | |||||
9568 | QualType getType() const { return Orig->getType(); } | ||||
9569 | |||||
9570 | Expr *Orig; | ||||
9571 | NamedDecl *Conversion; | ||||
9572 | }; | ||||
9573 | } | ||||
9574 | |||||
9575 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9576 | ExprResult &RHS) { | ||||
9577 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); | ||||
9578 | |||||
9579 | Diag(Loc, diag::err_typecheck_invalid_operands) | ||||
9580 | << OrigLHS.getType() << OrigRHS.getType() | ||||
9581 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
9582 | |||||
9583 | // If a user-defined conversion was applied to either of the operands prior | ||||
9584 | // to applying the built-in operator rules, tell the user about it. | ||||
9585 | if (OrigLHS.Conversion) { | ||||
9586 | Diag(OrigLHS.Conversion->getLocation(), | ||||
9587 | diag::note_typecheck_invalid_operands_converted) | ||||
9588 | << 0 << LHS.get()->getType(); | ||||
9589 | } | ||||
9590 | if (OrigRHS.Conversion) { | ||||
9591 | Diag(OrigRHS.Conversion->getLocation(), | ||||
9592 | diag::note_typecheck_invalid_operands_converted) | ||||
9593 | << 1 << RHS.get()->getType(); | ||||
9594 | } | ||||
9595 | |||||
9596 | return QualType(); | ||||
9597 | } | ||||
9598 | |||||
9599 | // Diagnose cases where a scalar was implicitly converted to a vector and | ||||
9600 | // diagnose the underlying types. Otherwise, diagnose the error | ||||
9601 | // as invalid vector logical operands for non-C++ cases. | ||||
9602 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | ||||
9603 | ExprResult &RHS) { | ||||
9604 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); | ||||
9605 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); | ||||
9606 | |||||
9607 | bool LHSNatVec = LHSType->isVectorType(); | ||||
9608 | bool RHSNatVec = RHSType->isVectorType(); | ||||
9609 | |||||
9610 | if (!(LHSNatVec && RHSNatVec)) { | ||||
9611 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); | ||||
9612 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); | ||||
9613 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9614 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() | ||||
9615 | << Vector->getSourceRange(); | ||||
9616 | return QualType(); | ||||
9617 | } | ||||
9618 | |||||
9619 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) | ||||
9620 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
9621 | << RHS.get()->getSourceRange(); | ||||
9622 | |||||
9623 | return QualType(); | ||||
9624 | } | ||||
9625 | |||||
9626 | /// Try to convert a value of non-vector type to a vector type by converting | ||||
9627 | /// the type to the element type of the vector and then performing a splat. | ||||
9628 | /// If the language is OpenCL, we only use conversions that promote scalar | ||||
9629 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except | ||||
9630 | /// for float->int. | ||||
9631 | /// | ||||
9632 | /// OpenCL V2.0 6.2.6.p2: | ||||
9633 | /// An error shall occur if any scalar operand type has greater rank | ||||
9634 | /// than the type of the vector element. | ||||
9635 | /// | ||||
9636 | /// \param scalar - if non-null, actually perform the conversions | ||||
9637 | /// \return true if the operation fails (but without diagnosing the failure) | ||||
9638 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, | ||||
9639 | QualType scalarTy, | ||||
9640 | QualType vectorEltTy, | ||||
9641 | QualType vectorTy, | ||||
9642 | unsigned &DiagID) { | ||||
9643 | // The conversion to apply to the scalar before splatting it, | ||||
9644 | // if necessary. | ||||
9645 | CastKind scalarCast = CK_NoOp; | ||||
9646 | |||||
9647 | if (vectorEltTy->isIntegralType(S.Context)) { | ||||
9648 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || | ||||
9649 | (scalarTy->isIntegerType() && | ||||
9650 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { | ||||
9651 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9652 | return true; | ||||
9653 | } | ||||
9654 | if (!scalarTy->isIntegralType(S.Context)) | ||||
9655 | return true; | ||||
9656 | scalarCast = CK_IntegralCast; | ||||
9657 | } else if (vectorEltTy->isRealFloatingType()) { | ||||
9658 | if (scalarTy->isRealFloatingType()) { | ||||
9659 | if (S.getLangOpts().OpenCL && | ||||
9660 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { | ||||
9661 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; | ||||
9662 | return true; | ||||
9663 | } | ||||
9664 | scalarCast = CK_FloatingCast; | ||||
9665 | } | ||||
9666 | else if (scalarTy->isIntegralType(S.Context)) | ||||
9667 | scalarCast = CK_IntegralToFloating; | ||||
9668 | else | ||||
9669 | return true; | ||||
9670 | } else { | ||||
9671 | return true; | ||||
9672 | } | ||||
9673 | |||||
9674 | // Adjust scalar if desired. | ||||
9675 | if (scalar) { | ||||
9676 | if (scalarCast != CK_NoOp) | ||||
9677 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); | ||||
9678 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); | ||||
9679 | } | ||||
9680 | return false; | ||||
9681 | } | ||||
9682 | |||||
9683 | /// Convert vector E to a vector with the same number of elements but different | ||||
9684 | /// element type. | ||||
9685 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { | ||||
9686 | const auto *VecTy = E->getType()->getAs<VectorType>(); | ||||
9687 | assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast <void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 9687, __PRETTY_FUNCTION__)); | ||||
9688 | QualType NewVecTy = S.Context.getVectorType(ElementType, | ||||
9689 | VecTy->getNumElements(), | ||||
9690 | VecTy->getVectorKind()); | ||||
9691 | |||||
9692 | // Look through the implicit cast. Return the subexpression if its type is | ||||
9693 | // NewVecTy. | ||||
9694 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
9695 | if (ICE->getSubExpr()->getType() == NewVecTy) | ||||
9696 | return ICE->getSubExpr(); | ||||
9697 | |||||
9698 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; | ||||
9699 | return S.ImpCastExprToType(E, NewVecTy, Cast); | ||||
9700 | } | ||||
9701 | |||||
9702 | /// Test if a (constant) integer Int can be casted to another integer type | ||||
9703 | /// IntTy without losing precision. | ||||
9704 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, | ||||
9705 | QualType OtherIntTy) { | ||||
9706 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9707 | |||||
9708 | // Reject cases where the value of the Int is unknown as that would | ||||
9709 | // possibly cause truncation, but accept cases where the scalar can be | ||||
9710 | // demoted without loss of precision. | ||||
9711 | Expr::EvalResult EVResult; | ||||
9712 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9713 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); | ||||
9714 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); | ||||
9715 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); | ||||
9716 | |||||
9717 | if (CstInt) { | ||||
9718 | // If the scalar is constant and is of a higher order and has more active | ||||
9719 | // bits that the vector element type, reject it. | ||||
9720 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9721 | unsigned NumBits = IntSigned | ||||
9722 | ? (Result.isNegative() ? Result.getMinSignedBits() | ||||
9723 | : Result.getActiveBits()) | ||||
9724 | : Result.getActiveBits(); | ||||
9725 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) | ||||
9726 | return true; | ||||
9727 | |||||
9728 | // If the signedness of the scalar type and the vector element type | ||||
9729 | // differs and the number of bits is greater than that of the vector | ||||
9730 | // element reject it. | ||||
9731 | return (IntSigned != OtherIntSigned && | ||||
9732 | NumBits > S.Context.getIntWidth(OtherIntTy)); | ||||
9733 | } | ||||
9734 | |||||
9735 | // Reject cases where the value of the scalar is not constant and it's | ||||
9736 | // order is greater than that of the vector element type. | ||||
9737 | return (Order < 0); | ||||
9738 | } | ||||
9739 | |||||
9740 | /// Test if a (constant) integer Int can be casted to floating point type | ||||
9741 | /// FloatTy without losing precision. | ||||
9742 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, | ||||
9743 | QualType FloatTy) { | ||||
9744 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); | ||||
9745 | |||||
9746 | // Determine if the integer constant can be expressed as a floating point | ||||
9747 | // number of the appropriate type. | ||||
9748 | Expr::EvalResult EVResult; | ||||
9749 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); | ||||
9750 | |||||
9751 | uint64_t Bits = 0; | ||||
9752 | if (CstInt) { | ||||
9753 | // Reject constants that would be truncated if they were converted to | ||||
9754 | // the floating point type. Test by simple to/from conversion. | ||||
9755 | // FIXME: Ideally the conversion to an APFloat and from an APFloat | ||||
9756 | // could be avoided if there was a convertFromAPInt method | ||||
9757 | // which could signal back if implicit truncation occurred. | ||||
9758 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
9759 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); | ||||
9760 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), | ||||
9761 | llvm::APFloat::rmTowardZero); | ||||
9762 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), | ||||
9763 | !IntTy->hasSignedIntegerRepresentation()); | ||||
9764 | bool Ignored = false; | ||||
9765 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, | ||||
9766 | &Ignored); | ||||
9767 | if (Result != ConvertBack) | ||||
9768 | return true; | ||||
9769 | } else { | ||||
9770 | // Reject types that cannot be fully encoded into the mantissa of | ||||
9771 | // the float. | ||||
9772 | Bits = S.Context.getTypeSize(IntTy); | ||||
9773 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( | ||||
9774 | S.Context.getFloatTypeSemantics(FloatTy)); | ||||
9775 | if (Bits > FloatPrec) | ||||
9776 | return true; | ||||
9777 | } | ||||
9778 | |||||
9779 | return false; | ||||
9780 | } | ||||
9781 | |||||
9782 | /// Attempt to convert and splat Scalar into a vector whose types matches | ||||
9783 | /// Vector following GCC conversion rules. The rule is that implicit | ||||
9784 | /// conversion can occur when Scalar can be casted to match Vector's element | ||||
9785 | /// type without causing truncation of Scalar. | ||||
9786 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, | ||||
9787 | ExprResult *Vector) { | ||||
9788 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); | ||||
9789 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); | ||||
9790 | const VectorType *VT = VectorTy->getAs<VectorType>(); | ||||
9791 | |||||
9792 | assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 9793, __PRETTY_FUNCTION__)) | ||||
9793 | "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 9793, __PRETTY_FUNCTION__)); | ||||
9794 | |||||
9795 | QualType VectorEltTy = VT->getElementType(); | ||||
9796 | |||||
9797 | // Reject cases where the vector element type or the scalar element type are | ||||
9798 | // not integral or floating point types. | ||||
9799 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) | ||||
9800 | return true; | ||||
9801 | |||||
9802 | // The conversion to apply to the scalar before splatting it, | ||||
9803 | // if necessary. | ||||
9804 | CastKind ScalarCast = CK_NoOp; | ||||
9805 | |||||
9806 | // Accept cases where the vector elements are integers and the scalar is | ||||
9807 | // an integer. | ||||
9808 | // FIXME: Notionally if the scalar was a floating point value with a precise | ||||
9809 | // integral representation, we could cast it to an appropriate integer | ||||
9810 | // type and then perform the rest of the checks here. GCC will perform | ||||
9811 | // this conversion in some cases as determined by the input language. | ||||
9812 | // We should accept it on a language independent basis. | ||||
9813 | if (VectorEltTy->isIntegralType(S.Context) && | ||||
9814 | ScalarTy->isIntegralType(S.Context) && | ||||
9815 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { | ||||
9816 | |||||
9817 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) | ||||
9818 | return true; | ||||
9819 | |||||
9820 | ScalarCast = CK_IntegralCast; | ||||
9821 | } else if (VectorEltTy->isIntegralType(S.Context) && | ||||
9822 | ScalarTy->isRealFloatingType()) { | ||||
9823 | if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) | ||||
9824 | ScalarCast = CK_FloatingToIntegral; | ||||
9825 | else | ||||
9826 | return true; | ||||
9827 | } else if (VectorEltTy->isRealFloatingType()) { | ||||
9828 | if (ScalarTy->isRealFloatingType()) { | ||||
9829 | |||||
9830 | // Reject cases where the scalar type is not a constant and has a higher | ||||
9831 | // Order than the vector element type. | ||||
9832 | llvm::APFloat Result(0.0); | ||||
9833 | |||||
9834 | // Determine whether this is a constant scalar. In the event that the | ||||
9835 | // value is dependent (and thus cannot be evaluated by the constant | ||||
9836 | // evaluator), skip the evaluation. This will then diagnose once the | ||||
9837 | // expression is instantiated. | ||||
9838 | bool CstScalar = Scalar->get()->isValueDependent() || | ||||
9839 | Scalar->get()->EvaluateAsFloat(Result, S.Context); | ||||
9840 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); | ||||
9841 | if (!CstScalar && Order < 0) | ||||
9842 | return true; | ||||
9843 | |||||
9844 | // If the scalar cannot be safely casted to the vector element type, | ||||
9845 | // reject it. | ||||
9846 | if (CstScalar) { | ||||
9847 | bool Truncated = false; | ||||
9848 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), | ||||
9849 | llvm::APFloat::rmNearestTiesToEven, &Truncated); | ||||
9850 | if (Truncated) | ||||
9851 | return true; | ||||
9852 | } | ||||
9853 | |||||
9854 | ScalarCast = CK_FloatingCast; | ||||
9855 | } else if (ScalarTy->isIntegralType(S.Context)) { | ||||
9856 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) | ||||
9857 | return true; | ||||
9858 | |||||
9859 | ScalarCast = CK_IntegralToFloating; | ||||
9860 | } else | ||||
9861 | return true; | ||||
9862 | } else if (ScalarTy->isEnumeralType()) | ||||
9863 | return true; | ||||
9864 | |||||
9865 | // Adjust scalar if desired. | ||||
9866 | if (Scalar) { | ||||
9867 | if (ScalarCast != CK_NoOp) | ||||
9868 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); | ||||
9869 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); | ||||
9870 | } | ||||
9871 | return false; | ||||
9872 | } | ||||
9873 | |||||
9874 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | ||||
9875 | SourceLocation Loc, bool IsCompAssign, | ||||
9876 | bool AllowBothBool, | ||||
9877 | bool AllowBoolConversions) { | ||||
9878 | if (!IsCompAssign) { | ||||
9879 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
9880 | if (LHS.isInvalid()) | ||||
9881 | return QualType(); | ||||
9882 | } | ||||
9883 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
9884 | if (RHS.isInvalid()) | ||||
9885 | return QualType(); | ||||
9886 | |||||
9887 | // For conversion purposes, we ignore any qualifiers. | ||||
9888 | // For example, "const float" and "float" are equivalent. | ||||
9889 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
9890 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
9891 | |||||
9892 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); | ||||
9893 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); | ||||
9894 | assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail ("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 9894, __PRETTY_FUNCTION__)); | ||||
9895 | |||||
9896 | if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || | ||||
9897 | (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) | ||||
9898 | return InvalidOperands(Loc, LHS, RHS); | ||||
9899 | |||||
9900 | // AltiVec-style "vector bool op vector bool" combinations are allowed | ||||
9901 | // for some operators but not others. | ||||
9902 | if (!AllowBothBool && | ||||
9903 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
9904 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
9905 | return InvalidOperands(Loc, LHS, RHS); | ||||
9906 | |||||
9907 | // If the vector types are identical, return. | ||||
9908 | if (Context.hasSameType(LHSType, RHSType)) | ||||
9909 | return LHSType; | ||||
9910 | |||||
9911 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. | ||||
9912 | if (LHSVecType && RHSVecType && | ||||
9913 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { | ||||
9914 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
9915 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
9916 | return LHSType; | ||||
9917 | } | ||||
9918 | |||||
9919 | if (!IsCompAssign) | ||||
9920 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
9921 | return RHSType; | ||||
9922 | } | ||||
9923 | |||||
9924 | // AllowBoolConversions says that bool and non-bool AltiVec vectors | ||||
9925 | // can be mixed, with the result being the non-bool type. The non-bool | ||||
9926 | // operand must have integer element type. | ||||
9927 | if (AllowBoolConversions && LHSVecType && RHSVecType && | ||||
9928 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && | ||||
9929 | (Context.getTypeSize(LHSVecType->getElementType()) == | ||||
9930 | Context.getTypeSize(RHSVecType->getElementType()))) { | ||||
9931 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
9932 | LHSVecType->getElementType()->isIntegerType() && | ||||
9933 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { | ||||
9934 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
9935 | return LHSType; | ||||
9936 | } | ||||
9937 | if (!IsCompAssign && | ||||
9938 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && | ||||
9939 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && | ||||
9940 | RHSVecType->getElementType()->isIntegerType()) { | ||||
9941 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
9942 | return RHSType; | ||||
9943 | } | ||||
9944 | } | ||||
9945 | |||||
9946 | // Expressions containing fixed-length and sizeless SVE vectors are invalid | ||||
9947 | // since the ambiguity can affect the ABI. | ||||
9948 | auto IsSveConversion = [](QualType FirstType, QualType SecondType) { | ||||
9949 | const VectorType *VecType = SecondType->getAs<VectorType>(); | ||||
9950 | return FirstType->isSizelessBuiltinType() && VecType && | ||||
9951 | (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || | ||||
9952 | VecType->getVectorKind() == | ||||
9953 | VectorType::SveFixedLengthPredicateVector); | ||||
9954 | }; | ||||
9955 | |||||
9956 | if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { | ||||
9957 | Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; | ||||
9958 | return QualType(); | ||||
9959 | } | ||||
9960 | |||||
9961 | // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid | ||||
9962 | // since the ambiguity can affect the ABI. | ||||
9963 | auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { | ||||
9964 | const VectorType *FirstVecType = FirstType->getAs<VectorType>(); | ||||
9965 | const VectorType *SecondVecType = SecondType->getAs<VectorType>(); | ||||
9966 | |||||
9967 | if (FirstVecType && SecondVecType) | ||||
9968 | return FirstVecType->getVectorKind() == VectorType::GenericVector && | ||||
9969 | (SecondVecType->getVectorKind() == | ||||
9970 | VectorType::SveFixedLengthDataVector || | ||||
9971 | SecondVecType->getVectorKind() == | ||||
9972 | VectorType::SveFixedLengthPredicateVector); | ||||
9973 | |||||
9974 | return FirstType->isSizelessBuiltinType() && SecondVecType && | ||||
9975 | SecondVecType->getVectorKind() == VectorType::GenericVector; | ||||
9976 | }; | ||||
9977 | |||||
9978 | if (IsSveGnuConversion(LHSType, RHSType) || | ||||
9979 | IsSveGnuConversion(RHSType, LHSType)) { | ||||
9980 | Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; | ||||
9981 | return QualType(); | ||||
9982 | } | ||||
9983 | |||||
9984 | // If there's a vector type and a scalar, try to convert the scalar to | ||||
9985 | // the vector element type and splat. | ||||
9986 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; | ||||
9987 | if (!RHSVecType) { | ||||
9988 | if (isa<ExtVectorType>(LHSVecType)) { | ||||
9989 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, | ||||
9990 | LHSVecType->getElementType(), LHSType, | ||||
9991 | DiagID)) | ||||
9992 | return LHSType; | ||||
9993 | } else { | ||||
9994 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) | ||||
9995 | return LHSType; | ||||
9996 | } | ||||
9997 | } | ||||
9998 | if (!LHSVecType) { | ||||
9999 | if (isa<ExtVectorType>(RHSVecType)) { | ||||
10000 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), | ||||
10001 | LHSType, RHSVecType->getElementType(), | ||||
10002 | RHSType, DiagID)) | ||||
10003 | return RHSType; | ||||
10004 | } else { | ||||
10005 | if (LHS.get()->getValueKind() == VK_LValue || | ||||
10006 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) | ||||
10007 | return RHSType; | ||||
10008 | } | ||||
10009 | } | ||||
10010 | |||||
10011 | // FIXME: The code below also handles conversion between vectors and | ||||
10012 | // non-scalars, we should break this down into fine grained specific checks | ||||
10013 | // and emit proper diagnostics. | ||||
10014 | QualType VecType = LHSVecType ? LHSType : RHSType; | ||||
10015 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; | ||||
10016 | QualType OtherType = LHSVecType ? RHSType : LHSType; | ||||
10017 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; | ||||
10018 | if (isLaxVectorConversion(OtherType, VecType)) { | ||||
10019 | // If we're allowing lax vector conversions, only the total (data) size | ||||
10020 | // needs to be the same. For non compound assignment, if one of the types is | ||||
10021 | // scalar, the result is always the vector type. | ||||
10022 | if (!IsCompAssign) { | ||||
10023 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); | ||||
10024 | return VecType; | ||||
10025 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding | ||||
10026 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' | ||||
10027 | // type. Note that this is already done by non-compound assignments in | ||||
10028 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for | ||||
10029 | // <1 x T> -> T. The result is also a vector type. | ||||
10030 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || | ||||
10031 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { | ||||
10032 | ExprResult *RHSExpr = &RHS; | ||||
10033 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); | ||||
10034 | return VecType; | ||||
10035 | } | ||||
10036 | } | ||||
10037 | |||||
10038 | // Okay, the expression is invalid. | ||||
10039 | |||||
10040 | // If there's a non-vector, non-real operand, diagnose that. | ||||
10041 | if ((!RHSVecType && !RHSType->isRealType()) || | ||||
10042 | (!LHSVecType && !LHSType->isRealType())) { | ||||
10043 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) | ||||
10044 | << LHSType << RHSType | ||||
10045 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10046 | return QualType(); | ||||
10047 | } | ||||
10048 | |||||
10049 | // OpenCL V1.1 6.2.6.p1: | ||||
10050 | // If the operands are of more than one vector type, then an error shall | ||||
10051 | // occur. Implicit conversions between vector types are not permitted, per | ||||
10052 | // section 6.2.1. | ||||
10053 | if (getLangOpts().OpenCL && | ||||
10054 | RHSVecType && isa<ExtVectorType>(RHSVecType) && | ||||
10055 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { | ||||
10056 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType | ||||
10057 | << RHSType; | ||||
10058 | return QualType(); | ||||
10059 | } | ||||
10060 | |||||
10061 | |||||
10062 | // If there is a vector type that is not a ExtVector and a scalar, we reach | ||||
10063 | // this point if scalar could not be converted to the vector's element type | ||||
10064 | // without truncation. | ||||
10065 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || | ||||
10066 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { | ||||
10067 | QualType Scalar = LHSVecType ? RHSType : LHSType; | ||||
10068 | QualType Vector = LHSVecType ? LHSType : RHSType; | ||||
10069 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; | ||||
10070 | Diag(Loc, | ||||
10071 | diag::err_typecheck_vector_not_convertable_implict_truncation) | ||||
10072 | << ScalarOrVector << Scalar << Vector; | ||||
10073 | |||||
10074 | return QualType(); | ||||
10075 | } | ||||
10076 | |||||
10077 | // Otherwise, use the generic diagnostic. | ||||
10078 | Diag(Loc, DiagID) | ||||
10079 | << LHSType << RHSType | ||||
10080 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10081 | return QualType(); | ||||
10082 | } | ||||
10083 | |||||
10084 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an | ||||
10085 | // expression. These are mainly cases where the null pointer is used as an | ||||
10086 | // integer instead of a pointer. | ||||
10087 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10088 | SourceLocation Loc, bool IsCompare) { | ||||
10089 | // The canonical way to check for a GNU null is with isNullPointerConstant, | ||||
10090 | // but we use a bit of a hack here for speed; this is a relatively | ||||
10091 | // hot path, and isNullPointerConstant is slow. | ||||
10092 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); | ||||
10093 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); | ||||
10094 | |||||
10095 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); | ||||
10096 | |||||
10097 | // Avoid analyzing cases where the result will either be invalid (and | ||||
10098 | // diagnosed as such) or entirely valid and not something to warn about. | ||||
10099 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || | ||||
10100 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) | ||||
10101 | return; | ||||
10102 | |||||
10103 | // Comparison operations would not make sense with a null pointer no matter | ||||
10104 | // what the other expression is. | ||||
10105 | if (!IsCompare) { | ||||
10106 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) | ||||
10107 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) | ||||
10108 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); | ||||
10109 | return; | ||||
10110 | } | ||||
10111 | |||||
10112 | // The rest of the operations only make sense with a null pointer | ||||
10113 | // if the other expression is a pointer. | ||||
10114 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || | ||||
10115 | NonNullType->canDecayToPointerType()) | ||||
10116 | return; | ||||
10117 | |||||
10118 | S.Diag(Loc, diag::warn_null_in_comparison_operation) | ||||
10119 | << LHSNull /* LHS is NULL */ << NonNullType | ||||
10120 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10121 | } | ||||
10122 | |||||
10123 | static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, | ||||
10124 | SourceLocation Loc) { | ||||
10125 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); | ||||
10126 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); | ||||
10127 | if (!LUE || !RUE) | ||||
10128 | return; | ||||
10129 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || | ||||
10130 | RUE->getKind() != UETT_SizeOf) | ||||
10131 | return; | ||||
10132 | |||||
10133 | const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); | ||||
10134 | QualType LHSTy = LHSArg->getType(); | ||||
10135 | QualType RHSTy; | ||||
10136 | |||||
10137 | if (RUE->isArgumentType()) | ||||
10138 | RHSTy = RUE->getArgumentType().getNonReferenceType(); | ||||
10139 | else | ||||
10140 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); | ||||
10141 | |||||
10142 | if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { | ||||
10143 | if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) | ||||
10144 | return; | ||||
10145 | |||||
10146 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); | ||||
10147 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10148 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10149 | S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) | ||||
10150 | << LHSArgDecl; | ||||
10151 | } | ||||
10152 | } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { | ||||
10153 | QualType ArrayElemTy = ArrayTy->getElementType(); | ||||
10154 | if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || | ||||
10155 | ArrayElemTy->isDependentType() || RHSTy->isDependentType() || | ||||
10156 | RHSTy->isReferenceType() || ArrayElemTy->isCharType() || | ||||
10157 | S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) | ||||
10158 | return; | ||||
10159 | S.Diag(Loc, diag::warn_division_sizeof_array) | ||||
10160 | << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; | ||||
10161 | if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { | ||||
10162 | if (const ValueDecl *LHSArgDecl = DRE->getDecl()) | ||||
10163 | S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) | ||||
10164 | << LHSArgDecl; | ||||
10165 | } | ||||
10166 | |||||
10167 | S.Diag(Loc, diag::note_precedence_silence) << RHS; | ||||
10168 | } | ||||
10169 | } | ||||
10170 | |||||
10171 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, | ||||
10172 | ExprResult &RHS, | ||||
10173 | SourceLocation Loc, bool IsDiv) { | ||||
10174 | // Check for division/remainder by zero. | ||||
10175 | Expr::EvalResult RHSValue; | ||||
10176 | if (!RHS.get()->isValueDependent() && | ||||
10177 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && | ||||
10178 | RHSValue.Val.getInt() == 0) | ||||
10179 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10180 | S.PDiag(diag::warn_remainder_division_by_zero) | ||||
10181 | << IsDiv << RHS.get()->getSourceRange()); | ||||
10182 | } | ||||
10183 | |||||
10184 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10185 | SourceLocation Loc, | ||||
10186 | bool IsCompAssign, bool IsDiv) { | ||||
10187 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10188 | |||||
10189 | if (LHS.get()->getType()->isVectorType() || | ||||
10190 | RHS.get()->getType()->isVectorType()) | ||||
10191 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10192 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10193 | /*AllowBoolConversions*/false); | ||||
10194 | if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || | ||||
10195 | RHS.get()->getType()->isConstantMatrixType())) | ||||
10196 | return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); | ||||
10197 | |||||
10198 | QualType compType = UsualArithmeticConversions( | ||||
10199 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10200 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10201 | return QualType(); | ||||
10202 | |||||
10203 | |||||
10204 | if (compType.isNull() || !compType->isArithmeticType()) | ||||
10205 | return InvalidOperands(Loc, LHS, RHS); | ||||
10206 | if (IsDiv) { | ||||
10207 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); | ||||
10208 | DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); | ||||
10209 | } | ||||
10210 | return compType; | ||||
10211 | } | ||||
10212 | |||||
10213 | QualType Sema::CheckRemainderOperands( | ||||
10214 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { | ||||
10215 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10216 | |||||
10217 | if (LHS.get()->getType()->isVectorType() || | ||||
10218 | RHS.get()->getType()->isVectorType()) { | ||||
10219 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
10220 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
10221 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
10222 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10223 | /*AllowBoolConversions*/false); | ||||
10224 | return InvalidOperands(Loc, LHS, RHS); | ||||
10225 | } | ||||
10226 | |||||
10227 | QualType compType = UsualArithmeticConversions( | ||||
10228 | LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); | ||||
10229 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10230 | return QualType(); | ||||
10231 | |||||
10232 | if (compType.isNull() || !compType->isIntegerType()) | ||||
10233 | return InvalidOperands(Loc, LHS, RHS); | ||||
10234 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); | ||||
10235 | return compType; | ||||
10236 | } | ||||
10237 | |||||
10238 | /// Diagnose invalid arithmetic on two void pointers. | ||||
10239 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, | ||||
10240 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10241 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10242 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10243 | : diag::ext_gnu_void_ptr) | ||||
10244 | << 1 /* two pointers */ << LHSExpr->getSourceRange() | ||||
10245 | << RHSExpr->getSourceRange(); | ||||
10246 | } | ||||
10247 | |||||
10248 | /// Diagnose invalid arithmetic on a void pointer. | ||||
10249 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, | ||||
10250 | Expr *Pointer) { | ||||
10251 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10252 | ? diag::err_typecheck_pointer_arith_void_type | ||||
10253 | : diag::ext_gnu_void_ptr) | ||||
10254 | << 0 /* one pointer */ << Pointer->getSourceRange(); | ||||
10255 | } | ||||
10256 | |||||
10257 | /// Diagnose invalid arithmetic on a null pointer. | ||||
10258 | /// | ||||
10259 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' | ||||
10260 | /// idiom, which we recognize as a GNU extension. | ||||
10261 | /// | ||||
10262 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, | ||||
10263 | Expr *Pointer, bool IsGNUIdiom) { | ||||
10264 | if (IsGNUIdiom) | ||||
10265 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) | ||||
10266 | << Pointer->getSourceRange(); | ||||
10267 | else | ||||
10268 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) | ||||
10269 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); | ||||
10270 | } | ||||
10271 | |||||
10272 | /// Diagnose invalid arithmetic on two function pointers. | ||||
10273 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, | ||||
10274 | Expr *LHS, Expr *RHS) { | ||||
10275 | assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10275, __PRETTY_FUNCTION__)); | ||||
10276 | assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10276, __PRETTY_FUNCTION__)); | ||||
10277 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10278 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10279 | : diag::ext_gnu_ptr_func_arith) | ||||
10280 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() | ||||
10281 | // We only show the second type if it differs from the first. | ||||
10282 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), | ||||
10283 | RHS->getType()) | ||||
10284 | << RHS->getType()->getPointeeType() | ||||
10285 | << LHS->getSourceRange() << RHS->getSourceRange(); | ||||
10286 | } | ||||
10287 | |||||
10288 | /// Diagnose invalid arithmetic on a function pointer. | ||||
10289 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, | ||||
10290 | Expr *Pointer) { | ||||
10291 | assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10291, __PRETTY_FUNCTION__)); | ||||
10292 | S.Diag(Loc, S.getLangOpts().CPlusPlus | ||||
10293 | ? diag::err_typecheck_pointer_arith_function_type | ||||
10294 | : diag::ext_gnu_ptr_func_arith) | ||||
10295 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() | ||||
10296 | << 0 /* one pointer, so only one type */ | ||||
10297 | << Pointer->getSourceRange(); | ||||
10298 | } | ||||
10299 | |||||
10300 | /// Emit error if Operand is incomplete pointer type | ||||
10301 | /// | ||||
10302 | /// \returns True if pointer has incomplete type | ||||
10303 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, | ||||
10304 | Expr *Operand) { | ||||
10305 | QualType ResType = Operand->getType(); | ||||
10306 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10307 | ResType = ResAtomicType->getValueType(); | ||||
10308 | |||||
10309 | assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType ()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10309, __PRETTY_FUNCTION__)); | ||||
10310 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10311 | return S.RequireCompleteSizedType( | ||||
10312 | Loc, PointeeTy, | ||||
10313 | diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, | ||||
10314 | Operand->getSourceRange()); | ||||
10315 | } | ||||
10316 | |||||
10317 | /// Check the validity of an arithmetic pointer operand. | ||||
10318 | /// | ||||
10319 | /// If the operand has pointer type, this code will check for pointer types | ||||
10320 | /// which are invalid in arithmetic operations. These will be diagnosed | ||||
10321 | /// appropriately, including whether or not the use is supported as an | ||||
10322 | /// extension. | ||||
10323 | /// | ||||
10324 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10325 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, | ||||
10326 | Expr *Operand) { | ||||
10327 | QualType ResType = Operand->getType(); | ||||
10328 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
10329 | ResType = ResAtomicType->getValueType(); | ||||
10330 | |||||
10331 | if (!ResType->isAnyPointerType()) return true; | ||||
10332 | |||||
10333 | QualType PointeeTy = ResType->getPointeeType(); | ||||
10334 | if (PointeeTy->isVoidType()) { | ||||
10335 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); | ||||
10336 | return !S.getLangOpts().CPlusPlus; | ||||
10337 | } | ||||
10338 | if (PointeeTy->isFunctionType()) { | ||||
10339 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); | ||||
10340 | return !S.getLangOpts().CPlusPlus; | ||||
10341 | } | ||||
10342 | |||||
10343 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; | ||||
10344 | |||||
10345 | return true; | ||||
10346 | } | ||||
10347 | |||||
10348 | /// Check the validity of a binary arithmetic operation w.r.t. pointer | ||||
10349 | /// operands. | ||||
10350 | /// | ||||
10351 | /// This routine will diagnose any invalid arithmetic on pointer operands much | ||||
10352 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic | ||||
10353 | /// for emitting a single diagnostic even for operations where both LHS and RHS | ||||
10354 | /// are (potentially problematic) pointers. | ||||
10355 | /// | ||||
10356 | /// \returns True when the operand is valid to use (even if as an extension). | ||||
10357 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, | ||||
10358 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10359 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); | ||||
10360 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); | ||||
10361 | if (!isLHSPointer && !isRHSPointer) return true; | ||||
10362 | |||||
10363 | QualType LHSPointeeTy, RHSPointeeTy; | ||||
10364 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); | ||||
10365 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); | ||||
10366 | |||||
10367 | // if both are pointers check if operation is valid wrt address spaces | ||||
10368 | if (isLHSPointer && isRHSPointer) { | ||||
10369 | if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { | ||||
10370 | S.Diag(Loc, | ||||
10371 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
10372 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ | ||||
10373 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); | ||||
10374 | return false; | ||||
10375 | } | ||||
10376 | } | ||||
10377 | |||||
10378 | // Check for arithmetic on pointers to incomplete types. | ||||
10379 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); | ||||
10380 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); | ||||
10381 | if (isLHSVoidPtr || isRHSVoidPtr) { | ||||
10382 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); | ||||
10383 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); | ||||
10384 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10385 | |||||
10386 | return !S.getLangOpts().CPlusPlus; | ||||
10387 | } | ||||
10388 | |||||
10389 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); | ||||
10390 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); | ||||
10391 | if (isLHSFuncPtr || isRHSFuncPtr) { | ||||
10392 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); | ||||
10393 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, | ||||
10394 | RHSExpr); | ||||
10395 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); | ||||
10396 | |||||
10397 | return !S.getLangOpts().CPlusPlus; | ||||
10398 | } | ||||
10399 | |||||
10400 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) | ||||
10401 | return false; | ||||
10402 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) | ||||
10403 | return false; | ||||
10404 | |||||
10405 | return true; | ||||
10406 | } | ||||
10407 | |||||
10408 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string | ||||
10409 | /// literal. | ||||
10410 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, | ||||
10411 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10412 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10413 | Expr* IndexExpr = RHSExpr; | ||||
10414 | if (!StrExpr) { | ||||
10415 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10416 | IndexExpr = LHSExpr; | ||||
10417 | } | ||||
10418 | |||||
10419 | bool IsStringPlusInt = StrExpr && | ||||
10420 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); | ||||
10421 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) | ||||
10422 | return; | ||||
10423 | |||||
10424 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10425 | Self.Diag(OpLoc, diag::warn_string_plus_int) | ||||
10426 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); | ||||
10427 | |||||
10428 | // Only print a fixit for "str" + int, not for int + "str". | ||||
10429 | if (IndexExpr == RHSExpr) { | ||||
10430 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10431 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10432 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10433 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10434 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10435 | } else | ||||
10436 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10437 | } | ||||
10438 | |||||
10439 | /// Emit a warning when adding a char literal to a string. | ||||
10440 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, | ||||
10441 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10442 | const Expr *StringRefExpr = LHSExpr; | ||||
10443 | const CharacterLiteral *CharExpr = | ||||
10444 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); | ||||
10445 | |||||
10446 | if (!CharExpr) { | ||||
10447 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); | ||||
10448 | StringRefExpr = RHSExpr; | ||||
10449 | } | ||||
10450 | |||||
10451 | if (!CharExpr || !StringRefExpr) | ||||
10452 | return; | ||||
10453 | |||||
10454 | const QualType StringType = StringRefExpr->getType(); | ||||
10455 | |||||
10456 | // Return if not a PointerType. | ||||
10457 | if (!StringType->isAnyPointerType()) | ||||
10458 | return; | ||||
10459 | |||||
10460 | // Return if not a CharacterType. | ||||
10461 | if (!StringType->getPointeeType()->isAnyCharacterType()) | ||||
10462 | return; | ||||
10463 | |||||
10464 | ASTContext &Ctx = Self.getASTContext(); | ||||
10465 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
10466 | |||||
10467 | const QualType CharType = CharExpr->getType(); | ||||
10468 | if (!CharType->isAnyCharacterType() && | ||||
10469 | CharType->isIntegerType() && | ||||
10470 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { | ||||
10471 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10472 | << DiagRange << Ctx.CharTy; | ||||
10473 | } else { | ||||
10474 | Self.Diag(OpLoc, diag::warn_string_plus_char) | ||||
10475 | << DiagRange << CharExpr->getType(); | ||||
10476 | } | ||||
10477 | |||||
10478 | // Only print a fixit for str + char, not for char + str. | ||||
10479 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { | ||||
10480 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); | ||||
10481 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) | ||||
10482 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") | ||||
10483 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") | ||||
10484 | << FixItHint::CreateInsertion(EndLoc, "]"); | ||||
10485 | } else { | ||||
10486 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); | ||||
10487 | } | ||||
10488 | } | ||||
10489 | |||||
10490 | /// Emit error when two pointers are incompatible. | ||||
10491 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, | ||||
10492 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
10493 | assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10493, __PRETTY_FUNCTION__)); | ||||
10494 | assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast <void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10494, __PRETTY_FUNCTION__)); | ||||
10495 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) | ||||
10496 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() | ||||
10497 | << RHSExpr->getSourceRange(); | ||||
10498 | } | ||||
10499 | |||||
10500 | // C99 6.5.6 | ||||
10501 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10502 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10503 | QualType* CompLHSTy) { | ||||
10504 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10505 | |||||
10506 | if (LHS.get()->getType()->isVectorType() || | ||||
10507 | RHS.get()->getType()->isVectorType()) { | ||||
10508 | QualType compType = CheckVectorOperands( | ||||
10509 | LHS, RHS, Loc, CompLHSTy, | ||||
10510 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10511 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10512 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10513 | return compType; | ||||
10514 | } | ||||
10515 | |||||
10516 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10517 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10518 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10519 | } | ||||
10520 | |||||
10521 | QualType compType = UsualArithmeticConversions( | ||||
10522 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10523 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10524 | return QualType(); | ||||
10525 | |||||
10526 | // Diagnose "string literal" '+' int and string '+' "char literal". | ||||
10527 | if (Opc == BO_Add) { | ||||
10528 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); | ||||
10529 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); | ||||
10530 | } | ||||
10531 | |||||
10532 | // handle the common case first (both operands are arithmetic). | ||||
10533 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10534 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10535 | return compType; | ||||
10536 | } | ||||
10537 | |||||
10538 | // Type-checking. Ultimately the pointer's going to be in PExp; | ||||
10539 | // note that we bias towards the LHS being the pointer. | ||||
10540 | Expr *PExp = LHS.get(), *IExp = RHS.get(); | ||||
10541 | |||||
10542 | bool isObjCPointer; | ||||
10543 | if (PExp->getType()->isPointerType()) { | ||||
10544 | isObjCPointer = false; | ||||
10545 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10546 | isObjCPointer = true; | ||||
10547 | } else { | ||||
10548 | std::swap(PExp, IExp); | ||||
10549 | if (PExp->getType()->isPointerType()) { | ||||
10550 | isObjCPointer = false; | ||||
10551 | } else if (PExp->getType()->isObjCObjectPointerType()) { | ||||
10552 | isObjCPointer = true; | ||||
10553 | } else { | ||||
10554 | return InvalidOperands(Loc, LHS, RHS); | ||||
10555 | } | ||||
10556 | } | ||||
10557 | assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast< void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10557, __PRETTY_FUNCTION__)); | ||||
10558 | |||||
10559 | if (!IExp->getType()->isIntegerType()) | ||||
10560 | return InvalidOperands(Loc, LHS, RHS); | ||||
10561 | |||||
10562 | // Adding to a null pointer results in undefined behavior. | ||||
10563 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( | ||||
10564 | Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||
10565 | // In C++ adding zero to a null pointer is defined. | ||||
10566 | Expr::EvalResult KnownVal; | ||||
10567 | if (!getLangOpts().CPlusPlus || | ||||
10568 | (!IExp->isValueDependent() && | ||||
10569 | (!IExp->EvaluateAsInt(KnownVal, Context) || | ||||
10570 | KnownVal.Val.getInt() != 0))) { | ||||
10571 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. | ||||
10572 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( | ||||
10573 | Context, BO_Add, PExp, IExp); | ||||
10574 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); | ||||
10575 | } | ||||
10576 | } | ||||
10577 | |||||
10578 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) | ||||
10579 | return QualType(); | ||||
10580 | |||||
10581 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) | ||||
10582 | return QualType(); | ||||
10583 | |||||
10584 | // Check array bounds for pointer arithemtic | ||||
10585 | CheckArrayAccess(PExp, IExp); | ||||
10586 | |||||
10587 | if (CompLHSTy) { | ||||
10588 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); | ||||
10589 | if (LHSTy.isNull()) { | ||||
10590 | LHSTy = LHS.get()->getType(); | ||||
10591 | if (LHSTy->isPromotableIntegerType()) | ||||
10592 | LHSTy = Context.getPromotedIntegerType(LHSTy); | ||||
10593 | } | ||||
10594 | *CompLHSTy = LHSTy; | ||||
10595 | } | ||||
10596 | |||||
10597 | return PExp->getType(); | ||||
10598 | } | ||||
10599 | |||||
10600 | // C99 6.5.6 | ||||
10601 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10602 | SourceLocation Loc, | ||||
10603 | QualType* CompLHSTy) { | ||||
10604 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10605 | |||||
10606 | if (LHS.get()->getType()->isVectorType() || | ||||
10607 | RHS.get()->getType()->isVectorType()) { | ||||
10608 | QualType compType = CheckVectorOperands( | ||||
10609 | LHS, RHS, Loc, CompLHSTy, | ||||
10610 | /*AllowBothBool*/getLangOpts().AltiVec, | ||||
10611 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
10612 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10613 | return compType; | ||||
10614 | } | ||||
10615 | |||||
10616 | if (LHS.get()->getType()->isConstantMatrixType() || | ||||
10617 | RHS.get()->getType()->isConstantMatrixType()) { | ||||
10618 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); | ||||
10619 | } | ||||
10620 | |||||
10621 | QualType compType = UsualArithmeticConversions( | ||||
10622 | LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); | ||||
10623 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
10624 | return QualType(); | ||||
10625 | |||||
10626 | // Enforce type constraints: C99 6.5.6p3. | ||||
10627 | |||||
10628 | // Handle the common case first (both operands are arithmetic). | ||||
10629 | if (!compType.isNull() && compType->isArithmeticType()) { | ||||
10630 | if (CompLHSTy) *CompLHSTy = compType; | ||||
10631 | return compType; | ||||
10632 | } | ||||
10633 | |||||
10634 | // Either ptr - int or ptr - ptr. | ||||
10635 | if (LHS.get()->getType()->isAnyPointerType()) { | ||||
10636 | QualType lpointee = LHS.get()->getType()->getPointeeType(); | ||||
10637 | |||||
10638 | // Diagnose bad cases where we step over interface counts. | ||||
10639 | if (LHS.get()->getType()->isObjCObjectPointerType() && | ||||
10640 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) | ||||
10641 | return QualType(); | ||||
10642 | |||||
10643 | // The result type of a pointer-int computation is the pointer type. | ||||
10644 | if (RHS.get()->getType()->isIntegerType()) { | ||||
10645 | // Subtracting from a null pointer should produce a warning. | ||||
10646 | // The last argument to the diagnose call says this doesn't match the | ||||
10647 | // GNU int-to-pointer idiom. | ||||
10648 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, | ||||
10649 | Expr::NPC_ValueDependentIsNotNull)) { | ||||
10650 | // In C++ adding zero to a null pointer is defined. | ||||
10651 | Expr::EvalResult KnownVal; | ||||
10652 | if (!getLangOpts().CPlusPlus || | ||||
10653 | (!RHS.get()->isValueDependent() && | ||||
10654 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || | ||||
10655 | KnownVal.Val.getInt() != 0))) { | ||||
10656 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); | ||||
10657 | } | ||||
10658 | } | ||||
10659 | |||||
10660 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) | ||||
10661 | return QualType(); | ||||
10662 | |||||
10663 | // Check array bounds for pointer arithemtic | ||||
10664 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, | ||||
10665 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); | ||||
10666 | |||||
10667 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10668 | return LHS.get()->getType(); | ||||
10669 | } | ||||
10670 | |||||
10671 | // Handle pointer-pointer subtractions. | ||||
10672 | if (const PointerType *RHSPTy | ||||
10673 | = RHS.get()->getType()->getAs<PointerType>()) { | ||||
10674 | QualType rpointee = RHSPTy->getPointeeType(); | ||||
10675 | |||||
10676 | if (getLangOpts().CPlusPlus) { | ||||
10677 | // Pointee types must be the same: C++ [expr.add] | ||||
10678 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { | ||||
10679 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10680 | } | ||||
10681 | } else { | ||||
10682 | // Pointee types must be compatible C99 6.5.6p3 | ||||
10683 | if (!Context.typesAreCompatible( | ||||
10684 | Context.getCanonicalType(lpointee).getUnqualifiedType(), | ||||
10685 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { | ||||
10686 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); | ||||
10687 | return QualType(); | ||||
10688 | } | ||||
10689 | } | ||||
10690 | |||||
10691 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, | ||||
10692 | LHS.get(), RHS.get())) | ||||
10693 | return QualType(); | ||||
10694 | |||||
10695 | // FIXME: Add warnings for nullptr - ptr. | ||||
10696 | |||||
10697 | // The pointee type may have zero size. As an extension, a structure or | ||||
10698 | // union may have zero size or an array may have zero length. In this | ||||
10699 | // case subtraction does not make sense. | ||||
10700 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { | ||||
10701 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); | ||||
10702 | if (ElementSize.isZero()) { | ||||
10703 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) | ||||
10704 | << rpointee.getUnqualifiedType() | ||||
10705 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10706 | } | ||||
10707 | } | ||||
10708 | |||||
10709 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); | ||||
10710 | return Context.getPointerDiffType(); | ||||
10711 | } | ||||
10712 | } | ||||
10713 | |||||
10714 | return InvalidOperands(Loc, LHS, RHS); | ||||
10715 | } | ||||
10716 | |||||
10717 | static bool isScopedEnumerationType(QualType T) { | ||||
10718 | if (const EnumType *ET = T->getAs<EnumType>()) | ||||
10719 | return ET->getDecl()->isScoped(); | ||||
10720 | return false; | ||||
10721 | } | ||||
10722 | |||||
10723 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, | ||||
10724 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10725 | QualType LHSType) { | ||||
10726 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), | ||||
10727 | // so skip remaining warnings as we don't want to modify values within Sema. | ||||
10728 | if (S.getLangOpts().OpenCL) | ||||
10729 | return; | ||||
10730 | |||||
10731 | // Check right/shifter operand | ||||
10732 | Expr::EvalResult RHSResult; | ||||
10733 | if (RHS.get()->isValueDependent() || | ||||
10734 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) | ||||
10735 | return; | ||||
10736 | llvm::APSInt Right = RHSResult.Val.getInt(); | ||||
10737 | |||||
10738 | if (Right.isNegative()) { | ||||
10739 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10740 | S.PDiag(diag::warn_shift_negative) | ||||
10741 | << RHS.get()->getSourceRange()); | ||||
10742 | return; | ||||
10743 | } | ||||
10744 | |||||
10745 | QualType LHSExprType = LHS.get()->getType(); | ||||
10746 | uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); | ||||
10747 | if (LHSExprType->isExtIntType()) | ||||
10748 | LeftSize = S.Context.getIntWidth(LHSExprType); | ||||
10749 | else if (LHSExprType->isFixedPointType()) { | ||||
10750 | auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); | ||||
10751 | LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); | ||||
10752 | } | ||||
10753 | llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); | ||||
10754 | if (Right.uge(LeftBits)) { | ||||
10755 | S.DiagRuntimeBehavior(Loc, RHS.get(), | ||||
10756 | S.PDiag(diag::warn_shift_gt_typewidth) | ||||
10757 | << RHS.get()->getSourceRange()); | ||||
10758 | return; | ||||
10759 | } | ||||
10760 | |||||
10761 | // FIXME: We probably need to handle fixed point types specially here. | ||||
10762 | if (Opc != BO_Shl || LHSExprType->isFixedPointType()) | ||||
10763 | return; | ||||
10764 | |||||
10765 | // When left shifting an ICE which is signed, we can check for overflow which | ||||
10766 | // according to C++ standards prior to C++2a has undefined behavior | ||||
10767 | // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one | ||||
10768 | // more than the maximum value representable in the result type, so never | ||||
10769 | // warn for those. (FIXME: Unsigned left-shift overflow in a constant | ||||
10770 | // expression is still probably a bug.) | ||||
10771 | Expr::EvalResult LHSResult; | ||||
10772 | if (LHS.get()->isValueDependent() || | ||||
10773 | LHSType->hasUnsignedIntegerRepresentation() || | ||||
10774 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) | ||||
10775 | return; | ||||
10776 | llvm::APSInt Left = LHSResult.Val.getInt(); | ||||
10777 | |||||
10778 | // If LHS does not have a signed type and non-negative value | ||||
10779 | // then, the behavior is undefined before C++2a. Warn about it. | ||||
10780 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && | ||||
10781 | !S.getLangOpts().CPlusPlus20) { | ||||
10782 | S.DiagRuntimeBehavior(Loc, LHS.get(), | ||||
10783 | S.PDiag(diag::warn_shift_lhs_negative) | ||||
10784 | << LHS.get()->getSourceRange()); | ||||
10785 | return; | ||||
10786 | } | ||||
10787 | |||||
10788 | llvm::APInt ResultBits = | ||||
10789 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); | ||||
10790 | if (LeftBits.uge(ResultBits)) | ||||
10791 | return; | ||||
10792 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); | ||||
10793 | Result = Result.shl(Right); | ||||
10794 | |||||
10795 | // Print the bit representation of the signed integer as an unsigned | ||||
10796 | // hexadecimal number. | ||||
10797 | SmallString<40> HexResult; | ||||
10798 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); | ||||
10799 | |||||
10800 | // If we are only missing a sign bit, this is less likely to result in actual | ||||
10801 | // bugs -- if the result is cast back to an unsigned type, it will have the | ||||
10802 | // expected value. Thus we place this behind a different warning that can be | ||||
10803 | // turned off separately if needed. | ||||
10804 | if (LeftBits == ResultBits - 1) { | ||||
10805 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) | ||||
10806 | << HexResult << LHSType | ||||
10807 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10808 | return; | ||||
10809 | } | ||||
10810 | |||||
10811 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) | ||||
10812 | << HexResult.str() << Result.getMinSignedBits() << LHSType | ||||
10813 | << Left.getBitWidth() << LHS.get()->getSourceRange() | ||||
10814 | << RHS.get()->getSourceRange(); | ||||
10815 | } | ||||
10816 | |||||
10817 | /// Return the resulting type when a vector is shifted | ||||
10818 | /// by a scalar or vector shift amount. | ||||
10819 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
10820 | SourceLocation Loc, bool IsCompAssign) { | ||||
10821 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. | ||||
10822 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && | ||||
10823 | !LHS.get()->getType()->isVectorType()) { | ||||
10824 | S.Diag(Loc, diag::err_shift_rhs_only_vector) | ||||
10825 | << RHS.get()->getType() << LHS.get()->getType() | ||||
10826 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10827 | return QualType(); | ||||
10828 | } | ||||
10829 | |||||
10830 | if (!IsCompAssign) { | ||||
10831 | LHS = S.UsualUnaryConversions(LHS.get()); | ||||
10832 | if (LHS.isInvalid()) return QualType(); | ||||
10833 | } | ||||
10834 | |||||
10835 | RHS = S.UsualUnaryConversions(RHS.get()); | ||||
10836 | if (RHS.isInvalid()) return QualType(); | ||||
10837 | |||||
10838 | QualType LHSType = LHS.get()->getType(); | ||||
10839 | // Note that LHS might be a scalar because the routine calls not only in | ||||
10840 | // OpenCL case. | ||||
10841 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); | ||||
10842 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; | ||||
10843 | |||||
10844 | // Note that RHS might not be a vector. | ||||
10845 | QualType RHSType = RHS.get()->getType(); | ||||
10846 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); | ||||
10847 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; | ||||
10848 | |||||
10849 | // The operands need to be integers. | ||||
10850 | if (!LHSEleType->isIntegerType()) { | ||||
10851 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
10852 | << LHS.get()->getType() << LHS.get()->getSourceRange(); | ||||
10853 | return QualType(); | ||||
10854 | } | ||||
10855 | |||||
10856 | if (!RHSEleType->isIntegerType()) { | ||||
10857 | S.Diag(Loc, diag::err_typecheck_expect_int) | ||||
10858 | << RHS.get()->getType() << RHS.get()->getSourceRange(); | ||||
10859 | return QualType(); | ||||
10860 | } | ||||
10861 | |||||
10862 | if (!LHSVecTy) { | ||||
10863 | assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10863, __PRETTY_FUNCTION__)); | ||||
10864 | if (IsCompAssign) | ||||
10865 | return RHSType; | ||||
10866 | if (LHSEleType != RHSEleType) { | ||||
10867 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); | ||||
10868 | LHSEleType = RHSEleType; | ||||
10869 | } | ||||
10870 | QualType VecTy = | ||||
10871 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); | ||||
10872 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); | ||||
10873 | LHSType = VecTy; | ||||
10874 | } else if (RHSVecTy) { | ||||
10875 | // OpenCL v1.1 s6.3.j says that for vector types, the operators | ||||
10876 | // are applied component-wise. So if RHS is a vector, then ensure | ||||
10877 | // that the number of elements is the same as LHS... | ||||
10878 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { | ||||
10879 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) | ||||
10880 | << LHS.get()->getType() << RHS.get()->getType() | ||||
10881 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10882 | return QualType(); | ||||
10883 | } | ||||
10884 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { | ||||
10885 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); | ||||
10886 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); | ||||
10887 | if (LHSBT != RHSBT && | ||||
10888 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { | ||||
10889 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) | ||||
10890 | << LHS.get()->getType() << RHS.get()->getType() | ||||
10891 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10892 | } | ||||
10893 | } | ||||
10894 | } else { | ||||
10895 | // ...else expand RHS to match the number of elements in LHS. | ||||
10896 | QualType VecTy = | ||||
10897 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); | ||||
10898 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); | ||||
10899 | } | ||||
10900 | |||||
10901 | return LHSType; | ||||
10902 | } | ||||
10903 | |||||
10904 | // C99 6.5.7 | ||||
10905 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, | ||||
10906 | SourceLocation Loc, BinaryOperatorKind Opc, | ||||
10907 | bool IsCompAssign) { | ||||
10908 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
10909 | |||||
10910 | // Vector shifts promote their scalar inputs to vector type. | ||||
10911 | if (LHS.get()->getType()->isVectorType() || | ||||
10912 | RHS.get()->getType()->isVectorType()) { | ||||
10913 | if (LangOpts.ZVector) { | ||||
10914 | // The shift operators for the z vector extensions work basically | ||||
10915 | // like general shifts, except that neither the LHS nor the RHS is | ||||
10916 | // allowed to be a "vector bool". | ||||
10917 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) | ||||
10918 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10919 | return InvalidOperands(Loc, LHS, RHS); | ||||
10920 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) | ||||
10921 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) | ||||
10922 | return InvalidOperands(Loc, LHS, RHS); | ||||
10923 | } | ||||
10924 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); | ||||
10925 | } | ||||
10926 | |||||
10927 | // Shifts don't perform usual arithmetic conversions, they just do integer | ||||
10928 | // promotions on each operand. C99 6.5.7p3 | ||||
10929 | |||||
10930 | // For the LHS, do usual unary conversions, but then reset them away | ||||
10931 | // if this is a compound assignment. | ||||
10932 | ExprResult OldLHS = LHS; | ||||
10933 | LHS = UsualUnaryConversions(LHS.get()); | ||||
10934 | if (LHS.isInvalid()) | ||||
10935 | return QualType(); | ||||
10936 | QualType LHSType = LHS.get()->getType(); | ||||
10937 | if (IsCompAssign) LHS = OldLHS; | ||||
10938 | |||||
10939 | // The RHS is simpler. | ||||
10940 | RHS = UsualUnaryConversions(RHS.get()); | ||||
10941 | if (RHS.isInvalid()) | ||||
10942 | return QualType(); | ||||
10943 | QualType RHSType = RHS.get()->getType(); | ||||
10944 | |||||
10945 | // C99 6.5.7p2: Each of the operands shall have integer type. | ||||
10946 | // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. | ||||
10947 | if ((!LHSType->isFixedPointOrIntegerType() && | ||||
10948 | !LHSType->hasIntegerRepresentation()) || | ||||
10949 | !RHSType->hasIntegerRepresentation()) | ||||
10950 | return InvalidOperands(Loc, LHS, RHS); | ||||
10951 | |||||
10952 | // C++0x: Don't allow scoped enums. FIXME: Use something better than | ||||
10953 | // hasIntegerRepresentation() above instead of this. | ||||
10954 | if (isScopedEnumerationType(LHSType) || | ||||
10955 | isScopedEnumerationType(RHSType)) { | ||||
10956 | return InvalidOperands(Loc, LHS, RHS); | ||||
10957 | } | ||||
10958 | // Sanity-check shift operands | ||||
10959 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); | ||||
10960 | |||||
10961 | // "The type of the result is that of the promoted left operand." | ||||
10962 | return LHSType; | ||||
10963 | } | ||||
10964 | |||||
10965 | /// Diagnose bad pointer comparisons. | ||||
10966 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, | ||||
10967 | ExprResult &LHS, ExprResult &RHS, | ||||
10968 | bool IsError) { | ||||
10969 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers | ||||
10970 | : diag::ext_typecheck_comparison_of_distinct_pointers) | ||||
10971 | << LHS.get()->getType() << RHS.get()->getType() | ||||
10972 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
10973 | } | ||||
10974 | |||||
10975 | /// Returns false if the pointers are converted to a composite type, | ||||
10976 | /// true otherwise. | ||||
10977 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, | ||||
10978 | ExprResult &LHS, ExprResult &RHS) { | ||||
10979 | // C++ [expr.rel]p2: | ||||
10980 | // [...] Pointer conversions (4.10) and qualification | ||||
10981 | // conversions (4.4) are performed on pointer operands (or on | ||||
10982 | // a pointer operand and a null pointer constant) to bring | ||||
10983 | // them to their composite pointer type. [...] | ||||
10984 | // | ||||
10985 | // C++ [expr.eq]p1 uses the same notion for (in)equality | ||||
10986 | // comparisons of pointers. | ||||
10987 | |||||
10988 | QualType LHSType = LHS.get()->getType(); | ||||
10989 | QualType RHSType = RHS.get()->getType(); | ||||
10990 | assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10991, __PRETTY_FUNCTION__)) | ||||
10991 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 10991, __PRETTY_FUNCTION__)); | ||||
10992 | |||||
10993 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); | ||||
10994 | if (T.isNull()) { | ||||
10995 | if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && | ||||
10996 | (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) | ||||
10997 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); | ||||
10998 | else | ||||
10999 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11000 | return true; | ||||
11001 | } | ||||
11002 | |||||
11003 | return false; | ||||
11004 | } | ||||
11005 | |||||
11006 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, | ||||
11007 | ExprResult &LHS, | ||||
11008 | ExprResult &RHS, | ||||
11009 | bool IsError) { | ||||
11010 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void | ||||
11011 | : diag::ext_typecheck_comparison_of_fptr_to_void) | ||||
11012 | << LHS.get()->getType() << RHS.get()->getType() | ||||
11013 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11014 | } | ||||
11015 | |||||
11016 | static bool isObjCObjectLiteral(ExprResult &E) { | ||||
11017 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { | ||||
11018 | case Stmt::ObjCArrayLiteralClass: | ||||
11019 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11020 | case Stmt::ObjCStringLiteralClass: | ||||
11021 | case Stmt::ObjCBoxedExprClass: | ||||
11022 | return true; | ||||
11023 | default: | ||||
11024 | // Note that ObjCBoolLiteral is NOT an object literal! | ||||
11025 | return false; | ||||
11026 | } | ||||
11027 | } | ||||
11028 | |||||
11029 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { | ||||
11030 | const ObjCObjectPointerType *Type = | ||||
11031 | LHS->getType()->getAs<ObjCObjectPointerType>(); | ||||
11032 | |||||
11033 | // If this is not actually an Objective-C object, bail out. | ||||
11034 | if (!Type) | ||||
11035 | return false; | ||||
11036 | |||||
11037 | // Get the LHS object's interface type. | ||||
11038 | QualType InterfaceType = Type->getPointeeType(); | ||||
11039 | |||||
11040 | // If the RHS isn't an Objective-C object, bail out. | ||||
11041 | if (!RHS->getType()->isObjCObjectPointerType()) | ||||
11042 | return false; | ||||
11043 | |||||
11044 | // Try to find the -isEqual: method. | ||||
11045 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); | ||||
11046 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, | ||||
11047 | InterfaceType, | ||||
11048 | /*IsInstance=*/true); | ||||
11049 | if (!Method) { | ||||
11050 | if (Type->isObjCIdType()) { | ||||
11051 | // For 'id', just check the global pool. | ||||
11052 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), | ||||
11053 | /*receiverId=*/true); | ||||
11054 | } else { | ||||
11055 | // Check protocols. | ||||
11056 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, | ||||
11057 | /*IsInstance=*/true); | ||||
11058 | } | ||||
11059 | } | ||||
11060 | |||||
11061 | if (!Method) | ||||
11062 | return false; | ||||
11063 | |||||
11064 | QualType T = Method->parameters()[0]->getType(); | ||||
11065 | if (!T->isObjCObjectPointerType()) | ||||
11066 | return false; | ||||
11067 | |||||
11068 | QualType R = Method->getReturnType(); | ||||
11069 | if (!R->isScalarType()) | ||||
11070 | return false; | ||||
11071 | |||||
11072 | return true; | ||||
11073 | } | ||||
11074 | |||||
11075 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { | ||||
11076 | FromE = FromE->IgnoreParenImpCasts(); | ||||
11077 | switch (FromE->getStmtClass()) { | ||||
11078 | default: | ||||
11079 | break; | ||||
11080 | case Stmt::ObjCStringLiteralClass: | ||||
11081 | // "string literal" | ||||
11082 | return LK_String; | ||||
11083 | case Stmt::ObjCArrayLiteralClass: | ||||
11084 | // "array literal" | ||||
11085 | return LK_Array; | ||||
11086 | case Stmt::ObjCDictionaryLiteralClass: | ||||
11087 | // "dictionary literal" | ||||
11088 | return LK_Dictionary; | ||||
11089 | case Stmt::BlockExprClass: | ||||
11090 | return LK_Block; | ||||
11091 | case Stmt::ObjCBoxedExprClass: { | ||||
11092 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); | ||||
11093 | switch (Inner->getStmtClass()) { | ||||
11094 | case Stmt::IntegerLiteralClass: | ||||
11095 | case Stmt::FloatingLiteralClass: | ||||
11096 | case Stmt::CharacterLiteralClass: | ||||
11097 | case Stmt::ObjCBoolLiteralExprClass: | ||||
11098 | case Stmt::CXXBoolLiteralExprClass: | ||||
11099 | // "numeric literal" | ||||
11100 | return LK_Numeric; | ||||
11101 | case Stmt::ImplicitCastExprClass: { | ||||
11102 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); | ||||
11103 | // Boolean literals can be represented by implicit casts. | ||||
11104 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) | ||||
11105 | return LK_Numeric; | ||||
11106 | break; | ||||
11107 | } | ||||
11108 | default: | ||||
11109 | break; | ||||
11110 | } | ||||
11111 | return LK_Boxed; | ||||
11112 | } | ||||
11113 | } | ||||
11114 | return LK_None; | ||||
11115 | } | ||||
11116 | |||||
11117 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, | ||||
11118 | ExprResult &LHS, ExprResult &RHS, | ||||
11119 | BinaryOperator::Opcode Opc){ | ||||
11120 | Expr *Literal; | ||||
11121 | Expr *Other; | ||||
11122 | if (isObjCObjectLiteral(LHS)) { | ||||
11123 | Literal = LHS.get(); | ||||
11124 | Other = RHS.get(); | ||||
11125 | } else { | ||||
11126 | Literal = RHS.get(); | ||||
11127 | Other = LHS.get(); | ||||
11128 | } | ||||
11129 | |||||
11130 | // Don't warn on comparisons against nil. | ||||
11131 | Other = Other->IgnoreParenCasts(); | ||||
11132 | if (Other->isNullPointerConstant(S.getASTContext(), | ||||
11133 | Expr::NPC_ValueDependentIsNotNull)) | ||||
11134 | return; | ||||
11135 | |||||
11136 | // This should be kept in sync with warn_objc_literal_comparison. | ||||
11137 | // LK_String should always be after the other literals, since it has its own | ||||
11138 | // warning flag. | ||||
11139 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); | ||||
11140 | assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0 ) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11140, __PRETTY_FUNCTION__)); | ||||
11141 | if (LiteralKind == Sema::LK_None) { | ||||
11142 | llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11142); | ||||
11143 | } | ||||
11144 | |||||
11145 | if (LiteralKind == Sema::LK_String) | ||||
11146 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) | ||||
11147 | << Literal->getSourceRange(); | ||||
11148 | else | ||||
11149 | S.Diag(Loc, diag::warn_objc_literal_comparison) | ||||
11150 | << LiteralKind << Literal->getSourceRange(); | ||||
11151 | |||||
11152 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
11153 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { | ||||
11154 | SourceLocation Start = LHS.get()->getBeginLoc(); | ||||
11155 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
11156 | CharSourceRange OpRange = | ||||
11157 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
11158 | |||||
11159 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) | ||||
11160 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") | ||||
11161 | << FixItHint::CreateReplacement(OpRange, " isEqual:") | ||||
11162 | << FixItHint::CreateInsertion(End, "]"); | ||||
11163 | } | ||||
11164 | } | ||||
11165 | |||||
11166 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. | ||||
11167 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, | ||||
11168 | ExprResult &RHS, SourceLocation Loc, | ||||
11169 | BinaryOperatorKind Opc) { | ||||
11170 | // Check that left hand side is !something. | ||||
11171 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); | ||||
11172 | if (!UO || UO->getOpcode() != UO_LNot) return; | ||||
11173 | |||||
11174 | // Only check if the right hand side is non-bool arithmetic type. | ||||
11175 | if (RHS.get()->isKnownToHaveBooleanValue()) return; | ||||
11176 | |||||
11177 | // Make sure that the something in !something is not bool. | ||||
11178 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); | ||||
11179 | if (SubExpr->isKnownToHaveBooleanValue()) return; | ||||
11180 | |||||
11181 | // Emit warning. | ||||
11182 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; | ||||
11183 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) | ||||
11184 | << Loc << IsBitwiseOp; | ||||
11185 | |||||
11186 | // First note suggest !(x < y) | ||||
11187 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); | ||||
11188 | SourceLocation FirstClose = RHS.get()->getEndLoc(); | ||||
11189 | FirstClose = S.getLocForEndOfToken(FirstClose); | ||||
11190 | if (FirstClose.isInvalid()) | ||||
11191 | FirstOpen = SourceLocation(); | ||||
11192 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) | ||||
11193 | << IsBitwiseOp | ||||
11194 | << FixItHint::CreateInsertion(FirstOpen, "(") | ||||
11195 | << FixItHint::CreateInsertion(FirstClose, ")"); | ||||
11196 | |||||
11197 | // Second note suggests (!x) < y | ||||
11198 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); | ||||
11199 | SourceLocation SecondClose = LHS.get()->getEndLoc(); | ||||
11200 | SecondClose = S.getLocForEndOfToken(SecondClose); | ||||
11201 | if (SecondClose.isInvalid()) | ||||
11202 | SecondOpen = SourceLocation(); | ||||
11203 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) | ||||
11204 | << FixItHint::CreateInsertion(SecondOpen, "(") | ||||
11205 | << FixItHint::CreateInsertion(SecondClose, ")"); | ||||
11206 | } | ||||
11207 | |||||
11208 | // Returns true if E refers to a non-weak array. | ||||
11209 | static bool checkForArray(const Expr *E) { | ||||
11210 | const ValueDecl *D = nullptr; | ||||
11211 | if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { | ||||
11212 | D = DR->getDecl(); | ||||
11213 | } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { | ||||
11214 | if (Mem->isImplicitAccess()) | ||||
11215 | D = Mem->getMemberDecl(); | ||||
11216 | } | ||||
11217 | if (!D) | ||||
11218 | return false; | ||||
11219 | return D->getType()->isArrayType() && !D->isWeak(); | ||||
11220 | } | ||||
11221 | |||||
11222 | /// Diagnose some forms of syntactically-obvious tautological comparison. | ||||
11223 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, | ||||
11224 | Expr *LHS, Expr *RHS, | ||||
11225 | BinaryOperatorKind Opc) { | ||||
11226 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); | ||||
11227 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); | ||||
11228 | |||||
11229 | QualType LHSType = LHS->getType(); | ||||
11230 | QualType RHSType = RHS->getType(); | ||||
11231 | if (LHSType->hasFloatingRepresentation() || | ||||
11232 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || | ||||
11233 | S.inTemplateInstantiation()) | ||||
11234 | return; | ||||
11235 | |||||
11236 | // Comparisons between two array types are ill-formed for operator<=>, so | ||||
11237 | // we shouldn't emit any additional warnings about it. | ||||
11238 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) | ||||
11239 | return; | ||||
11240 | |||||
11241 | // For non-floating point types, check for self-comparisons of the form | ||||
11242 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
11243 | // often indicate logic errors in the program. | ||||
11244 | // | ||||
11245 | // NOTE: Don't warn about comparison expressions resulting from macro | ||||
11246 | // expansion. Also don't warn about comparisons which are only self | ||||
11247 | // comparisons within a template instantiation. The warnings should catch | ||||
11248 | // obvious cases in the definition of the template anyways. The idea is to | ||||
11249 | // warn when the typed comparison operator will always evaluate to the same | ||||
11250 | // result. | ||||
11251 | |||||
11252 | // Used for indexing into %select in warn_comparison_always | ||||
11253 | enum { | ||||
11254 | AlwaysConstant, | ||||
11255 | AlwaysTrue, | ||||
11256 | AlwaysFalse, | ||||
11257 | AlwaysEqual, // std::strong_ordering::equal from operator<=> | ||||
11258 | }; | ||||
11259 | |||||
11260 | // C++2a [depr.array.comp]: | ||||
11261 | // Equality and relational comparisons ([expr.eq], [expr.rel]) between two | ||||
11262 | // operands of array type are deprecated. | ||||
11263 | if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && | ||||
11264 | RHSStripped->getType()->isArrayType()) { | ||||
11265 | S.Diag(Loc, diag::warn_depr_array_comparison) | ||||
11266 | << LHS->getSourceRange() << RHS->getSourceRange() | ||||
11267 | << LHSStripped->getType() << RHSStripped->getType(); | ||||
11268 | // Carry on to produce the tautological comparison warning, if this | ||||
11269 | // expression is potentially-evaluated, we can resolve the array to a | ||||
11270 | // non-weak declaration, and so on. | ||||
11271 | } | ||||
11272 | |||||
11273 | if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { | ||||
11274 | if (Expr::isSameComparisonOperand(LHS, RHS)) { | ||||
11275 | unsigned Result; | ||||
11276 | switch (Opc) { | ||||
11277 | case BO_EQ: | ||||
11278 | case BO_LE: | ||||
11279 | case BO_GE: | ||||
11280 | Result = AlwaysTrue; | ||||
11281 | break; | ||||
11282 | case BO_NE: | ||||
11283 | case BO_LT: | ||||
11284 | case BO_GT: | ||||
11285 | Result = AlwaysFalse; | ||||
11286 | break; | ||||
11287 | case BO_Cmp: | ||||
11288 | Result = AlwaysEqual; | ||||
11289 | break; | ||||
11290 | default: | ||||
11291 | Result = AlwaysConstant; | ||||
11292 | break; | ||||
11293 | } | ||||
11294 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11295 | S.PDiag(diag::warn_comparison_always) | ||||
11296 | << 0 /*self-comparison*/ | ||||
11297 | << Result); | ||||
11298 | } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { | ||||
11299 | // What is it always going to evaluate to? | ||||
11300 | unsigned Result; | ||||
11301 | switch (Opc) { | ||||
11302 | case BO_EQ: // e.g. array1 == array2 | ||||
11303 | Result = AlwaysFalse; | ||||
11304 | break; | ||||
11305 | case BO_NE: // e.g. array1 != array2 | ||||
11306 | Result = AlwaysTrue; | ||||
11307 | break; | ||||
11308 | default: // e.g. array1 <= array2 | ||||
11309 | // The best we can say is 'a constant' | ||||
11310 | Result = AlwaysConstant; | ||||
11311 | break; | ||||
11312 | } | ||||
11313 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11314 | S.PDiag(diag::warn_comparison_always) | ||||
11315 | << 1 /*array comparison*/ | ||||
11316 | << Result); | ||||
11317 | } | ||||
11318 | } | ||||
11319 | |||||
11320 | if (isa<CastExpr>(LHSStripped)) | ||||
11321 | LHSStripped = LHSStripped->IgnoreParenCasts(); | ||||
11322 | if (isa<CastExpr>(RHSStripped)) | ||||
11323 | RHSStripped = RHSStripped->IgnoreParenCasts(); | ||||
11324 | |||||
11325 | // Warn about comparisons against a string constant (unless the other | ||||
11326 | // operand is null); the user probably wants string comparison function. | ||||
11327 | Expr *LiteralString = nullptr; | ||||
11328 | Expr *LiteralStringStripped = nullptr; | ||||
11329 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && | ||||
11330 | !RHSStripped->isNullPointerConstant(S.Context, | ||||
11331 | Expr::NPC_ValueDependentIsNull)) { | ||||
11332 | LiteralString = LHS; | ||||
11333 | LiteralStringStripped = LHSStripped; | ||||
11334 | } else if ((isa<StringLiteral>(RHSStripped) || | ||||
11335 | isa<ObjCEncodeExpr>(RHSStripped)) && | ||||
11336 | !LHSStripped->isNullPointerConstant(S.Context, | ||||
11337 | Expr::NPC_ValueDependentIsNull)) { | ||||
11338 | LiteralString = RHS; | ||||
11339 | LiteralStringStripped = RHSStripped; | ||||
11340 | } | ||||
11341 | |||||
11342 | if (LiteralString) { | ||||
11343 | S.DiagRuntimeBehavior(Loc, nullptr, | ||||
11344 | S.PDiag(diag::warn_stringcompare) | ||||
11345 | << isa<ObjCEncodeExpr>(LiteralStringStripped) | ||||
11346 | << LiteralString->getSourceRange()); | ||||
11347 | } | ||||
11348 | } | ||||
11349 | |||||
11350 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { | ||||
11351 | switch (CK) { | ||||
11352 | default: { | ||||
11353 | #ifndef NDEBUG | ||||
11354 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) | ||||
11355 | << "\n"; | ||||
11356 | #endif | ||||
11357 | llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11357); | ||||
11358 | } | ||||
11359 | case CK_UserDefinedConversion: | ||||
11360 | return ICK_Identity; | ||||
11361 | case CK_LValueToRValue: | ||||
11362 | return ICK_Lvalue_To_Rvalue; | ||||
11363 | case CK_ArrayToPointerDecay: | ||||
11364 | return ICK_Array_To_Pointer; | ||||
11365 | case CK_FunctionToPointerDecay: | ||||
11366 | return ICK_Function_To_Pointer; | ||||
11367 | case CK_IntegralCast: | ||||
11368 | return ICK_Integral_Conversion; | ||||
11369 | case CK_FloatingCast: | ||||
11370 | return ICK_Floating_Conversion; | ||||
11371 | case CK_IntegralToFloating: | ||||
11372 | case CK_FloatingToIntegral: | ||||
11373 | return ICK_Floating_Integral; | ||||
11374 | case CK_IntegralComplexCast: | ||||
11375 | case CK_FloatingComplexCast: | ||||
11376 | case CK_FloatingComplexToIntegralComplex: | ||||
11377 | case CK_IntegralComplexToFloatingComplex: | ||||
11378 | return ICK_Complex_Conversion; | ||||
11379 | case CK_FloatingComplexToReal: | ||||
11380 | case CK_FloatingRealToComplex: | ||||
11381 | case CK_IntegralComplexToReal: | ||||
11382 | case CK_IntegralRealToComplex: | ||||
11383 | return ICK_Complex_Real; | ||||
11384 | } | ||||
11385 | } | ||||
11386 | |||||
11387 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, | ||||
11388 | QualType FromType, | ||||
11389 | SourceLocation Loc) { | ||||
11390 | // Check for a narrowing implicit conversion. | ||||
11391 | StandardConversionSequence SCS; | ||||
11392 | SCS.setAsIdentityConversion(); | ||||
11393 | SCS.setToType(0, FromType); | ||||
11394 | SCS.setToType(1, ToType); | ||||
11395 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
11396 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); | ||||
11397 | |||||
11398 | APValue PreNarrowingValue; | ||||
11399 | QualType PreNarrowingType; | ||||
11400 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, | ||||
11401 | PreNarrowingType, | ||||
11402 | /*IgnoreFloatToIntegralConversion*/ true)) { | ||||
11403 | case NK_Dependent_Narrowing: | ||||
11404 | // Implicit conversion to a narrower type, but the expression is | ||||
11405 | // value-dependent so we can't tell whether it's actually narrowing. | ||||
11406 | case NK_Not_Narrowing: | ||||
11407 | return false; | ||||
11408 | |||||
11409 | case NK_Constant_Narrowing: | ||||
11410 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11411 | // expression. | ||||
11412 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11413 | << /*Constant*/ 1 | ||||
11414 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; | ||||
11415 | return true; | ||||
11416 | |||||
11417 | case NK_Variable_Narrowing: | ||||
11418 | // Implicit conversion to a narrower type, and the value is not a constant | ||||
11419 | // expression. | ||||
11420 | case NK_Type_Narrowing: | ||||
11421 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) | ||||
11422 | << /*Constant*/ 0 << FromType << ToType; | ||||
11423 | // TODO: It's not a constant expression, but what if the user intended it | ||||
11424 | // to be? Can we produce notes to help them figure out why it isn't? | ||||
11425 | return true; | ||||
11426 | } | ||||
11427 | llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11427); | ||||
11428 | } | ||||
11429 | |||||
11430 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, | ||||
11431 | ExprResult &LHS, | ||||
11432 | ExprResult &RHS, | ||||
11433 | SourceLocation Loc) { | ||||
11434 | QualType LHSType = LHS.get()->getType(); | ||||
11435 | QualType RHSType = RHS.get()->getType(); | ||||
11436 | // Dig out the original argument type and expression before implicit casts | ||||
11437 | // were applied. These are the types/expressions we need to check the | ||||
11438 | // [expr.spaceship] requirements against. | ||||
11439 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); | ||||
11440 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); | ||||
11441 | QualType LHSStrippedType = LHSStripped.get()->getType(); | ||||
11442 | QualType RHSStrippedType = RHSStripped.get()->getType(); | ||||
11443 | |||||
11444 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the | ||||
11445 | // other is not, the program is ill-formed. | ||||
11446 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { | ||||
11447 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11448 | return QualType(); | ||||
11449 | } | ||||
11450 | |||||
11451 | // FIXME: Consider combining this with checkEnumArithmeticConversions. | ||||
11452 | int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + | ||||
11453 | RHSStrippedType->isEnumeralType(); | ||||
11454 | if (NumEnumArgs == 1) { | ||||
11455 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); | ||||
11456 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; | ||||
11457 | if (OtherTy->hasFloatingRepresentation()) { | ||||
11458 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); | ||||
11459 | return QualType(); | ||||
11460 | } | ||||
11461 | } | ||||
11462 | if (NumEnumArgs == 2) { | ||||
11463 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration | ||||
11464 | // type E, the operator yields the result of converting the operands | ||||
11465 | // to the underlying type of E and applying <=> to the converted operands. | ||||
11466 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { | ||||
11467 | S.InvalidOperands(Loc, LHS, RHS); | ||||
11468 | return QualType(); | ||||
11469 | } | ||||
11470 | QualType IntType = | ||||
11471 | LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); | ||||
11472 | assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> ( 0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11472, __PRETTY_FUNCTION__)); | ||||
11473 | |||||
11474 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we | ||||
11475 | // promote the boolean type, and all other promotable integer types, to | ||||
11476 | // avoid this. | ||||
11477 | if (IntType->isPromotableIntegerType()) | ||||
11478 | IntType = S.Context.getPromotedIntegerType(IntType); | ||||
11479 | |||||
11480 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); | ||||
11481 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); | ||||
11482 | LHSType = RHSType = IntType; | ||||
11483 | } | ||||
11484 | |||||
11485 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the | ||||
11486 | // usual arithmetic conversions are applied to the operands. | ||||
11487 | QualType Type = | ||||
11488 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11489 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11490 | return QualType(); | ||||
11491 | if (Type.isNull()) | ||||
11492 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11493 | |||||
11494 | Optional<ComparisonCategoryType> CCT = | ||||
11495 | getComparisonCategoryForBuiltinCmp(Type); | ||||
11496 | if (!CCT) | ||||
11497 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11498 | |||||
11499 | bool HasNarrowing = checkThreeWayNarrowingConversion( | ||||
11500 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); | ||||
11501 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, | ||||
11502 | RHS.get()->getBeginLoc()); | ||||
11503 | if (HasNarrowing) | ||||
11504 | return QualType(); | ||||
11505 | |||||
11506 | assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set" ) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11506, __PRETTY_FUNCTION__)); | ||||
11507 | |||||
11508 | return S.CheckComparisonCategoryType( | ||||
11509 | *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); | ||||
11510 | } | ||||
11511 | |||||
11512 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, | ||||
11513 | ExprResult &RHS, | ||||
11514 | SourceLocation Loc, | ||||
11515 | BinaryOperatorKind Opc) { | ||||
11516 | if (Opc == BO_Cmp) | ||||
11517 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); | ||||
11518 | |||||
11519 | // C99 6.5.8p3 / C99 6.5.9p4 | ||||
11520 | QualType Type = | ||||
11521 | S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); | ||||
11522 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
11523 | return QualType(); | ||||
11524 | if (Type.isNull()) | ||||
11525 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11526 | assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ? static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11526, __PRETTY_FUNCTION__)); | ||||
11527 | |||||
11528 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) | ||||
11529 | return S.InvalidOperands(Loc, LHS, RHS); | ||||
11530 | |||||
11531 | // Check for comparisons of floating point operands using != and ==. | ||||
11532 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) | ||||
11533 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
11534 | |||||
11535 | // The result of comparisons is 'bool' in C++, 'int' in C. | ||||
11536 | return S.Context.getLogicalOperationType(); | ||||
11537 | } | ||||
11538 | |||||
11539 | void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { | ||||
11540 | if (!NullE.get()->getType()->isAnyPointerType()) | ||||
11541 | return; | ||||
11542 | int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; | ||||
11543 | if (!E.get()->getType()->isAnyPointerType() && | ||||
11544 | E.get()->isNullPointerConstant(Context, | ||||
11545 | Expr::NPC_ValueDependentIsNotNull) == | ||||
11546 | Expr::NPCK_ZeroExpression) { | ||||
11547 | if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { | ||||
11548 | if (CL->getValue() == 0) | ||||
11549 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11550 | << NullValue | ||||
11551 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11552 | NullValue ? "NULL" : "(void *)0"); | ||||
11553 | } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { | ||||
11554 | TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); | ||||
11555 | QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); | ||||
11556 | if (T == Context.CharTy) | ||||
11557 | Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) | ||||
11558 | << NullValue | ||||
11559 | << FixItHint::CreateReplacement(E.get()->getExprLoc(), | ||||
11560 | NullValue ? "NULL" : "(void *)0"); | ||||
11561 | } | ||||
11562 | } | ||||
11563 | } | ||||
11564 | |||||
11565 | // C99 6.5.8, C++ [expr.rel] | ||||
11566 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
11567 | SourceLocation Loc, | ||||
11568 | BinaryOperatorKind Opc) { | ||||
11569 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); | ||||
11570 | bool IsThreeWay = Opc == BO_Cmp; | ||||
11571 | bool IsOrdered = IsRelational || IsThreeWay; | ||||
11572 | auto IsAnyPointerType = [](ExprResult E) { | ||||
11573 | QualType Ty = E.get()->getType(); | ||||
11574 | return Ty->isPointerType() || Ty->isMemberPointerType(); | ||||
11575 | }; | ||||
11576 | |||||
11577 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer | ||||
11578 | // type, array-to-pointer, ..., conversions are performed on both operands to | ||||
11579 | // bring them to their composite type. | ||||
11580 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before | ||||
11581 | // any type-related checks. | ||||
11582 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { | ||||
11583 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
11584 | if (LHS.isInvalid()) | ||||
11585 | return QualType(); | ||||
11586 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
11587 | if (RHS.isInvalid()) | ||||
11588 | return QualType(); | ||||
11589 | } else { | ||||
11590 | LHS = DefaultLvalueConversion(LHS.get()); | ||||
11591 | if (LHS.isInvalid()) | ||||
11592 | return QualType(); | ||||
11593 | RHS = DefaultLvalueConversion(RHS.get()); | ||||
11594 | if (RHS.isInvalid()) | ||||
11595 | return QualType(); | ||||
11596 | } | ||||
11597 | |||||
11598 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); | ||||
11599 | if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { | ||||
11600 | CheckPtrComparisonWithNullChar(LHS, RHS); | ||||
11601 | CheckPtrComparisonWithNullChar(RHS, LHS); | ||||
11602 | } | ||||
11603 | |||||
11604 | // Handle vector comparisons separately. | ||||
11605 | if (LHS.get()->getType()->isVectorType() || | ||||
11606 | RHS.get()->getType()->isVectorType()) | ||||
11607 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); | ||||
11608 | |||||
11609 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
11610 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
11611 | |||||
11612 | QualType LHSType = LHS.get()->getType(); | ||||
11613 | QualType RHSType = RHS.get()->getType(); | ||||
11614 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && | ||||
11615 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) | ||||
11616 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); | ||||
11617 | |||||
11618 | const Expr::NullPointerConstantKind LHSNullKind = | ||||
11619 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11620 | const Expr::NullPointerConstantKind RHSNullKind = | ||||
11621 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); | ||||
11622 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; | ||||
11623 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; | ||||
11624 | |||||
11625 | auto computeResultTy = [&]() { | ||||
11626 | if (Opc != BO_Cmp) | ||||
11627 | return Context.getLogicalOperationType(); | ||||
11628 | assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11628, __PRETTY_FUNCTION__)); | ||||
11629 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()-> getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11629, __PRETTY_FUNCTION__)); | ||||
11630 | |||||
11631 | QualType CompositeTy = LHS.get()->getType(); | ||||
11632 | assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void> (0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 11632, __PRETTY_FUNCTION__)); | ||||
11633 | |||||
11634 | Optional<ComparisonCategoryType> CCT = | ||||
11635 | getComparisonCategoryForBuiltinCmp(CompositeTy); | ||||
11636 | if (!CCT) | ||||
11637 | return InvalidOperands(Loc, LHS, RHS); | ||||
11638 | |||||
11639 | if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { | ||||
11640 | // P0946R0: Comparisons between a null pointer constant and an object | ||||
11641 | // pointer result in std::strong_equality, which is ill-formed under | ||||
11642 | // P1959R0. | ||||
11643 | Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) | ||||
11644 | << (LHSIsNull ? LHS.get()->getSourceRange() | ||||
11645 | : RHS.get()->getSourceRange()); | ||||
11646 | return QualType(); | ||||
11647 | } | ||||
11648 | |||||
11649 | return CheckComparisonCategoryType( | ||||
11650 | *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); | ||||
11651 | }; | ||||
11652 | |||||
11653 | if (!IsOrdered && LHSIsNull != RHSIsNull) { | ||||
11654 | bool IsEquality = Opc == BO_EQ; | ||||
11655 | if (RHSIsNull) | ||||
11656 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, | ||||
11657 | RHS.get()->getSourceRange()); | ||||
11658 | else | ||||
11659 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, | ||||
11660 | LHS.get()->getSourceRange()); | ||||
11661 | } | ||||
11662 | |||||
11663 | if ((LHSType->isIntegerType() && !LHSIsNull) || | ||||
11664 | (RHSType->isIntegerType() && !RHSIsNull)) { | ||||
11665 | // Skip normal pointer conversion checks in this case; we have better | ||||
11666 | // diagnostics for this below. | ||||
11667 | } else if (getLangOpts().CPlusPlus) { | ||||
11668 | // Equality comparison of a function pointer to a void pointer is invalid, | ||||
11669 | // but we allow it as an extension. | ||||
11670 | // FIXME: If we really want to allow this, should it be part of composite | ||||
11671 | // pointer type computation so it works in conditionals too? | ||||
11672 | if (!IsOrdered && | ||||
11673 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || | ||||
11674 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { | ||||
11675 | // This is a gcc extension compatibility comparison. | ||||
11676 | // In a SFINAE context, we treat this as a hard error to maintain | ||||
11677 | // conformance with the C++ standard. | ||||
11678 | diagnoseFunctionPointerToVoidComparison( | ||||
11679 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); | ||||
11680 | |||||
11681 | if (isSFINAEContext()) | ||||
11682 | return QualType(); | ||||
11683 | |||||
11684 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11685 | return computeResultTy(); | ||||
11686 | } | ||||
11687 | |||||
11688 | // C++ [expr.eq]p2: | ||||
11689 | // If at least one operand is a pointer [...] bring them to their | ||||
11690 | // composite pointer type. | ||||
11691 | // C++ [expr.spaceship]p6 | ||||
11692 | // If at least one of the operands is of pointer type, [...] bring them | ||||
11693 | // to their composite pointer type. | ||||
11694 | // C++ [expr.rel]p2: | ||||
11695 | // If both operands are pointers, [...] bring them to their composite | ||||
11696 | // pointer type. | ||||
11697 | // For <=>, the only valid non-pointer types are arrays and functions, and | ||||
11698 | // we already decayed those, so this is really the same as the relational | ||||
11699 | // comparison rule. | ||||
11700 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= | ||||
11701 | (IsOrdered ? 2 : 1) && | ||||
11702 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || | ||||
11703 | RHSType->isObjCObjectPointerType()))) { | ||||
11704 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
11705 | return QualType(); | ||||
11706 | return computeResultTy(); | ||||
11707 | } | ||||
11708 | } else if (LHSType->isPointerType() && | ||||
11709 | RHSType->isPointerType()) { // C99 6.5.8p2 | ||||
11710 | // All of the following pointer-related warnings are GCC extensions, except | ||||
11711 | // when handling null pointer constants. | ||||
11712 | QualType LCanPointeeTy = | ||||
11713 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11714 | QualType RCanPointeeTy = | ||||
11715 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); | ||||
11716 | |||||
11717 | // C99 6.5.9p2 and C99 6.5.8p2 | ||||
11718 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), | ||||
11719 | RCanPointeeTy.getUnqualifiedType())) { | ||||
11720 | if (IsRelational) { | ||||
11721 | // Pointers both need to point to complete or incomplete types | ||||
11722 | if ((LCanPointeeTy->isIncompleteType() != | ||||
11723 | RCanPointeeTy->isIncompleteType()) && | ||||
11724 | !getLangOpts().C11) { | ||||
11725 | Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) | ||||
11726 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() | ||||
11727 | << LHSType << RHSType << LCanPointeeTy->isIncompleteType() | ||||
11728 | << RCanPointeeTy->isIncompleteType(); | ||||
11729 | } | ||||
11730 | if (LCanPointeeTy->isFunctionType()) { | ||||
11731 | // Valid unless a relational comparison of function pointers | ||||
11732 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) | ||||
11733 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11734 | << RHS.get()->getSourceRange(); | ||||
11735 | } | ||||
11736 | } | ||||
11737 | } else if (!IsRelational && | ||||
11738 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { | ||||
11739 | // Valid unless comparison between non-null pointer and function pointer | ||||
11740 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) | ||||
11741 | && !LHSIsNull && !RHSIsNull) | ||||
11742 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, | ||||
11743 | /*isError*/false); | ||||
11744 | } else { | ||||
11745 | // Invalid | ||||
11746 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); | ||||
11747 | } | ||||
11748 | if (LCanPointeeTy != RCanPointeeTy) { | ||||
11749 | // Treat NULL constant as a special case in OpenCL. | ||||
11750 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { | ||||
11751 | if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { | ||||
11752 | Diag(Loc, | ||||
11753 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) | ||||
11754 | << LHSType << RHSType << 0 /* comparison */ | ||||
11755 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | ||||
11756 | } | ||||
11757 | } | ||||
11758 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); | ||||
11759 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); | ||||
11760 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion | ||||
11761 | : CK_BitCast; | ||||
11762 | if (LHSIsNull && !RHSIsNull) | ||||
11763 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); | ||||
11764 | else | ||||
11765 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); | ||||
11766 | } | ||||
11767 | return computeResultTy(); | ||||
11768 | } | ||||
11769 | |||||
11770 | if (getLangOpts().CPlusPlus) { | ||||
11771 | // C++ [expr.eq]p4: | ||||
11772 | // Two operands of type std::nullptr_t or one operand of type | ||||
11773 | // std::nullptr_t and the other a null pointer constant compare equal. | ||||
11774 | if (!IsOrdered && LHSIsNull && RHSIsNull) { | ||||
11775 | if (LHSType->isNullPtrType()) { | ||||
11776 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11777 | return computeResultTy(); | ||||
11778 | } | ||||
11779 | if (RHSType->isNullPtrType()) { | ||||
11780 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11781 | return computeResultTy(); | ||||
11782 | } | ||||
11783 | } | ||||
11784 | |||||
11785 | // Comparison of Objective-C pointers and block pointers against nullptr_t. | ||||
11786 | // These aren't covered by the composite pointer type rules. | ||||
11787 | if (!IsOrdered && RHSType->isNullPtrType() && | ||||
11788 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { | ||||
11789 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11790 | return computeResultTy(); | ||||
11791 | } | ||||
11792 | if (!IsOrdered && LHSType->isNullPtrType() && | ||||
11793 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { | ||||
11794 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11795 | return computeResultTy(); | ||||
11796 | } | ||||
11797 | |||||
11798 | if (IsRelational && | ||||
11799 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || | ||||
11800 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { | ||||
11801 | // HACK: Relational comparison of nullptr_t against a pointer type is | ||||
11802 | // invalid per DR583, but we allow it within std::less<> and friends, | ||||
11803 | // since otherwise common uses of it break. | ||||
11804 | // FIXME: Consider removing this hack once LWG fixes std::less<> and | ||||
11805 | // friends to have std::nullptr_t overload candidates. | ||||
11806 | DeclContext *DC = CurContext; | ||||
11807 | if (isa<FunctionDecl>(DC)) | ||||
11808 | DC = DC->getParent(); | ||||
11809 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { | ||||
11810 | if (CTSD->isInStdNamespace() && | ||||
11811 | llvm::StringSwitch<bool>(CTSD->getName()) | ||||
11812 | .Cases("less", "less_equal", "greater", "greater_equal", true) | ||||
11813 | .Default(false)) { | ||||
11814 | if (RHSType->isNullPtrType()) | ||||
11815 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11816 | else | ||||
11817 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11818 | return computeResultTy(); | ||||
11819 | } | ||||
11820 | } | ||||
11821 | } | ||||
11822 | |||||
11823 | // C++ [expr.eq]p2: | ||||
11824 | // If at least one operand is a pointer to member, [...] bring them to | ||||
11825 | // their composite pointer type. | ||||
11826 | if (!IsOrdered && | ||||
11827 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { | ||||
11828 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) | ||||
11829 | return QualType(); | ||||
11830 | else | ||||
11831 | return computeResultTy(); | ||||
11832 | } | ||||
11833 | } | ||||
11834 | |||||
11835 | // Handle block pointer types. | ||||
11836 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
11837 | RHSType->isBlockPointerType()) { | ||||
11838 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
11839 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); | ||||
11840 | |||||
11841 | if (!LHSIsNull && !RHSIsNull && | ||||
11842 | !Context.typesAreCompatible(lpointee, rpointee)) { | ||||
11843 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
11844 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11845 | << RHS.get()->getSourceRange(); | ||||
11846 | } | ||||
11847 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11848 | return computeResultTy(); | ||||
11849 | } | ||||
11850 | |||||
11851 | // Allow block pointers to be compared with null pointer constants. | ||||
11852 | if (!IsOrdered | ||||
11853 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) | ||||
11854 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { | ||||
11855 | if (!LHSIsNull && !RHSIsNull) { | ||||
11856 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() | ||||
11857 | ->getPointeeType()->isVoidType()) | ||||
11858 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() | ||||
11859 | ->getPointeeType()->isVoidType()))) | ||||
11860 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) | ||||
11861 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11862 | << RHS.get()->getSourceRange(); | ||||
11863 | } | ||||
11864 | if (LHSIsNull && !RHSIsNull) | ||||
11865 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
11866 | RHSType->isPointerType() ? CK_BitCast | ||||
11867 | : CK_AnyPointerToBlockPointerCast); | ||||
11868 | else | ||||
11869 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
11870 | LHSType->isPointerType() ? CK_BitCast | ||||
11871 | : CK_AnyPointerToBlockPointerCast); | ||||
11872 | return computeResultTy(); | ||||
11873 | } | ||||
11874 | |||||
11875 | if (LHSType->isObjCObjectPointerType() || | ||||
11876 | RHSType->isObjCObjectPointerType()) { | ||||
11877 | const PointerType *LPT = LHSType->getAs<PointerType>(); | ||||
11878 | const PointerType *RPT = RHSType->getAs<PointerType>(); | ||||
11879 | if (LPT || RPT) { | ||||
11880 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; | ||||
11881 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; | ||||
11882 | |||||
11883 | if (!LPtrToVoid && !RPtrToVoid && | ||||
11884 | !Context.typesAreCompatible(LHSType, RHSType)) { | ||||
11885 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
11886 | /*isError*/false); | ||||
11887 | } | ||||
11888 | // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than | ||||
11889 | // the RHS, but we have test coverage for this behavior. | ||||
11890 | // FIXME: Consider using convertPointersToCompositeType in C++. | ||||
11891 | if (LHSIsNull && !RHSIsNull) { | ||||
11892 | Expr *E = LHS.get(); | ||||
11893 | if (getLangOpts().ObjCAutoRefCount) | ||||
11894 | CheckObjCConversion(SourceRange(), RHSType, E, | ||||
11895 | CCK_ImplicitConversion); | ||||
11896 | LHS = ImpCastExprToType(E, RHSType, | ||||
11897 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
11898 | } | ||||
11899 | else { | ||||
11900 | Expr *E = RHS.get(); | ||||
11901 | if (getLangOpts().ObjCAutoRefCount) | ||||
11902 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, | ||||
11903 | /*Diagnose=*/true, | ||||
11904 | /*DiagnoseCFAudited=*/false, Opc); | ||||
11905 | RHS = ImpCastExprToType(E, LHSType, | ||||
11906 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); | ||||
11907 | } | ||||
11908 | return computeResultTy(); | ||||
11909 | } | ||||
11910 | if (LHSType->isObjCObjectPointerType() && | ||||
11911 | RHSType->isObjCObjectPointerType()) { | ||||
11912 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) | ||||
11913 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, | ||||
11914 | /*isError*/false); | ||||
11915 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) | ||||
11916 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); | ||||
11917 | |||||
11918 | if (LHSIsNull && !RHSIsNull) | ||||
11919 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); | ||||
11920 | else | ||||
11921 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); | ||||
11922 | return computeResultTy(); | ||||
11923 | } | ||||
11924 | |||||
11925 | if (!IsOrdered && LHSType->isBlockPointerType() && | ||||
11926 | RHSType->isBlockCompatibleObjCPointerType(Context)) { | ||||
11927 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
11928 | CK_BlockPointerToObjCPointerCast); | ||||
11929 | return computeResultTy(); | ||||
11930 | } else if (!IsOrdered && | ||||
11931 | LHSType->isBlockCompatibleObjCPointerType(Context) && | ||||
11932 | RHSType->isBlockPointerType()) { | ||||
11933 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
11934 | CK_BlockPointerToObjCPointerCast); | ||||
11935 | return computeResultTy(); | ||||
11936 | } | ||||
11937 | } | ||||
11938 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || | ||||
11939 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { | ||||
11940 | unsigned DiagID = 0; | ||||
11941 | bool isError = false; | ||||
11942 | if (LangOpts.DebuggerSupport) { | ||||
11943 | // Under a debugger, allow the comparison of pointers to integers, | ||||
11944 | // since users tend to want to compare addresses. | ||||
11945 | } else if ((LHSIsNull && LHSType->isIntegerType()) || | ||||
11946 | (RHSIsNull && RHSType->isIntegerType())) { | ||||
11947 | if (IsOrdered) { | ||||
11948 | isError = getLangOpts().CPlusPlus; | ||||
11949 | DiagID = | ||||
11950 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero | ||||
11951 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; | ||||
11952 | } | ||||
11953 | } else if (getLangOpts().CPlusPlus) { | ||||
11954 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; | ||||
11955 | isError = true; | ||||
11956 | } else if (IsOrdered) | ||||
11957 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; | ||||
11958 | else | ||||
11959 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; | ||||
11960 | |||||
11961 | if (DiagID) { | ||||
11962 | Diag(Loc, DiagID) | ||||
11963 | << LHSType << RHSType << LHS.get()->getSourceRange() | ||||
11964 | << RHS.get()->getSourceRange(); | ||||
11965 | if (isError) | ||||
11966 | return QualType(); | ||||
11967 | } | ||||
11968 | |||||
11969 | if (LHSType->isIntegerType()) | ||||
11970 | LHS = ImpCastExprToType(LHS.get(), RHSType, | ||||
11971 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
11972 | else | ||||
11973 | RHS = ImpCastExprToType(RHS.get(), LHSType, | ||||
11974 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); | ||||
11975 | return computeResultTy(); | ||||
11976 | } | ||||
11977 | |||||
11978 | // Handle block pointers. | ||||
11979 | if (!IsOrdered && RHSIsNull | ||||
11980 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { | ||||
11981 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
11982 | return computeResultTy(); | ||||
11983 | } | ||||
11984 | if (!IsOrdered && LHSIsNull | ||||
11985 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { | ||||
11986 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
11987 | return computeResultTy(); | ||||
11988 | } | ||||
11989 | |||||
11990 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||
11991 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { | ||||
11992 | return computeResultTy(); | ||||
11993 | } | ||||
11994 | |||||
11995 | if (LHSType->isQueueT() && RHSType->isQueueT()) { | ||||
11996 | return computeResultTy(); | ||||
11997 | } | ||||
11998 | |||||
11999 | if (LHSIsNull && RHSType->isQueueT()) { | ||||
12000 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); | ||||
12001 | return computeResultTy(); | ||||
12002 | } | ||||
12003 | |||||
12004 | if (LHSType->isQueueT() && RHSIsNull) { | ||||
12005 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); | ||||
12006 | return computeResultTy(); | ||||
12007 | } | ||||
12008 | } | ||||
12009 | |||||
12010 | return InvalidOperands(Loc, LHS, RHS); | ||||
12011 | } | ||||
12012 | |||||
12013 | // Return a signed ext_vector_type that is of identical size and number of | ||||
12014 | // elements. For floating point vectors, return an integer type of identical | ||||
12015 | // size and number of elements. In the non ext_vector_type case, search from | ||||
12016 | // the largest type to the smallest type to avoid cases where long long == long, | ||||
12017 | // where long gets picked over long long. | ||||
12018 | QualType Sema::GetSignedVectorType(QualType V) { | ||||
12019 | const VectorType *VTy = V->castAs<VectorType>(); | ||||
12020 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); | ||||
12021 | |||||
12022 | if (isa<ExtVectorType>(VTy)) { | ||||
12023 | if (TypeSize == Context.getTypeSize(Context.CharTy)) | ||||
12024 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); | ||||
12025 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12026 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); | ||||
12027 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12028 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); | ||||
12029 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12030 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); | ||||
12031 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12032, __PRETTY_FUNCTION__)) | ||||
12032 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare") ? static_cast <void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12032, __PRETTY_FUNCTION__)); | ||||
12033 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); | ||||
12034 | } | ||||
12035 | |||||
12036 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) | ||||
12037 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), | ||||
12038 | VectorType::GenericVector); | ||||
12039 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) | ||||
12040 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), | ||||
12041 | VectorType::GenericVector); | ||||
12042 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) | ||||
12043 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), | ||||
12044 | VectorType::GenericVector); | ||||
12045 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) | ||||
12046 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), | ||||
12047 | VectorType::GenericVector); | ||||
12048 | assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12049, __PRETTY_FUNCTION__)) | ||||
12049 | "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare" ) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12049, __PRETTY_FUNCTION__)); | ||||
12050 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), | ||||
12051 | VectorType::GenericVector); | ||||
12052 | } | ||||
12053 | |||||
12054 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that | ||||
12055 | /// operates on extended vector types. Instead of producing an IntTy result, | ||||
12056 | /// like a scalar comparison, a vector comparison produces a vector of integer | ||||
12057 | /// types. | ||||
12058 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12059 | SourceLocation Loc, | ||||
12060 | BinaryOperatorKind Opc) { | ||||
12061 | if (Opc == BO_Cmp) { | ||||
12062 | Diag(Loc, diag::err_three_way_vector_comparison); | ||||
12063 | return QualType(); | ||||
12064 | } | ||||
12065 | |||||
12066 | // Check to make sure we're operating on vectors of the same type and width, | ||||
12067 | // Allowing one side to be a scalar of element type. | ||||
12068 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, | ||||
12069 | /*AllowBothBool*/true, | ||||
12070 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12071 | if (vType.isNull()) | ||||
12072 | return vType; | ||||
12073 | |||||
12074 | QualType LHSType = LHS.get()->getType(); | ||||
12075 | |||||
12076 | // If AltiVec, the comparison results in a numeric type, i.e. | ||||
12077 | // bool for C++, int for C | ||||
12078 | if (getLangOpts().AltiVec && | ||||
12079 | vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) | ||||
12080 | return Context.getLogicalOperationType(); | ||||
12081 | |||||
12082 | // For non-floating point types, check for self-comparisons of the form | ||||
12083 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and | ||||
12084 | // often indicate logic errors in the program. | ||||
12085 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); | ||||
12086 | |||||
12087 | // Check for comparisons of floating point operands using != and ==. | ||||
12088 | if (BinaryOperator::isEqualityOp(Opc) && | ||||
12089 | LHSType->hasFloatingRepresentation()) { | ||||
12090 | assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast <void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12090, __PRETTY_FUNCTION__)); | ||||
12091 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); | ||||
12092 | } | ||||
12093 | |||||
12094 | // Return a signed type for the vector. | ||||
12095 | return GetSignedVectorType(vType); | ||||
12096 | } | ||||
12097 | |||||
12098 | static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, | ||||
12099 | const ExprResult &XorRHS, | ||||
12100 | const SourceLocation Loc) { | ||||
12101 | // Do not diagnose macros. | ||||
12102 | if (Loc.isMacroID()) | ||||
12103 | return; | ||||
12104 | |||||
12105 | // Do not diagnose if both LHS and RHS are macros. | ||||
12106 | if (XorLHS.get()->getExprLoc().isMacroID() && | ||||
12107 | XorRHS.get()->getExprLoc().isMacroID()) | ||||
12108 | return; | ||||
12109 | |||||
12110 | bool Negative = false; | ||||
12111 | bool ExplicitPlus = false; | ||||
12112 | const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); | ||||
12113 | const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); | ||||
12114 | |||||
12115 | if (!LHSInt) | ||||
12116 | return; | ||||
12117 | if (!RHSInt) { | ||||
12118 | // Check negative literals. | ||||
12119 | if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { | ||||
12120 | UnaryOperatorKind Opc = UO->getOpcode(); | ||||
12121 | if (Opc != UO_Minus && Opc != UO_Plus) | ||||
12122 | return; | ||||
12123 | RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); | ||||
12124 | if (!RHSInt) | ||||
12125 | return; | ||||
12126 | Negative = (Opc == UO_Minus); | ||||
12127 | ExplicitPlus = !Negative; | ||||
12128 | } else { | ||||
12129 | return; | ||||
12130 | } | ||||
12131 | } | ||||
12132 | |||||
12133 | const llvm::APInt &LeftSideValue = LHSInt->getValue(); | ||||
12134 | llvm::APInt RightSideValue = RHSInt->getValue(); | ||||
12135 | if (LeftSideValue != 2 && LeftSideValue != 10) | ||||
12136 | return; | ||||
12137 | |||||
12138 | if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) | ||||
12139 | return; | ||||
12140 | |||||
12141 | CharSourceRange ExprRange = CharSourceRange::getCharRange( | ||||
12142 | LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); | ||||
12143 | llvm::StringRef ExprStr = | ||||
12144 | Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); | ||||
12145 | |||||
12146 | CharSourceRange XorRange = | ||||
12147 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); | ||||
12148 | llvm::StringRef XorStr = | ||||
12149 | Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); | ||||
12150 | // Do not diagnose if xor keyword/macro is used. | ||||
12151 | if (XorStr == "xor") | ||||
12152 | return; | ||||
12153 | |||||
12154 | std::string LHSStr = std::string(Lexer::getSourceText( | ||||
12155 | CharSourceRange::getTokenRange(LHSInt->getSourceRange()), | ||||
12156 | S.getSourceManager(), S.getLangOpts())); | ||||
12157 | std::string RHSStr = std::string(Lexer::getSourceText( | ||||
12158 | CharSourceRange::getTokenRange(RHSInt->getSourceRange()), | ||||
12159 | S.getSourceManager(), S.getLangOpts())); | ||||
12160 | |||||
12161 | if (Negative) { | ||||
12162 | RightSideValue = -RightSideValue; | ||||
12163 | RHSStr = "-" + RHSStr; | ||||
12164 | } else if (ExplicitPlus) { | ||||
12165 | RHSStr = "+" + RHSStr; | ||||
12166 | } | ||||
12167 | |||||
12168 | StringRef LHSStrRef = LHSStr; | ||||
12169 | StringRef RHSStrRef = RHSStr; | ||||
12170 | // Do not diagnose literals with digit separators, binary, hexadecimal, octal | ||||
12171 | // literals. | ||||
12172 | if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || | ||||
12173 | RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || | ||||
12174 | LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || | ||||
12175 | RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || | ||||
12176 | (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || | ||||
12177 | (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || | ||||
12178 | LHSStrRef.find('\'') != StringRef::npos || | ||||
12179 | RHSStrRef.find('\'') != StringRef::npos) | ||||
12180 | return; | ||||
12181 | |||||
12182 | bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); | ||||
12183 | const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; | ||||
12184 | int64_t RightSideIntValue = RightSideValue.getSExtValue(); | ||||
12185 | if (LeftSideValue == 2 && RightSideIntValue >= 0) { | ||||
12186 | std::string SuggestedExpr = "1 << " + RHSStr; | ||||
12187 | bool Overflow = false; | ||||
12188 | llvm::APInt One = (LeftSideValue - 1); | ||||
12189 | llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); | ||||
12190 | if (Overflow) { | ||||
12191 | if (RightSideIntValue < 64) | ||||
12192 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12193 | << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) | ||||
12194 | << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); | ||||
12195 | else if (RightSideIntValue == 64) | ||||
12196 | S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); | ||||
12197 | else | ||||
12198 | return; | ||||
12199 | } else { | ||||
12200 | S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) | ||||
12201 | << ExprStr << XorValue.toString(10, true) << SuggestedExpr | ||||
12202 | << PowValue.toString(10, true) | ||||
12203 | << FixItHint::CreateReplacement( | ||||
12204 | ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); | ||||
12205 | } | ||||
12206 | |||||
12207 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; | ||||
12208 | } else if (LeftSideValue == 10) { | ||||
12209 | std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); | ||||
12210 | S.Diag(Loc, diag::warn_xor_used_as_pow_base) | ||||
12211 | << ExprStr << XorValue.toString(10, true) << SuggestedValue | ||||
12212 | << FixItHint::CreateReplacement(ExprRange, SuggestedValue); | ||||
12213 | S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; | ||||
12214 | } | ||||
12215 | } | ||||
12216 | |||||
12217 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12218 | SourceLocation Loc) { | ||||
12219 | // Ensure that either both operands are of the same vector type, or | ||||
12220 | // one operand is of a vector type and the other is of its element type. | ||||
12221 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, | ||||
12222 | /*AllowBothBool*/true, | ||||
12223 | /*AllowBoolConversions*/false); | ||||
12224 | if (vType.isNull()) | ||||
12225 | return InvalidOperands(Loc, LHS, RHS); | ||||
12226 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && | ||||
12227 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) | ||||
12228 | return InvalidOperands(Loc, LHS, RHS); | ||||
12229 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the | ||||
12230 | // usage of the logical operators && and || with vectors in C. This | ||||
12231 | // check could be notionally dropped. | ||||
12232 | if (!getLangOpts().CPlusPlus && | ||||
12233 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) | ||||
12234 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); | ||||
12235 | |||||
12236 | return GetSignedVectorType(LHS.get()->getType()); | ||||
12237 | } | ||||
12238 | |||||
12239 | QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12240 | SourceLocation Loc, | ||||
12241 | bool IsCompAssign) { | ||||
12242 | if (!IsCompAssign) { | ||||
12243 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12244 | if (LHS.isInvalid()) | ||||
12245 | return QualType(); | ||||
12246 | } | ||||
12247 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12248 | if (RHS.isInvalid()) | ||||
12249 | return QualType(); | ||||
12250 | |||||
12251 | // For conversion purposes, we ignore any qualifiers. | ||||
12252 | // For example, "const float" and "float" are equivalent. | ||||
12253 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); | ||||
12254 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); | ||||
12255 | |||||
12256 | const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); | ||||
12257 | const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); | ||||
12258 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12258, __PRETTY_FUNCTION__)); | ||||
12259 | |||||
12260 | if (Context.hasSameType(LHSType, RHSType)) | ||||
12261 | return LHSType; | ||||
12262 | |||||
12263 | // Type conversion may change LHS/RHS. Keep copies to the original results, in | ||||
12264 | // case we have to return InvalidOperands. | ||||
12265 | ExprResult OriginalLHS = LHS; | ||||
12266 | ExprResult OriginalRHS = RHS; | ||||
12267 | if (LHSMatType && !RHSMatType) { | ||||
12268 | RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); | ||||
12269 | if (!RHS.isInvalid()) | ||||
12270 | return LHSType; | ||||
12271 | |||||
12272 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12273 | } | ||||
12274 | |||||
12275 | if (!LHSMatType && RHSMatType) { | ||||
12276 | LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); | ||||
12277 | if (!LHS.isInvalid()) | ||||
12278 | return RHSType; | ||||
12279 | return InvalidOperands(Loc, OriginalLHS, OriginalRHS); | ||||
12280 | } | ||||
12281 | |||||
12282 | return InvalidOperands(Loc, LHS, RHS); | ||||
12283 | } | ||||
12284 | |||||
12285 | QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12286 | SourceLocation Loc, | ||||
12287 | bool IsCompAssign) { | ||||
12288 | if (!IsCompAssign) { | ||||
12289 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | ||||
12290 | if (LHS.isInvalid()) | ||||
12291 | return QualType(); | ||||
12292 | } | ||||
12293 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
12294 | if (RHS.isInvalid()) | ||||
12295 | return QualType(); | ||||
12296 | |||||
12297 | auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12298 | auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); | ||||
12299 | assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix" ) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12299, __PRETTY_FUNCTION__)); | ||||
12300 | |||||
12301 | if (LHSMatType && RHSMatType) { | ||||
12302 | if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) | ||||
12303 | return InvalidOperands(Loc, LHS, RHS); | ||||
12304 | |||||
12305 | if (!Context.hasSameType(LHSMatType->getElementType(), | ||||
12306 | RHSMatType->getElementType())) | ||||
12307 | return InvalidOperands(Loc, LHS, RHS); | ||||
12308 | |||||
12309 | return Context.getConstantMatrixType(LHSMatType->getElementType(), | ||||
12310 | LHSMatType->getNumRows(), | ||||
12311 | RHSMatType->getNumColumns()); | ||||
12312 | } | ||||
12313 | return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); | ||||
12314 | } | ||||
12315 | |||||
12316 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12317 | SourceLocation Loc, | ||||
12318 | BinaryOperatorKind Opc) { | ||||
12319 | checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); | ||||
12320 | |||||
12321 | bool IsCompAssign = | ||||
12322 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; | ||||
12323 | |||||
12324 | if (LHS.get()->getType()->isVectorType() || | ||||
12325 | RHS.get()->getType()->isVectorType()) { | ||||
12326 | if (LHS.get()->getType()->hasIntegerRepresentation() && | ||||
12327 | RHS.get()->getType()->hasIntegerRepresentation()) | ||||
12328 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, | ||||
12329 | /*AllowBothBool*/true, | ||||
12330 | /*AllowBoolConversions*/getLangOpts().ZVector); | ||||
12331 | return InvalidOperands(Loc, LHS, RHS); | ||||
12332 | } | ||||
12333 | |||||
12334 | if (Opc == BO_And) | ||||
12335 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); | ||||
12336 | |||||
12337 | if (LHS.get()->getType()->hasFloatingRepresentation() || | ||||
12338 | RHS.get()->getType()->hasFloatingRepresentation()) | ||||
12339 | return InvalidOperands(Loc, LHS, RHS); | ||||
12340 | |||||
12341 | ExprResult LHSResult = LHS, RHSResult = RHS; | ||||
12342 | QualType compType = UsualArithmeticConversions( | ||||
12343 | LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); | ||||
12344 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) | ||||
12345 | return QualType(); | ||||
12346 | LHS = LHSResult.get(); | ||||
12347 | RHS = RHSResult.get(); | ||||
12348 | |||||
12349 | if (Opc == BO_Xor) | ||||
12350 | diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); | ||||
12351 | |||||
12352 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) | ||||
12353 | return compType; | ||||
12354 | return InvalidOperands(Loc, LHS, RHS); | ||||
12355 | } | ||||
12356 | |||||
12357 | // C99 6.5.[13,14] | ||||
12358 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, | ||||
12359 | SourceLocation Loc, | ||||
12360 | BinaryOperatorKind Opc) { | ||||
12361 | // Check vector operands differently. | ||||
12362 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) | ||||
12363 | return CheckVectorLogicalOperands(LHS, RHS, Loc); | ||||
12364 | |||||
12365 | bool EnumConstantInBoolContext = false; | ||||
12366 | for (const ExprResult &HS : {LHS, RHS}) { | ||||
12367 | if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { | ||||
12368 | const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); | ||||
12369 | if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) | ||||
12370 | EnumConstantInBoolContext = true; | ||||
12371 | } | ||||
12372 | } | ||||
12373 | |||||
12374 | if (EnumConstantInBoolContext) | ||||
12375 | Diag(Loc, diag::warn_enum_constant_in_bool_context); | ||||
12376 | |||||
12377 | // Diagnose cases where the user write a logical and/or but probably meant a | ||||
12378 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS | ||||
12379 | // is a constant. | ||||
12380 | if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && | ||||
12381 | !LHS.get()->getType()->isBooleanType() && | ||||
12382 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && | ||||
12383 | // Don't warn in macros or template instantiations. | ||||
12384 | !Loc.isMacroID() && !inTemplateInstantiation()) { | ||||
12385 | // If the RHS can be constant folded, and if it constant folds to something | ||||
12386 | // that isn't 0 or 1 (which indicate a potential logical operation that | ||||
12387 | // happened to fold to true/false) then warn. | ||||
12388 | // Parens on the RHS are ignored. | ||||
12389 | Expr::EvalResult EVResult; | ||||
12390 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { | ||||
12391 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||
12392 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && | ||||
12393 | !RHS.get()->getExprLoc().isMacroID()) || | ||||
12394 | (Result != 0 && Result != 1)) { | ||||
12395 | Diag(Loc, diag::warn_logical_instead_of_bitwise) | ||||
12396 | << RHS.get()->getSourceRange() | ||||
12397 | << (Opc == BO_LAnd ? "&&" : "||"); | ||||
12398 | // Suggest replacing the logical operator with the bitwise version | ||||
12399 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) | ||||
12400 | << (Opc == BO_LAnd ? "&" : "|") | ||||
12401 | << FixItHint::CreateReplacement(SourceRange( | ||||
12402 | Loc, getLocForEndOfToken(Loc)), | ||||
12403 | Opc == BO_LAnd ? "&" : "|"); | ||||
12404 | if (Opc == BO_LAnd) | ||||
12405 | // Suggest replacing "Foo() && kNonZero" with "Foo()" | ||||
12406 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) | ||||
12407 | << FixItHint::CreateRemoval( | ||||
12408 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), | ||||
12409 | RHS.get()->getEndLoc())); | ||||
12410 | } | ||||
12411 | } | ||||
12412 | } | ||||
12413 | |||||
12414 | if (!Context.getLangOpts().CPlusPlus) { | ||||
12415 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do | ||||
12416 | // not operate on the built-in scalar and vector float types. | ||||
12417 | if (Context.getLangOpts().OpenCL && | ||||
12418 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
12419 | if (LHS.get()->getType()->isFloatingType() || | ||||
12420 | RHS.get()->getType()->isFloatingType()) | ||||
12421 | return InvalidOperands(Loc, LHS, RHS); | ||||
12422 | } | ||||
12423 | |||||
12424 | LHS = UsualUnaryConversions(LHS.get()); | ||||
12425 | if (LHS.isInvalid()) | ||||
12426 | return QualType(); | ||||
12427 | |||||
12428 | RHS = UsualUnaryConversions(RHS.get()); | ||||
12429 | if (RHS.isInvalid()) | ||||
12430 | return QualType(); | ||||
12431 | |||||
12432 | if (!LHS.get()->getType()->isScalarType() || | ||||
12433 | !RHS.get()->getType()->isScalarType()) | ||||
12434 | return InvalidOperands(Loc, LHS, RHS); | ||||
12435 | |||||
12436 | return Context.IntTy; | ||||
12437 | } | ||||
12438 | |||||
12439 | // The following is safe because we only use this method for | ||||
12440 | // non-overloadable operands. | ||||
12441 | |||||
12442 | // C++ [expr.log.and]p1 | ||||
12443 | // C++ [expr.log.or]p1 | ||||
12444 | // The operands are both contextually converted to type bool. | ||||
12445 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); | ||||
12446 | if (LHSRes.isInvalid()) | ||||
12447 | return InvalidOperands(Loc, LHS, RHS); | ||||
12448 | LHS = LHSRes; | ||||
12449 | |||||
12450 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); | ||||
12451 | if (RHSRes.isInvalid()) | ||||
12452 | return InvalidOperands(Loc, LHS, RHS); | ||||
12453 | RHS = RHSRes; | ||||
12454 | |||||
12455 | // C++ [expr.log.and]p2 | ||||
12456 | // C++ [expr.log.or]p2 | ||||
12457 | // The result is a bool. | ||||
12458 | return Context.BoolTy; | ||||
12459 | } | ||||
12460 | |||||
12461 | static bool IsReadonlyMessage(Expr *E, Sema &S) { | ||||
12462 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
12463 | if (!ME) return false; | ||||
12464 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; | ||||
12465 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( | ||||
12466 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); | ||||
12467 | if (!Base) return false; | ||||
12468 | return Base->getMethodDecl() != nullptr; | ||||
12469 | } | ||||
12470 | |||||
12471 | /// Is the given expression (which must be 'const') a reference to a | ||||
12472 | /// variable which was originally non-const, but which has become | ||||
12473 | /// 'const' due to being captured within a block? | ||||
12474 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; | ||||
12475 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { | ||||
12476 | assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified ()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12476, __PRETTY_FUNCTION__)); | ||||
12477 | E = E->IgnoreParens(); | ||||
12478 | |||||
12479 | // Must be a reference to a declaration from an enclosing scope. | ||||
12480 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
12481 | if (!DRE) return NCCK_None; | ||||
12482 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; | ||||
12483 | |||||
12484 | // The declaration must be a variable which is not declared 'const'. | ||||
12485 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); | ||||
12486 | if (!var) return NCCK_None; | ||||
12487 | if (var->getType().isConstQualified()) return NCCK_None; | ||||
12488 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?" ) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12488, __PRETTY_FUNCTION__)); | ||||
12489 | |||||
12490 | // Decide whether the first capture was for a block or a lambda. | ||||
12491 | DeclContext *DC = S.CurContext, *Prev = nullptr; | ||||
12492 | // Decide whether the first capture was for a block or a lambda. | ||||
12493 | while (DC) { | ||||
12494 | // For init-capture, it is possible that the variable belongs to the | ||||
12495 | // template pattern of the current context. | ||||
12496 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | ||||
12497 | if (var->isInitCapture() && | ||||
12498 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) | ||||
12499 | break; | ||||
12500 | if (DC == var->getDeclContext()) | ||||
12501 | break; | ||||
12502 | Prev = DC; | ||||
12503 | DC = DC->getParent(); | ||||
12504 | } | ||||
12505 | // Unless we have an init-capture, we've gone one step too far. | ||||
12506 | if (!var->isInitCapture()) | ||||
12507 | DC = Prev; | ||||
12508 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); | ||||
12509 | } | ||||
12510 | |||||
12511 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { | ||||
12512 | Ty = Ty.getNonReferenceType(); | ||||
12513 | if (IsDereference && Ty->isPointerType()) | ||||
12514 | Ty = Ty->getPointeeType(); | ||||
12515 | return !Ty.isConstQualified(); | ||||
12516 | } | ||||
12517 | |||||
12518 | // Update err_typecheck_assign_const and note_typecheck_assign_const | ||||
12519 | // when this enum is changed. | ||||
12520 | enum { | ||||
12521 | ConstFunction, | ||||
12522 | ConstVariable, | ||||
12523 | ConstMember, | ||||
12524 | ConstMethod, | ||||
12525 | NestedConstMember, | ||||
12526 | ConstUnknown, // Keep as last element | ||||
12527 | }; | ||||
12528 | |||||
12529 | /// Emit the "read-only variable not assignable" error and print notes to give | ||||
12530 | /// more information about why the variable is not assignable, such as pointing | ||||
12531 | /// to the declaration of a const variable, showing that a method is const, or | ||||
12532 | /// that the function is returning a const reference. | ||||
12533 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, | ||||
12534 | SourceLocation Loc) { | ||||
12535 | SourceRange ExprRange = E->getSourceRange(); | ||||
12536 | |||||
12537 | // Only emit one error on the first const found. All other consts will emit | ||||
12538 | // a note to the error. | ||||
12539 | bool DiagnosticEmitted = false; | ||||
12540 | |||||
12541 | // Track if the current expression is the result of a dereference, and if the | ||||
12542 | // next checked expression is the result of a dereference. | ||||
12543 | bool IsDereference = false; | ||||
12544 | bool NextIsDereference = false; | ||||
12545 | |||||
12546 | // Loop to process MemberExpr chains. | ||||
12547 | while (true) { | ||||
12548 | IsDereference = NextIsDereference; | ||||
12549 | |||||
12550 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); | ||||
12551 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
12552 | NextIsDereference = ME->isArrow(); | ||||
12553 | const ValueDecl *VD = ME->getMemberDecl(); | ||||
12554 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { | ||||
12555 | // Mutable fields can be modified even if the class is const. | ||||
12556 | if (Field->isMutable()) { | ||||
12557 | assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted." ) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12557, __PRETTY_FUNCTION__)); | ||||
12558 | break; | ||||
12559 | } | ||||
12560 | |||||
12561 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { | ||||
12562 | if (!DiagnosticEmitted) { | ||||
12563 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12564 | << ExprRange << ConstMember << false /*static*/ << Field | ||||
12565 | << Field->getType(); | ||||
12566 | DiagnosticEmitted = true; | ||||
12567 | } | ||||
12568 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12569 | << ConstMember << false /*static*/ << Field << Field->getType() | ||||
12570 | << Field->getSourceRange(); | ||||
12571 | } | ||||
12572 | E = ME->getBase(); | ||||
12573 | continue; | ||||
12574 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { | ||||
12575 | if (VDecl->getType().isConstQualified()) { | ||||
12576 | if (!DiagnosticEmitted) { | ||||
12577 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12578 | << ExprRange << ConstMember << true /*static*/ << VDecl | ||||
12579 | << VDecl->getType(); | ||||
12580 | DiagnosticEmitted = true; | ||||
12581 | } | ||||
12582 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12583 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() | ||||
12584 | << VDecl->getSourceRange(); | ||||
12585 | } | ||||
12586 | // Static fields do not inherit constness from parents. | ||||
12587 | break; | ||||
12588 | } | ||||
12589 | break; // End MemberExpr | ||||
12590 | } else if (const ArraySubscriptExpr *ASE = | ||||
12591 | dyn_cast<ArraySubscriptExpr>(E)) { | ||||
12592 | E = ASE->getBase()->IgnoreParenImpCasts(); | ||||
12593 | continue; | ||||
12594 | } else if (const ExtVectorElementExpr *EVE = | ||||
12595 | dyn_cast<ExtVectorElementExpr>(E)) { | ||||
12596 | E = EVE->getBase()->IgnoreParenImpCasts(); | ||||
12597 | continue; | ||||
12598 | } | ||||
12599 | break; | ||||
12600 | } | ||||
12601 | |||||
12602 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { | ||||
12603 | // Function calls | ||||
12604 | const FunctionDecl *FD = CE->getDirectCallee(); | ||||
12605 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { | ||||
12606 | if (!DiagnosticEmitted) { | ||||
12607 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12608 | << ConstFunction << FD; | ||||
12609 | DiagnosticEmitted = true; | ||||
12610 | } | ||||
12611 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), | ||||
12612 | diag::note_typecheck_assign_const) | ||||
12613 | << ConstFunction << FD << FD->getReturnType() | ||||
12614 | << FD->getReturnTypeSourceRange(); | ||||
12615 | } | ||||
12616 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
12617 | // Point to variable declaration. | ||||
12618 | if (const ValueDecl *VD = DRE->getDecl()) { | ||||
12619 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { | ||||
12620 | if (!DiagnosticEmitted) { | ||||
12621 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12622 | << ExprRange << ConstVariable << VD << VD->getType(); | ||||
12623 | DiagnosticEmitted = true; | ||||
12624 | } | ||||
12625 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) | ||||
12626 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); | ||||
12627 | } | ||||
12628 | } | ||||
12629 | } else if (isa<CXXThisExpr>(E)) { | ||||
12630 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { | ||||
12631 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { | ||||
12632 | if (MD->isConst()) { | ||||
12633 | if (!DiagnosticEmitted) { | ||||
12634 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange | ||||
12635 | << ConstMethod << MD; | ||||
12636 | DiagnosticEmitted = true; | ||||
12637 | } | ||||
12638 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) | ||||
12639 | << ConstMethod << MD << MD->getSourceRange(); | ||||
12640 | } | ||||
12641 | } | ||||
12642 | } | ||||
12643 | } | ||||
12644 | |||||
12645 | if (DiagnosticEmitted) | ||||
12646 | return; | ||||
12647 | |||||
12648 | // Can't determine a more specific message, so display the generic error. | ||||
12649 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; | ||||
12650 | } | ||||
12651 | |||||
12652 | enum OriginalExprKind { | ||||
12653 | OEK_Variable, | ||||
12654 | OEK_Member, | ||||
12655 | OEK_LValue | ||||
12656 | }; | ||||
12657 | |||||
12658 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, | ||||
12659 | const RecordType *Ty, | ||||
12660 | SourceLocation Loc, SourceRange Range, | ||||
12661 | OriginalExprKind OEK, | ||||
12662 | bool &DiagnosticEmitted) { | ||||
12663 | std::vector<const RecordType *> RecordTypeList; | ||||
12664 | RecordTypeList.push_back(Ty); | ||||
12665 | unsigned NextToCheckIndex = 0; | ||||
12666 | // We walk the record hierarchy breadth-first to ensure that we print | ||||
12667 | // diagnostics in field nesting order. | ||||
12668 | while (RecordTypeList.size() > NextToCheckIndex) { | ||||
12669 | bool IsNested = NextToCheckIndex > 0; | ||||
12670 | for (const FieldDecl *Field : | ||||
12671 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { | ||||
12672 | // First, check every field for constness. | ||||
12673 | QualType FieldTy = Field->getType(); | ||||
12674 | if (FieldTy.isConstQualified()) { | ||||
12675 | if (!DiagnosticEmitted) { | ||||
12676 | S.Diag(Loc, diag::err_typecheck_assign_const) | ||||
12677 | << Range << NestedConstMember << OEK << VD | ||||
12678 | << IsNested << Field; | ||||
12679 | DiagnosticEmitted = true; | ||||
12680 | } | ||||
12681 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) | ||||
12682 | << NestedConstMember << IsNested << Field | ||||
12683 | << FieldTy << Field->getSourceRange(); | ||||
12684 | } | ||||
12685 | |||||
12686 | // Then we append it to the list to check next in order. | ||||
12687 | FieldTy = FieldTy.getCanonicalType(); | ||||
12688 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { | ||||
12689 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) | ||||
12690 | RecordTypeList.push_back(FieldRecTy); | ||||
12691 | } | ||||
12692 | } | ||||
12693 | ++NextToCheckIndex; | ||||
12694 | } | ||||
12695 | } | ||||
12696 | |||||
12697 | /// Emit an error for the case where a record we are trying to assign to has a | ||||
12698 | /// const-qualified field somewhere in its hierarchy. | ||||
12699 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, | ||||
12700 | SourceLocation Loc) { | ||||
12701 | QualType Ty = E->getType(); | ||||
12702 | assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ? static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12702, __PRETTY_FUNCTION__)); | ||||
12703 | SourceRange Range = E->getSourceRange(); | ||||
12704 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); | ||||
12705 | bool DiagEmitted = false; | ||||
12706 | |||||
12707 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
12708 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, | ||||
12709 | Range, OEK_Member, DiagEmitted); | ||||
12710 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
12711 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, | ||||
12712 | Range, OEK_Variable, DiagEmitted); | ||||
12713 | else | ||||
12714 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, | ||||
12715 | Range, OEK_LValue, DiagEmitted); | ||||
12716 | if (!DiagEmitted) | ||||
12717 | DiagnoseConstAssignment(S, E, Loc); | ||||
12718 | } | ||||
12719 | |||||
12720 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, | ||||
12721 | /// emit an error and return true. If so, return false. | ||||
12722 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { | ||||
12723 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast <void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12723, __PRETTY_FUNCTION__)); | ||||
12724 | |||||
12725 | S.CheckShadowingDeclModification(E, Loc); | ||||
12726 | |||||
12727 | SourceLocation OrigLoc = Loc; | ||||
12728 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, | ||||
12729 | &Loc); | ||||
12730 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) | ||||
12731 | IsLV = Expr::MLV_InvalidMessageExpression; | ||||
12732 | if (IsLV == Expr::MLV_Valid) | ||||
12733 | return false; | ||||
12734 | |||||
12735 | unsigned DiagID = 0; | ||||
12736 | bool NeedType = false; | ||||
12737 | switch (IsLV) { // C99 6.5.16p2 | ||||
12738 | case Expr::MLV_ConstQualified: | ||||
12739 | // Use a specialized diagnostic when we're assigning to an object | ||||
12740 | // from an enclosing function or block. | ||||
12741 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { | ||||
12742 | if (NCCK == NCCK_Block) | ||||
12743 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; | ||||
12744 | else | ||||
12745 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; | ||||
12746 | break; | ||||
12747 | } | ||||
12748 | |||||
12749 | // In ARC, use some specialized diagnostics for occasions where we | ||||
12750 | // infer 'const'. These are always pseudo-strong variables. | ||||
12751 | if (S.getLangOpts().ObjCAutoRefCount) { | ||||
12752 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); | ||||
12753 | if (declRef && isa<VarDecl>(declRef->getDecl())) { | ||||
12754 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); | ||||
12755 | |||||
12756 | // Use the normal diagnostic if it's pseudo-__strong but the | ||||
12757 | // user actually wrote 'const'. | ||||
12758 | if (var->isARCPseudoStrong() && | ||||
12759 | (!var->getTypeSourceInfo() || | ||||
12760 | !var->getTypeSourceInfo()->getType().isConstQualified())) { | ||||
12761 | // There are three pseudo-strong cases: | ||||
12762 | // - self | ||||
12763 | ObjCMethodDecl *method = S.getCurMethodDecl(); | ||||
12764 | if (method && var == method->getSelfDecl()) { | ||||
12765 | DiagID = method->isClassMethod() | ||||
12766 | ? diag::err_typecheck_arc_assign_self_class_method | ||||
12767 | : diag::err_typecheck_arc_assign_self; | ||||
12768 | |||||
12769 | // - Objective-C externally_retained attribute. | ||||
12770 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || | ||||
12771 | isa<ParmVarDecl>(var)) { | ||||
12772 | DiagID = diag::err_typecheck_arc_assign_externally_retained; | ||||
12773 | |||||
12774 | // - fast enumeration variables | ||||
12775 | } else { | ||||
12776 | DiagID = diag::err_typecheck_arr_assign_enumeration; | ||||
12777 | } | ||||
12778 | |||||
12779 | SourceRange Assign; | ||||
12780 | if (Loc != OrigLoc) | ||||
12781 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
12782 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
12783 | // We need to preserve the AST regardless, so migration tool | ||||
12784 | // can do its job. | ||||
12785 | return false; | ||||
12786 | } | ||||
12787 | } | ||||
12788 | } | ||||
12789 | |||||
12790 | // If none of the special cases above are triggered, then this is a | ||||
12791 | // simple const assignment. | ||||
12792 | if (DiagID == 0) { | ||||
12793 | DiagnoseConstAssignment(S, E, Loc); | ||||
12794 | return true; | ||||
12795 | } | ||||
12796 | |||||
12797 | break; | ||||
12798 | case Expr::MLV_ConstAddrSpace: | ||||
12799 | DiagnoseConstAssignment(S, E, Loc); | ||||
12800 | return true; | ||||
12801 | case Expr::MLV_ConstQualifiedField: | ||||
12802 | DiagnoseRecursiveConstFields(S, E, Loc); | ||||
12803 | return true; | ||||
12804 | case Expr::MLV_ArrayType: | ||||
12805 | case Expr::MLV_ArrayTemporary: | ||||
12806 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; | ||||
12807 | NeedType = true; | ||||
12808 | break; | ||||
12809 | case Expr::MLV_NotObjectType: | ||||
12810 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; | ||||
12811 | NeedType = true; | ||||
12812 | break; | ||||
12813 | case Expr::MLV_LValueCast: | ||||
12814 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; | ||||
12815 | break; | ||||
12816 | case Expr::MLV_Valid: | ||||
12817 | 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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12817); | ||||
12818 | case Expr::MLV_InvalidExpression: | ||||
12819 | case Expr::MLV_MemberFunction: | ||||
12820 | case Expr::MLV_ClassTemporary: | ||||
12821 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; | ||||
12822 | break; | ||||
12823 | case Expr::MLV_IncompleteType: | ||||
12824 | case Expr::MLV_IncompleteVoidType: | ||||
12825 | return S.RequireCompleteType(Loc, E->getType(), | ||||
12826 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); | ||||
12827 | case Expr::MLV_DuplicateVectorComponents: | ||||
12828 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; | ||||
12829 | break; | ||||
12830 | case Expr::MLV_NoSetterProperty: | ||||
12831 | llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12831); | ||||
12832 | case Expr::MLV_InvalidMessageExpression: | ||||
12833 | DiagID = diag::err_readonly_message_assignment; | ||||
12834 | break; | ||||
12835 | case Expr::MLV_SubObjCPropertySetting: | ||||
12836 | DiagID = diag::err_no_subobject_property_setting; | ||||
12837 | break; | ||||
12838 | } | ||||
12839 | |||||
12840 | SourceRange Assign; | ||||
12841 | if (Loc != OrigLoc) | ||||
12842 | Assign = SourceRange(OrigLoc, OrigLoc); | ||||
12843 | if (NeedType) | ||||
12844 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; | ||||
12845 | else | ||||
12846 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; | ||||
12847 | return true; | ||||
12848 | } | ||||
12849 | |||||
12850 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, | ||||
12851 | SourceLocation Loc, | ||||
12852 | Sema &Sema) { | ||||
12853 | if (Sema.inTemplateInstantiation()) | ||||
12854 | return; | ||||
12855 | if (Sema.isUnevaluatedContext()) | ||||
12856 | return; | ||||
12857 | if (Loc.isInvalid() || Loc.isMacroID()) | ||||
12858 | return; | ||||
12859 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) | ||||
12860 | return; | ||||
12861 | |||||
12862 | // C / C++ fields | ||||
12863 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); | ||||
12864 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); | ||||
12865 | if (ML && MR) { | ||||
12866 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) | ||||
12867 | return; | ||||
12868 | const ValueDecl *LHSDecl = | ||||
12869 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); | ||||
12870 | const ValueDecl *RHSDecl = | ||||
12871 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); | ||||
12872 | if (LHSDecl != RHSDecl) | ||||
12873 | return; | ||||
12874 | if (LHSDecl->getType().isVolatileQualified()) | ||||
12875 | return; | ||||
12876 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
12877 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
12878 | return; | ||||
12879 | |||||
12880 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; | ||||
12881 | } | ||||
12882 | |||||
12883 | // Objective-C instance variables | ||||
12884 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); | ||||
12885 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); | ||||
12886 | if (OL && OR && OL->getDecl() == OR->getDecl()) { | ||||
12887 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); | ||||
12888 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); | ||||
12889 | if (RL && RR && RL->getDecl() == RR->getDecl()) | ||||
12890 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; | ||||
12891 | } | ||||
12892 | } | ||||
12893 | |||||
12894 | // C99 6.5.16.1 | ||||
12895 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, | ||||
12896 | SourceLocation Loc, | ||||
12897 | QualType CompoundType) { | ||||
12898 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 12898, __PRETTY_FUNCTION__)); | ||||
12899 | |||||
12900 | // Verify that LHS is a modifiable lvalue, and emit error if not. | ||||
12901 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) | ||||
12902 | return QualType(); | ||||
12903 | |||||
12904 | QualType LHSType = LHSExpr->getType(); | ||||
12905 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : | ||||
12906 | CompoundType; | ||||
12907 | // OpenCL v1.2 s6.1.1.1 p2: | ||||
12908 | // The half data type can only be used to declare a pointer to a buffer that | ||||
12909 | // contains half values | ||||
12910 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && | ||||
12911 | LHSType->isHalfType()) { | ||||
12912 | Diag(Loc, diag::err_opencl_half_load_store) << 1 | ||||
12913 | << LHSType.getUnqualifiedType(); | ||||
12914 | return QualType(); | ||||
12915 | } | ||||
12916 | |||||
12917 | AssignConvertType ConvTy; | ||||
12918 | if (CompoundType.isNull()) { | ||||
12919 | Expr *RHSCheck = RHS.get(); | ||||
12920 | |||||
12921 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); | ||||
12922 | |||||
12923 | QualType LHSTy(LHSType); | ||||
12924 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); | ||||
12925 | if (RHS.isInvalid()) | ||||
12926 | return QualType(); | ||||
12927 | // Special case of NSObject attributes on c-style pointer types. | ||||
12928 | if (ConvTy == IncompatiblePointer && | ||||
12929 | ((Context.isObjCNSObjectType(LHSType) && | ||||
12930 | RHSType->isObjCObjectPointerType()) || | ||||
12931 | (Context.isObjCNSObjectType(RHSType) && | ||||
12932 | LHSType->isObjCObjectPointerType()))) | ||||
12933 | ConvTy = Compatible; | ||||
12934 | |||||
12935 | if (ConvTy == Compatible && | ||||
12936 | LHSType->isObjCObjectType()) | ||||
12937 | Diag(Loc, diag::err_objc_object_assignment) | ||||
12938 | << LHSType; | ||||
12939 | |||||
12940 | // If the RHS is a unary plus or minus, check to see if they = and + are | ||||
12941 | // right next to each other. If so, the user may have typo'd "x =+ 4" | ||||
12942 | // instead of "x += 4". | ||||
12943 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) | ||||
12944 | RHSCheck = ICE->getSubExpr(); | ||||
12945 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { | ||||
12946 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && | ||||
12947 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && | ||||
12948 | // Only if the two operators are exactly adjacent. | ||||
12949 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && | ||||
12950 | // And there is a space or other character before the subexpr of the | ||||
12951 | // unary +/-. We don't want to warn on "x=-1". | ||||
12952 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && | ||||
12953 | UO->getSubExpr()->getBeginLoc().isFileID()) { | ||||
12954 | Diag(Loc, diag::warn_not_compound_assign) | ||||
12955 | << (UO->getOpcode() == UO_Plus ? "+" : "-") | ||||
12956 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); | ||||
12957 | } | ||||
12958 | } | ||||
12959 | |||||
12960 | if (ConvTy == Compatible) { | ||||
12961 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { | ||||
12962 | // Warn about retain cycles where a block captures the LHS, but | ||||
12963 | // not if the LHS is a simple variable into which the block is | ||||
12964 | // being stored...unless that variable can be captured by reference! | ||||
12965 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); | ||||
12966 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); | ||||
12967 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) | ||||
12968 | checkRetainCycles(LHSExpr, RHS.get()); | ||||
12969 | } | ||||
12970 | |||||
12971 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
12972 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { | ||||
12973 | // It is safe to assign a weak reference into a strong variable. | ||||
12974 | // Although this code can still have problems: | ||||
12975 | // id x = self.weakProp; | ||||
12976 | // id y = self.weakProp; | ||||
12977 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
12978 | // paths through the function. This should be revisited if | ||||
12979 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
12980 | // For ObjCWeak only, we do not warn if the assign is to a non-weak | ||||
12981 | // variable, which will be valid for the current autorelease scope. | ||||
12982 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
12983 | RHS.get()->getBeginLoc())) | ||||
12984 | getCurFunction()->markSafeWeakUse(RHS.get()); | ||||
12985 | |||||
12986 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { | ||||
12987 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); | ||||
12988 | } | ||||
12989 | } | ||||
12990 | } else { | ||||
12991 | // Compound assignment "x += y" | ||||
12992 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); | ||||
12993 | } | ||||
12994 | |||||
12995 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, | ||||
12996 | RHS.get(), AA_Assigning)) | ||||
12997 | return QualType(); | ||||
12998 | |||||
12999 | CheckForNullPointerDereference(*this, LHSExpr); | ||||
13000 | |||||
13001 | if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { | ||||
13002 | if (CompoundType.isNull()) { | ||||
13003 | // C++2a [expr.ass]p5: | ||||
13004 | // A simple-assignment whose left operand is of a volatile-qualified | ||||
13005 | // type is deprecated unless the assignment is either a discarded-value | ||||
13006 | // expression or an unevaluated operand | ||||
13007 | ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); | ||||
13008 | } else { | ||||
13009 | // C++2a [expr.ass]p6: | ||||
13010 | // [Compound-assignment] expressions are deprecated if E1 has | ||||
13011 | // volatile-qualified type | ||||
13012 | Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; | ||||
13013 | } | ||||
13014 | } | ||||
13015 | |||||
13016 | // C99 6.5.16p3: The type of an assignment expression is the type of the | ||||
13017 | // left operand unless the left operand has qualified type, in which case | ||||
13018 | // it is the unqualified version of the type of the left operand. | ||||
13019 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand | ||||
13020 | // is converted to the type of the assignment expression (above). | ||||
13021 | // C++ 5.17p1: the type of the assignment expression is that of its left | ||||
13022 | // operand. | ||||
13023 | return (getLangOpts().CPlusPlus | ||||
13024 | ? LHSType : LHSType.getUnqualifiedType()); | ||||
13025 | } | ||||
13026 | |||||
13027 | // Only ignore explicit casts to void. | ||||
13028 | static bool IgnoreCommaOperand(const Expr *E) { | ||||
13029 | E = E->IgnoreParens(); | ||||
13030 | |||||
13031 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { | ||||
13032 | if (CE->getCastKind() == CK_ToVoid) { | ||||
13033 | return true; | ||||
13034 | } | ||||
13035 | |||||
13036 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. | ||||
13037 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && | ||||
13038 | CE->getSubExpr()->getType()->isDependentType()) { | ||||
13039 | return true; | ||||
13040 | } | ||||
13041 | } | ||||
13042 | |||||
13043 | return false; | ||||
13044 | } | ||||
13045 | |||||
13046 | // Look for instances where it is likely the comma operator is confused with | ||||
13047 | // another operator. There is an explicit list of acceptable expressions for | ||||
13048 | // the left hand side of the comma operator, otherwise emit a warning. | ||||
13049 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { | ||||
13050 | // No warnings in macros | ||||
13051 | if (Loc.isMacroID()) | ||||
13052 | return; | ||||
13053 | |||||
13054 | // Don't warn in template instantiations. | ||||
13055 | if (inTemplateInstantiation()) | ||||
13056 | return; | ||||
13057 | |||||
13058 | // Scope isn't fine-grained enough to explicitly list the specific cases, so | ||||
13059 | // instead, skip more than needed, then call back into here with the | ||||
13060 | // CommaVisitor in SemaStmt.cpp. | ||||
13061 | // The listed locations are the initialization and increment portions | ||||
13062 | // of a for loop. The additional checks are on the condition of | ||||
13063 | // if statements, do/while loops, and for loops. | ||||
13064 | // Differences in scope flags for C89 mode requires the extra logic. | ||||
13065 | const unsigned ForIncrementFlags = | ||||
13066 | getLangOpts().C99 || getLangOpts().CPlusPlus | ||||
13067 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope | ||||
13068 | : Scope::ContinueScope | Scope::BreakScope; | ||||
13069 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; | ||||
13070 | const unsigned ScopeFlags = getCurScope()->getFlags(); | ||||
13071 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || | ||||
13072 | (ScopeFlags & ForInitFlags) == ForInitFlags) | ||||
13073 | return; | ||||
13074 | |||||
13075 | // If there are multiple comma operators used together, get the RHS of the | ||||
13076 | // of the comma operator as the LHS. | ||||
13077 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { | ||||
13078 | if (BO->getOpcode() != BO_Comma) | ||||
13079 | break; | ||||
13080 | LHS = BO->getRHS(); | ||||
13081 | } | ||||
13082 | |||||
13083 | // Only allow some expressions on LHS to not warn. | ||||
13084 | if (IgnoreCommaOperand(LHS)) | ||||
13085 | return; | ||||
13086 | |||||
13087 | Diag(Loc, diag::warn_comma_operator); | ||||
13088 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) | ||||
13089 | << LHS->getSourceRange() | ||||
13090 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), | ||||
13091 | LangOpts.CPlusPlus ? "static_cast<void>(" | ||||
13092 | : "(void)(") | ||||
13093 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), | ||||
13094 | ")"); | ||||
13095 | } | ||||
13096 | |||||
13097 | // C99 6.5.17 | ||||
13098 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, | ||||
13099 | SourceLocation Loc) { | ||||
13100 | LHS = S.CheckPlaceholderExpr(LHS.get()); | ||||
13101 | RHS = S.CheckPlaceholderExpr(RHS.get()); | ||||
13102 | if (LHS.isInvalid() || RHS.isInvalid()) | ||||
13103 | return QualType(); | ||||
13104 | |||||
13105 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its | ||||
13106 | // operands, but not unary promotions. | ||||
13107 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). | ||||
13108 | |||||
13109 | // So we treat the LHS as a ignored value, and in C++ we allow the | ||||
13110 | // containing site to determine what should be done with the RHS. | ||||
13111 | LHS = S.IgnoredValueConversions(LHS.get()); | ||||
13112 | if (LHS.isInvalid()) | ||||
13113 | return QualType(); | ||||
13114 | |||||
13115 | S.DiagnoseUnusedExprResult(LHS.get()); | ||||
13116 | |||||
13117 | if (!S.getLangOpts().CPlusPlus) { | ||||
13118 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); | ||||
13119 | if (RHS.isInvalid()) | ||||
13120 | return QualType(); | ||||
13121 | if (!RHS.get()->getType()->isVoidType()) | ||||
13122 | S.RequireCompleteType(Loc, RHS.get()->getType(), | ||||
13123 | diag::err_incomplete_type); | ||||
13124 | } | ||||
13125 | |||||
13126 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) | ||||
13127 | S.DiagnoseCommaOperator(LHS.get(), Loc); | ||||
13128 | |||||
13129 | return RHS.get()->getType(); | ||||
13130 | } | ||||
13131 | |||||
13132 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine | ||||
13133 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. | ||||
13134 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, | ||||
13135 | ExprValueKind &VK, | ||||
13136 | ExprObjectKind &OK, | ||||
13137 | SourceLocation OpLoc, | ||||
13138 | bool IsInc, bool IsPrefix) { | ||||
13139 | if (Op->isTypeDependent()) | ||||
13140 | return S.Context.DependentTy; | ||||
13141 | |||||
13142 | QualType ResType = Op->getType(); | ||||
13143 | // Atomic types can be used for increment / decrement where the non-atomic | ||||
13144 | // versions can, so ignore the _Atomic() specifier for the purpose of | ||||
13145 | // checking. | ||||
13146 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) | ||||
13147 | ResType = ResAtomicType->getValueType(); | ||||
13148 | |||||
13149 | assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression" ) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13149, __PRETTY_FUNCTION__)); | ||||
13150 | |||||
13151 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { | ||||
13152 | // Decrement of bool is not allowed. | ||||
13153 | if (!IsInc) { | ||||
13154 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); | ||||
13155 | return QualType(); | ||||
13156 | } | ||||
13157 | // Increment of bool sets it to true, but is deprecated. | ||||
13158 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool | ||||
13159 | : diag::warn_increment_bool) | ||||
13160 | << Op->getSourceRange(); | ||||
13161 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { | ||||
13162 | // Error on enum increments and decrements in C++ mode | ||||
13163 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; | ||||
13164 | return QualType(); | ||||
13165 | } else if (ResType->isRealType()) { | ||||
13166 | // OK! | ||||
13167 | } else if (ResType->isPointerType()) { | ||||
13168 | // C99 6.5.2.4p2, 6.5.6p2 | ||||
13169 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) | ||||
13170 | return QualType(); | ||||
13171 | } else if (ResType->isObjCObjectPointerType()) { | ||||
13172 | // On modern runtimes, ObjC pointer arithmetic is forbidden. | ||||
13173 | // Otherwise, we just need a complete type. | ||||
13174 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || | ||||
13175 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) | ||||
13176 | return QualType(); | ||||
13177 | } else if (ResType->isAnyComplexType()) { | ||||
13178 | // C99 does not support ++/-- on complex types, we allow as an extension. | ||||
13179 | S.Diag(OpLoc, diag::ext_integer_increment_complex) | ||||
13180 | << ResType << Op->getSourceRange(); | ||||
13181 | } else if (ResType->isPlaceholderType()) { | ||||
13182 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13183 | if (PR.isInvalid()) return QualType(); | ||||
13184 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, | ||||
13185 | IsInc, IsPrefix); | ||||
13186 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { | ||||
13187 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) | ||||
13188 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && | ||||
13189 | (ResType->castAs<VectorType>()->getVectorKind() != | ||||
13190 | VectorType::AltiVecBool)) { | ||||
13191 | // The z vector extensions allow ++ and -- for non-bool vectors. | ||||
13192 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && | ||||
13193 | ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { | ||||
13194 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. | ||||
13195 | } else { | ||||
13196 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) | ||||
13197 | << ResType << int(IsInc) << Op->getSourceRange(); | ||||
13198 | return QualType(); | ||||
13199 | } | ||||
13200 | // At this point, we know we have a real, complex or pointer type. | ||||
13201 | // Now make sure the operand is a modifiable lvalue. | ||||
13202 | if (CheckForModifiableLvalue(Op, OpLoc, S)) | ||||
13203 | return QualType(); | ||||
13204 | if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { | ||||
13205 | // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: | ||||
13206 | // An operand with volatile-qualified type is deprecated | ||||
13207 | S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) | ||||
13208 | << IsInc << ResType; | ||||
13209 | } | ||||
13210 | // In C++, a prefix increment is the same type as the operand. Otherwise | ||||
13211 | // (in C or with postfix), the increment is the unqualified type of the | ||||
13212 | // operand. | ||||
13213 | if (IsPrefix && S.getLangOpts().CPlusPlus) { | ||||
13214 | VK = VK_LValue; | ||||
13215 | OK = Op->getObjectKind(); | ||||
13216 | return ResType; | ||||
13217 | } else { | ||||
13218 | VK = VK_RValue; | ||||
13219 | return ResType.getUnqualifiedType(); | ||||
13220 | } | ||||
13221 | } | ||||
13222 | |||||
13223 | |||||
13224 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). | ||||
13225 | /// This routine allows us to typecheck complex/recursive expressions | ||||
13226 | /// where the declaration is needed for type checking. We only need to | ||||
13227 | /// handle cases when the expression references a function designator | ||||
13228 | /// or is an lvalue. Here are some examples: | ||||
13229 | /// - &(x) => x | ||||
13230 | /// - &*****f => f for f a function designator. | ||||
13231 | /// - &s.xx => s | ||||
13232 | /// - &s.zz[1].yy -> s, if zz is an array | ||||
13233 | /// - *(x + 1) -> x, if x is an array | ||||
13234 | /// - &"123"[2] -> 0 | ||||
13235 | /// - & __real__ x -> x | ||||
13236 | /// | ||||
13237 | /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to | ||||
13238 | /// members. | ||||
13239 | static ValueDecl *getPrimaryDecl(Expr *E) { | ||||
13240 | switch (E->getStmtClass()) { | ||||
13241 | case Stmt::DeclRefExprClass: | ||||
13242 | return cast<DeclRefExpr>(E)->getDecl(); | ||||
13243 | case Stmt::MemberExprClass: | ||||
13244 | // If this is an arrow operator, the address is an offset from | ||||
13245 | // the base's value, so the object the base refers to is | ||||
13246 | // irrelevant. | ||||
13247 | if (cast<MemberExpr>(E)->isArrow()) | ||||
13248 | return nullptr; | ||||
13249 | // Otherwise, the expression refers to a part of the base | ||||
13250 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); | ||||
13251 | case Stmt::ArraySubscriptExprClass: { | ||||
13252 | // FIXME: This code shouldn't be necessary! We should catch the implicit | ||||
13253 | // promotion of register arrays earlier. | ||||
13254 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); | ||||
13255 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
13256 | if (ICE->getSubExpr()->getType()->isArrayType()) | ||||
13257 | return getPrimaryDecl(ICE->getSubExpr()); | ||||
13258 | } | ||||
13259 | return nullptr; | ||||
13260 | } | ||||
13261 | case Stmt::UnaryOperatorClass: { | ||||
13262 | UnaryOperator *UO = cast<UnaryOperator>(E); | ||||
13263 | |||||
13264 | switch(UO->getOpcode()) { | ||||
13265 | case UO_Real: | ||||
13266 | case UO_Imag: | ||||
13267 | case UO_Extension: | ||||
13268 | return getPrimaryDecl(UO->getSubExpr()); | ||||
13269 | default: | ||||
13270 | return nullptr; | ||||
13271 | } | ||||
13272 | } | ||||
13273 | case Stmt::ParenExprClass: | ||||
13274 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); | ||||
13275 | case Stmt::ImplicitCastExprClass: | ||||
13276 | // If the result of an implicit cast is an l-value, we care about | ||||
13277 | // the sub-expression; otherwise, the result here doesn't matter. | ||||
13278 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); | ||||
13279 | case Stmt::CXXUuidofExprClass: | ||||
13280 | return cast<CXXUuidofExpr>(E)->getGuidDecl(); | ||||
13281 | default: | ||||
13282 | return nullptr; | ||||
13283 | } | ||||
13284 | } | ||||
13285 | |||||
13286 | namespace { | ||||
13287 | enum { | ||||
13288 | AO_Bit_Field = 0, | ||||
13289 | AO_Vector_Element = 1, | ||||
13290 | AO_Property_Expansion = 2, | ||||
13291 | AO_Register_Variable = 3, | ||||
13292 | AO_Matrix_Element = 4, | ||||
13293 | AO_No_Error = 5 | ||||
13294 | }; | ||||
13295 | } | ||||
13296 | /// Diagnose invalid operand for address of operations. | ||||
13297 | /// | ||||
13298 | /// \param Type The type of operand which cannot have its address taken. | ||||
13299 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, | ||||
13300 | Expr *E, unsigned Type) { | ||||
13301 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); | ||||
13302 | } | ||||
13303 | |||||
13304 | /// CheckAddressOfOperand - The operand of & must be either a function | ||||
13305 | /// designator or an lvalue designating an object. If it is an lvalue, the | ||||
13306 | /// object cannot be declared with storage class register or be a bit field. | ||||
13307 | /// Note: The usual conversions are *not* applied to the operand of the & | ||||
13308 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. | ||||
13309 | /// In C++, the operand might be an overloaded function name, in which case | ||||
13310 | /// we allow the '&' but retain the overloaded-function type. | ||||
13311 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { | ||||
13312 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ | ||||
13313 | if (PTy->getKind() == BuiltinType::Overload) { | ||||
13314 | Expr *E = OrigOp.get()->IgnoreParens(); | ||||
13315 | if (!isa<OverloadExpr>(E)) { | ||||
13316 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13316, __PRETTY_FUNCTION__)); | ||||
13317 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) | ||||
13318 | << OrigOp.get()->getSourceRange(); | ||||
13319 | return QualType(); | ||||
13320 | } | ||||
13321 | |||||
13322 | OverloadExpr *Ovl = cast<OverloadExpr>(E); | ||||
13323 | if (isa<UnresolvedMemberExpr>(Ovl)) | ||||
13324 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { | ||||
13325 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13326 | << OrigOp.get()->getSourceRange(); | ||||
13327 | return QualType(); | ||||
13328 | } | ||||
13329 | |||||
13330 | return Context.OverloadTy; | ||||
13331 | } | ||||
13332 | |||||
13333 | if (PTy->getKind() == BuiltinType::UnknownAny) | ||||
13334 | return Context.UnknownAnyTy; | ||||
13335 | |||||
13336 | if (PTy->getKind() == BuiltinType::BoundMember) { | ||||
13337 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13338 | << OrigOp.get()->getSourceRange(); | ||||
13339 | return QualType(); | ||||
13340 | } | ||||
13341 | |||||
13342 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); | ||||
13343 | if (OrigOp.isInvalid()) return QualType(); | ||||
13344 | } | ||||
13345 | |||||
13346 | if (OrigOp.get()->isTypeDependent()) | ||||
13347 | return Context.DependentTy; | ||||
13348 | |||||
13349 | assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast <void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13349, __PRETTY_FUNCTION__)); | ||||
13350 | |||||
13351 | // Make sure to ignore parentheses in subsequent checks | ||||
13352 | Expr *op = OrigOp.get()->IgnoreParens(); | ||||
13353 | |||||
13354 | // In OpenCL captures for blocks called as lambda functions | ||||
13355 | // are located in the private address space. Blocks used in | ||||
13356 | // enqueue_kernel can be located in a different address space | ||||
13357 | // depending on a vendor implementation. Thus preventing | ||||
13358 | // taking an address of the capture to avoid invalid AS casts. | ||||
13359 | if (LangOpts.OpenCL) { | ||||
13360 | auto* VarRef = dyn_cast<DeclRefExpr>(op); | ||||
13361 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { | ||||
13362 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); | ||||
13363 | return QualType(); | ||||
13364 | } | ||||
13365 | } | ||||
13366 | |||||
13367 | if (getLangOpts().C99) { | ||||
13368 | // Implement C99-only parts of addressof rules. | ||||
13369 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { | ||||
13370 | if (uOp->getOpcode() == UO_Deref) | ||||
13371 | // Per C99 6.5.3.2, the address of a deref always returns a valid result | ||||
13372 | // (assuming the deref expression is valid). | ||||
13373 | return uOp->getSubExpr()->getType(); | ||||
13374 | } | ||||
13375 | // Technically, there should be a check for array subscript | ||||
13376 | // expressions here, but the result of one is always an lvalue anyway. | ||||
13377 | } | ||||
13378 | ValueDecl *dcl = getPrimaryDecl(op); | ||||
13379 | |||||
13380 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) | ||||
13381 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||
13382 | op->getBeginLoc())) | ||||
13383 | return QualType(); | ||||
13384 | |||||
13385 | Expr::LValueClassification lval = op->ClassifyLValue(Context); | ||||
13386 | unsigned AddressOfError = AO_No_Error; | ||||
13387 | |||||
13388 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { | ||||
13389 | bool sfinae = (bool)isSFINAEContext(); | ||||
13390 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary | ||||
13391 | : diag::ext_typecheck_addrof_temporary) | ||||
13392 | << op->getType() << op->getSourceRange(); | ||||
13393 | if (sfinae) | ||||
13394 | return QualType(); | ||||
13395 | // Materialize the temporary as an lvalue so that we can take its address. | ||||
13396 | OrigOp = op = | ||||
13397 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); | ||||
13398 | } else if (isa<ObjCSelectorExpr>(op)) { | ||||
13399 | return Context.getPointerType(op->getType()); | ||||
13400 | } else if (lval == Expr::LV_MemberFunction) { | ||||
13401 | // If it's an instance method, make a member pointer. | ||||
13402 | // The expression must have exactly the form &A::foo. | ||||
13403 | |||||
13404 | // If the underlying expression isn't a decl ref, give up. | ||||
13405 | if (!isa<DeclRefExpr>(op)) { | ||||
13406 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) | ||||
13407 | << OrigOp.get()->getSourceRange(); | ||||
13408 | return QualType(); | ||||
13409 | } | ||||
13410 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); | ||||
13411 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); | ||||
13412 | |||||
13413 | // The id-expression was parenthesized. | ||||
13414 | if (OrigOp.get() != DRE) { | ||||
13415 | Diag(OpLoc, diag::err_parens_pointer_member_function) | ||||
13416 | << OrigOp.get()->getSourceRange(); | ||||
13417 | |||||
13418 | // The method was named without a qualifier. | ||||
13419 | } else if (!DRE->getQualifier()) { | ||||
13420 | if (MD->getParent()->getName().empty()) | ||||
13421 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13422 | << op->getSourceRange(); | ||||
13423 | else { | ||||
13424 | SmallString<32> Str; | ||||
13425 | StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); | ||||
13426 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) | ||||
13427 | << op->getSourceRange() | ||||
13428 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); | ||||
13429 | } | ||||
13430 | } | ||||
13431 | |||||
13432 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. | ||||
13433 | if (isa<CXXDestructorDecl>(MD)) | ||||
13434 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); | ||||
13435 | |||||
13436 | QualType MPTy = Context.getMemberPointerType( | ||||
13437 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); | ||||
13438 | // Under the MS ABI, lock down the inheritance model now. | ||||
13439 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13440 | (void)isCompleteType(OpLoc, MPTy); | ||||
13441 | return MPTy; | ||||
13442 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { | ||||
13443 | // C99 6.5.3.2p1 | ||||
13444 | // The operand must be either an l-value or a function designator | ||||
13445 | if (!op->getType()->isFunctionType()) { | ||||
13446 | // Use a special diagnostic for loads from property references. | ||||
13447 | if (isa<PseudoObjectExpr>(op)) { | ||||
13448 | AddressOfError = AO_Property_Expansion; | ||||
13449 | } else { | ||||
13450 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) | ||||
13451 | << op->getType() << op->getSourceRange(); | ||||
13452 | return QualType(); | ||||
13453 | } | ||||
13454 | } | ||||
13455 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 | ||||
13456 | // The operand cannot be a bit-field | ||||
13457 | AddressOfError = AO_Bit_Field; | ||||
13458 | } else if (op->getObjectKind() == OK_VectorComponent) { | ||||
13459 | // The operand cannot be an element of a vector | ||||
13460 | AddressOfError = AO_Vector_Element; | ||||
13461 | } else if (op->getObjectKind() == OK_MatrixComponent) { | ||||
13462 | // The operand cannot be an element of a matrix. | ||||
13463 | AddressOfError = AO_Matrix_Element; | ||||
13464 | } else if (dcl) { // C99 6.5.3.2p1 | ||||
13465 | // We have an lvalue with a decl. Make sure the decl is not declared | ||||
13466 | // with the register storage-class specifier. | ||||
13467 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { | ||||
13468 | // in C++ it is not error to take address of a register | ||||
13469 | // variable (c++03 7.1.1P3) | ||||
13470 | if (vd->getStorageClass() == SC_Register && | ||||
13471 | !getLangOpts().CPlusPlus) { | ||||
13472 | AddressOfError = AO_Register_Variable; | ||||
13473 | } | ||||
13474 | } else if (isa<MSPropertyDecl>(dcl)) { | ||||
13475 | AddressOfError = AO_Property_Expansion; | ||||
13476 | } else if (isa<FunctionTemplateDecl>(dcl)) { | ||||
13477 | return Context.OverloadTy; | ||||
13478 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { | ||||
13479 | // Okay: we can take the address of a field. | ||||
13480 | // Could be a pointer to member, though, if there is an explicit | ||||
13481 | // scope qualifier for the class. | ||||
13482 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { | ||||
13483 | DeclContext *Ctx = dcl->getDeclContext(); | ||||
13484 | if (Ctx && Ctx->isRecord()) { | ||||
13485 | if (dcl->getType()->isReferenceType()) { | ||||
13486 | Diag(OpLoc, | ||||
13487 | diag::err_cannot_form_pointer_to_member_of_reference_type) | ||||
13488 | << dcl->getDeclName() << dcl->getType(); | ||||
13489 | return QualType(); | ||||
13490 | } | ||||
13491 | |||||
13492 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) | ||||
13493 | Ctx = Ctx->getParent(); | ||||
13494 | |||||
13495 | QualType MPTy = Context.getMemberPointerType( | ||||
13496 | op->getType(), | ||||
13497 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); | ||||
13498 | // Under the MS ABI, lock down the inheritance model now. | ||||
13499 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
13500 | (void)isCompleteType(OpLoc, MPTy); | ||||
13501 | return MPTy; | ||||
13502 | } | ||||
13503 | } | ||||
13504 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && | ||||
13505 | !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) | ||||
13506 | llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13506); | ||||
13507 | } | ||||
13508 | |||||
13509 | if (AddressOfError != AO_No_Error) { | ||||
13510 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); | ||||
13511 | return QualType(); | ||||
13512 | } | ||||
13513 | |||||
13514 | if (lval == Expr::LV_IncompleteVoidType) { | ||||
13515 | // Taking the address of a void variable is technically illegal, but we | ||||
13516 | // allow it in cases which are otherwise valid. | ||||
13517 | // Example: "extern void x; void* y = &x;". | ||||
13518 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); | ||||
13519 | } | ||||
13520 | |||||
13521 | // If the operand has type "type", the result has type "pointer to type". | ||||
13522 | if (op->getType()->isObjCObjectType()) | ||||
13523 | return Context.getObjCObjectPointerType(op->getType()); | ||||
13524 | |||||
13525 | CheckAddressOfPackedMember(op); | ||||
13526 | |||||
13527 | return Context.getPointerType(op->getType()); | ||||
13528 | } | ||||
13529 | |||||
13530 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { | ||||
13531 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); | ||||
13532 | if (!DRE) | ||||
13533 | return; | ||||
13534 | const Decl *D = DRE->getDecl(); | ||||
13535 | if (!D) | ||||
13536 | return; | ||||
13537 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); | ||||
13538 | if (!Param) | ||||
13539 | return; | ||||
13540 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) | ||||
13541 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) | ||||
13542 | return; | ||||
13543 | if (FunctionScopeInfo *FD = S.getCurFunction()) | ||||
13544 | if (!FD->ModifiedNonNullParams.count(Param)) | ||||
13545 | FD->ModifiedNonNullParams.insert(Param); | ||||
13546 | } | ||||
13547 | |||||
13548 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). | ||||
13549 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, | ||||
13550 | SourceLocation OpLoc) { | ||||
13551 | if (Op->isTypeDependent()) | ||||
13552 | return S.Context.DependentTy; | ||||
13553 | |||||
13554 | ExprResult ConvResult = S.UsualUnaryConversions(Op); | ||||
13555 | if (ConvResult.isInvalid()) | ||||
13556 | return QualType(); | ||||
13557 | Op = ConvResult.get(); | ||||
13558 | QualType OpTy = Op->getType(); | ||||
13559 | QualType Result; | ||||
13560 | |||||
13561 | if (isa<CXXReinterpretCastExpr>(Op)) { | ||||
13562 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); | ||||
13563 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, | ||||
13564 | Op->getSourceRange()); | ||||
13565 | } | ||||
13566 | |||||
13567 | if (const PointerType *PT = OpTy->getAs<PointerType>()) | ||||
13568 | { | ||||
13569 | Result = PT->getPointeeType(); | ||||
13570 | } | ||||
13571 | else if (const ObjCObjectPointerType *OPT = | ||||
13572 | OpTy->getAs<ObjCObjectPointerType>()) | ||||
13573 | Result = OPT->getPointeeType(); | ||||
13574 | else { | ||||
13575 | ExprResult PR = S.CheckPlaceholderExpr(Op); | ||||
13576 | if (PR.isInvalid()) return QualType(); | ||||
13577 | if (PR.get() != Op) | ||||
13578 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); | ||||
13579 | } | ||||
13580 | |||||
13581 | if (Result.isNull()) { | ||||
13582 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) | ||||
13583 | << OpTy << Op->getSourceRange(); | ||||
13584 | return QualType(); | ||||
13585 | } | ||||
13586 | |||||
13587 | // Note that per both C89 and C99, indirection is always legal, even if Result | ||||
13588 | // is an incomplete type or void. It would be possible to warn about | ||||
13589 | // dereferencing a void pointer, but it's completely well-defined, and such a | ||||
13590 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid | ||||
13591 | // for pointers to 'void' but is fine for any other pointer type: | ||||
13592 | // | ||||
13593 | // C++ [expr.unary.op]p1: | ||||
13594 | // [...] the expression to which [the unary * operator] is applied shall | ||||
13595 | // be a pointer to an object type, or a pointer to a function type | ||||
13596 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) | ||||
13597 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) | ||||
13598 | << OpTy << Op->getSourceRange(); | ||||
13599 | |||||
13600 | // Dereferences are usually l-values... | ||||
13601 | VK = VK_LValue; | ||||
13602 | |||||
13603 | // ...except that certain expressions are never l-values in C. | ||||
13604 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) | ||||
13605 | VK = VK_RValue; | ||||
13606 | |||||
13607 | return Result; | ||||
13608 | } | ||||
13609 | |||||
13610 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { | ||||
13611 | BinaryOperatorKind Opc; | ||||
13612 | switch (Kind) { | ||||
13613 | default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13613); | ||||
13614 | case tok::periodstar: Opc = BO_PtrMemD; break; | ||||
13615 | case tok::arrowstar: Opc = BO_PtrMemI; break; | ||||
13616 | case tok::star: Opc = BO_Mul; break; | ||||
13617 | case tok::slash: Opc = BO_Div; break; | ||||
13618 | case tok::percent: Opc = BO_Rem; break; | ||||
13619 | case tok::plus: Opc = BO_Add; break; | ||||
13620 | case tok::minus: Opc = BO_Sub; break; | ||||
13621 | case tok::lessless: Opc = BO_Shl; break; | ||||
13622 | case tok::greatergreater: Opc = BO_Shr; break; | ||||
13623 | case tok::lessequal: Opc = BO_LE; break; | ||||
13624 | case tok::less: Opc = BO_LT; break; | ||||
13625 | case tok::greaterequal: Opc = BO_GE; break; | ||||
13626 | case tok::greater: Opc = BO_GT; break; | ||||
13627 | case tok::exclaimequal: Opc = BO_NE; break; | ||||
13628 | case tok::equalequal: Opc = BO_EQ; break; | ||||
13629 | case tok::spaceship: Opc = BO_Cmp; break; | ||||
13630 | case tok::amp: Opc = BO_And; break; | ||||
13631 | case tok::caret: Opc = BO_Xor; break; | ||||
13632 | case tok::pipe: Opc = BO_Or; break; | ||||
13633 | case tok::ampamp: Opc = BO_LAnd; break; | ||||
13634 | case tok::pipepipe: Opc = BO_LOr; break; | ||||
13635 | case tok::equal: Opc = BO_Assign; break; | ||||
13636 | case tok::starequal: Opc = BO_MulAssign; break; | ||||
13637 | case tok::slashequal: Opc = BO_DivAssign; break; | ||||
13638 | case tok::percentequal: Opc = BO_RemAssign; break; | ||||
13639 | case tok::plusequal: Opc = BO_AddAssign; break; | ||||
13640 | case tok::minusequal: Opc = BO_SubAssign; break; | ||||
13641 | case tok::lesslessequal: Opc = BO_ShlAssign; break; | ||||
13642 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; | ||||
13643 | case tok::ampequal: Opc = BO_AndAssign; break; | ||||
13644 | case tok::caretequal: Opc = BO_XorAssign; break; | ||||
13645 | case tok::pipeequal: Opc = BO_OrAssign; break; | ||||
13646 | case tok::comma: Opc = BO_Comma; break; | ||||
13647 | } | ||||
13648 | return Opc; | ||||
13649 | } | ||||
13650 | |||||
13651 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( | ||||
13652 | tok::TokenKind Kind) { | ||||
13653 | UnaryOperatorKind Opc; | ||||
13654 | switch (Kind) { | ||||
13655 | default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13655); | ||||
13656 | case tok::plusplus: Opc = UO_PreInc; break; | ||||
13657 | case tok::minusminus: Opc = UO_PreDec; break; | ||||
13658 | case tok::amp: Opc = UO_AddrOf; break; | ||||
13659 | case tok::star: Opc = UO_Deref; break; | ||||
13660 | case tok::plus: Opc = UO_Plus; break; | ||||
13661 | case tok::minus: Opc = UO_Minus; break; | ||||
13662 | case tok::tilde: Opc = UO_Not; break; | ||||
13663 | case tok::exclaim: Opc = UO_LNot; break; | ||||
13664 | case tok::kw___real: Opc = UO_Real; break; | ||||
13665 | case tok::kw___imag: Opc = UO_Imag; break; | ||||
13666 | case tok::kw___extension__: Opc = UO_Extension; break; | ||||
13667 | } | ||||
13668 | return Opc; | ||||
13669 | } | ||||
13670 | |||||
13671 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. | ||||
13672 | /// This warning suppressed in the event of macro expansions. | ||||
13673 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, | ||||
13674 | SourceLocation OpLoc, bool IsBuiltin) { | ||||
13675 | if (S.inTemplateInstantiation()) | ||||
13676 | return; | ||||
13677 | if (S.isUnevaluatedContext()) | ||||
13678 | return; | ||||
13679 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) | ||||
13680 | return; | ||||
13681 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); | ||||
13682 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); | ||||
13683 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); | ||||
13684 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); | ||||
13685 | if (!LHSDeclRef || !RHSDeclRef || | ||||
13686 | LHSDeclRef->getLocation().isMacroID() || | ||||
13687 | RHSDeclRef->getLocation().isMacroID()) | ||||
13688 | return; | ||||
13689 | const ValueDecl *LHSDecl = | ||||
13690 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13691 | const ValueDecl *RHSDecl = | ||||
13692 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); | ||||
13693 | if (LHSDecl != RHSDecl) | ||||
13694 | return; | ||||
13695 | if (LHSDecl->getType().isVolatileQualified()) | ||||
13696 | return; | ||||
13697 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) | ||||
13698 | if (RefTy->getPointeeType().isVolatileQualified()) | ||||
13699 | return; | ||||
13700 | |||||
13701 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin | ||||
13702 | : diag::warn_self_assignment_overloaded) | ||||
13703 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() | ||||
13704 | << RHSExpr->getSourceRange(); | ||||
13705 | } | ||||
13706 | |||||
13707 | /// Check if a bitwise-& is performed on an Objective-C pointer. This | ||||
13708 | /// is usually indicative of introspection within the Objective-C pointer. | ||||
13709 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, | ||||
13710 | SourceLocation OpLoc) { | ||||
13711 | if (!S.getLangOpts().ObjC) | ||||
13712 | return; | ||||
13713 | |||||
13714 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; | ||||
13715 | const Expr *LHS = L.get(); | ||||
13716 | const Expr *RHS = R.get(); | ||||
13717 | |||||
13718 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
13719 | ObjCPointerExpr = LHS; | ||||
13720 | OtherExpr = RHS; | ||||
13721 | } | ||||
13722 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { | ||||
13723 | ObjCPointerExpr = RHS; | ||||
13724 | OtherExpr = LHS; | ||||
13725 | } | ||||
13726 | |||||
13727 | // This warning is deliberately made very specific to reduce false | ||||
13728 | // positives with logic that uses '&' for hashing. This logic mainly | ||||
13729 | // looks for code trying to introspect into tagged pointers, which | ||||
13730 | // code should generally never do. | ||||
13731 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { | ||||
13732 | unsigned Diag = diag::warn_objc_pointer_masking; | ||||
13733 | // Determine if we are introspecting the result of performSelectorXXX. | ||||
13734 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); | ||||
13735 | // Special case messages to -performSelector and friends, which | ||||
13736 | // can return non-pointer values boxed in a pointer value. | ||||
13737 | // Some clients may wish to silence warnings in this subcase. | ||||
13738 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { | ||||
13739 | Selector S = ME->getSelector(); | ||||
13740 | StringRef SelArg0 = S.getNameForSlot(0); | ||||
13741 | if (SelArg0.startswith("performSelector")) | ||||
13742 | Diag = diag::warn_objc_pointer_masking_performSelector; | ||||
13743 | } | ||||
13744 | |||||
13745 | S.Diag(OpLoc, Diag) | ||||
13746 | << ObjCPointerExpr->getSourceRange(); | ||||
13747 | } | ||||
13748 | } | ||||
13749 | |||||
13750 | static NamedDecl *getDeclFromExpr(Expr *E) { | ||||
13751 | if (!E) | ||||
13752 | return nullptr; | ||||
13753 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
13754 | return DRE->getDecl(); | ||||
13755 | if (auto *ME = dyn_cast<MemberExpr>(E)) | ||||
13756 | return ME->getMemberDecl(); | ||||
13757 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) | ||||
13758 | return IRE->getDecl(); | ||||
13759 | return nullptr; | ||||
13760 | } | ||||
13761 | |||||
13762 | // This helper function promotes a binary operator's operands (which are of a | ||||
13763 | // half vector type) to a vector of floats and then truncates the result to | ||||
13764 | // a vector of either half or short. | ||||
13765 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, | ||||
13766 | BinaryOperatorKind Opc, QualType ResultTy, | ||||
13767 | ExprValueKind VK, ExprObjectKind OK, | ||||
13768 | bool IsCompAssign, SourceLocation OpLoc, | ||||
13769 | FPOptionsOverride FPFeatures) { | ||||
13770 | auto &Context = S.getASTContext(); | ||||
13771 | assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13773, __PRETTY_FUNCTION__)) | ||||
13772 | isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13773, __PRETTY_FUNCTION__)) | ||||
13773 | "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context .ShortTy)) && "Result must be a vector of half or short" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13773, __PRETTY_FUNCTION__)); | ||||
13774 | assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< 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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13776, __PRETTY_FUNCTION__)) | ||||
13775 | isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< 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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13776, __PRETTY_FUNCTION__)) | ||||
13776 | "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && "both operands expected to be a half vector") ? static_cast< 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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13776, __PRETTY_FUNCTION__)); | ||||
13777 | |||||
13778 | RHS = convertVector(RHS.get(), Context.FloatTy, S); | ||||
13779 | QualType BinOpResTy = RHS.get()->getType(); | ||||
13780 | |||||
13781 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, | ||||
13782 | // change BinOpResTy to a vector of ints. | ||||
13783 | if (isVector(ResultTy, Context.ShortTy)) | ||||
13784 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); | ||||
13785 | |||||
13786 | if (IsCompAssign) | ||||
13787 | return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
13788 | ResultTy, VK, OK, OpLoc, FPFeatures, | ||||
13789 | BinOpResTy, BinOpResTy); | ||||
13790 | |||||
13791 | LHS = convertVector(LHS.get(), Context.FloatTy, S); | ||||
13792 | auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, | ||||
13793 | BinOpResTy, VK, OK, OpLoc, FPFeatures); | ||||
13794 | return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); | ||||
13795 | } | ||||
13796 | |||||
13797 | static std::pair<ExprResult, ExprResult> | ||||
13798 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, | ||||
13799 | Expr *RHSExpr) { | ||||
13800 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
13801 | if (!S.Context.isDependenceAllowed()) { | ||||
13802 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
13803 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
13804 | // been dealt with before checking the operands. | ||||
13805 | LHS = S.CorrectDelayedTyposInExpr(LHS); | ||||
13806 | RHS = S.CorrectDelayedTyposInExpr( | ||||
13807 | RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, | ||||
13808 | [Opc, LHS](Expr *E) { | ||||
13809 | if (Opc != BO_Assign) | ||||
13810 | return ExprResult(E); | ||||
13811 | // Avoid correcting the RHS to the same Expr as the LHS. | ||||
13812 | Decl *D = getDeclFromExpr(E); | ||||
13813 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; | ||||
13814 | }); | ||||
13815 | } | ||||
13816 | return std::make_pair(LHS, RHS); | ||||
13817 | } | ||||
13818 | |||||
13819 | /// Returns true if conversion between vectors of halfs and vectors of floats | ||||
13820 | /// is needed. | ||||
13821 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, | ||||
13822 | Expr *E0, Expr *E1 = nullptr) { | ||||
13823 | if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || | ||||
13824 | Ctx.getTargetInfo().useFP16ConversionIntrinsics()) | ||||
13825 | return false; | ||||
13826 | |||||
13827 | auto HasVectorOfHalfType = [&Ctx](Expr *E) { | ||||
13828 | QualType Ty = E->IgnoreImplicit()->getType(); | ||||
13829 | |||||
13830 | // Don't promote half precision neon vectors like float16x4_t in arm_neon.h | ||||
13831 | // to vectors of floats. Although the element type of the vectors is __fp16, | ||||
13832 | // the vectors shouldn't be treated as storage-only types. See the | ||||
13833 | // discussion here: https://reviews.llvm.org/rG825235c140e7 | ||||
13834 | if (const VectorType *VT = Ty->getAs<VectorType>()) { | ||||
13835 | if (VT->getVectorKind() == VectorType::NeonVector) | ||||
13836 | return false; | ||||
13837 | return VT->getElementType().getCanonicalType() == Ctx.HalfTy; | ||||
13838 | } | ||||
13839 | return false; | ||||
13840 | }; | ||||
13841 | |||||
13842 | return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); | ||||
13843 | } | ||||
13844 | |||||
13845 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with | ||||
13846 | /// operator @p Opc at location @c TokLoc. This routine only supports | ||||
13847 | /// built-in operations; ActOnBinOp handles overloaded operators. | ||||
13848 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, | ||||
13849 | BinaryOperatorKind Opc, | ||||
13850 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
13851 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { | ||||
13852 | // The syntax only allows initializer lists on the RHS of assignment, | ||||
13853 | // so we don't need to worry about accepting invalid code for | ||||
13854 | // non-assignment operators. | ||||
13855 | // C++11 5.17p9: | ||||
13856 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning | ||||
13857 | // of x = {} is x = T(). | ||||
13858 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||
13859 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
13860 | InitializedEntity Entity = | ||||
13861 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); | ||||
13862 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); | ||||
13863 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); | ||||
13864 | if (Init.isInvalid()) | ||||
13865 | return Init; | ||||
13866 | RHSExpr = Init.get(); | ||||
13867 | } | ||||
13868 | |||||
13869 | ExprResult LHS = LHSExpr, RHS = RHSExpr; | ||||
13870 | QualType ResultTy; // Result type of the binary operator. | ||||
13871 | // The following two variables are used for compound assignment operators | ||||
13872 | QualType CompLHSTy; // Type of LHS after promotions for computation | ||||
13873 | QualType CompResultTy; // Type of computation result | ||||
13874 | ExprValueKind VK = VK_RValue; | ||||
13875 | ExprObjectKind OK = OK_Ordinary; | ||||
13876 | bool ConvertHalfVec = false; | ||||
13877 | |||||
13878 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
13879 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
13880 | return ExprError(); | ||||
13881 | |||||
13882 | if (getLangOpts().OpenCL) { | ||||
13883 | QualType LHSTy = LHSExpr->getType(); | ||||
13884 | QualType RHSTy = RHSExpr->getType(); | ||||
13885 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by | ||||
13886 | // the ATOMIC_VAR_INIT macro. | ||||
13887 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { | ||||
13888 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); | ||||
13889 | if (BO_Assign == Opc) | ||||
13890 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; | ||||
13891 | else | ||||
13892 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
13893 | return ExprError(); | ||||
13894 | } | ||||
13895 | |||||
13896 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
13897 | // only with a builtin functions and therefore should be disallowed here. | ||||
13898 | if (LHSTy->isImageType() || RHSTy->isImageType() || | ||||
13899 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || | ||||
13900 | LHSTy->isPipeType() || RHSTy->isPipeType() || | ||||
13901 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { | ||||
13902 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); | ||||
13903 | return ExprError(); | ||||
13904 | } | ||||
13905 | } | ||||
13906 | |||||
13907 | switch (Opc) { | ||||
13908 | case BO_Assign: | ||||
13909 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); | ||||
13910 | if (getLangOpts().CPlusPlus && | ||||
13911 | LHS.get()->getObjectKind() != OK_ObjCProperty) { | ||||
13912 | VK = LHS.get()->getValueKind(); | ||||
13913 | OK = LHS.get()->getObjectKind(); | ||||
13914 | } | ||||
13915 | if (!ResultTy.isNull()) { | ||||
13916 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
13917 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); | ||||
13918 | |||||
13919 | // Avoid copying a block to the heap if the block is assigned to a local | ||||
13920 | // auto variable that is declared in the same scope as the block. This | ||||
13921 | // optimization is unsafe if the local variable is declared in an outer | ||||
13922 | // scope. For example: | ||||
13923 | // | ||||
13924 | // BlockTy b; | ||||
13925 | // { | ||||
13926 | // b = ^{...}; | ||||
13927 | // } | ||||
13928 | // // It is unsafe to invoke the block here if it wasn't copied to the | ||||
13929 | // // heap. | ||||
13930 | // b(); | ||||
13931 | |||||
13932 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) | ||||
13933 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) | ||||
13934 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) | ||||
13935 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) | ||||
13936 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
13937 | |||||
13938 | if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
13939 | checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), | ||||
13940 | NTCUC_Assignment, NTCUK_Copy); | ||||
13941 | } | ||||
13942 | RecordModifiableNonNullParam(*this, LHS.get()); | ||||
13943 | break; | ||||
13944 | case BO_PtrMemD: | ||||
13945 | case BO_PtrMemI: | ||||
13946 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, | ||||
13947 | Opc == BO_PtrMemI); | ||||
13948 | break; | ||||
13949 | case BO_Mul: | ||||
13950 | case BO_Div: | ||||
13951 | ConvertHalfVec = true; | ||||
13952 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, | ||||
13953 | Opc == BO_Div); | ||||
13954 | break; | ||||
13955 | case BO_Rem: | ||||
13956 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); | ||||
13957 | break; | ||||
13958 | case BO_Add: | ||||
13959 | ConvertHalfVec = true; | ||||
13960 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); | ||||
13961 | break; | ||||
13962 | case BO_Sub: | ||||
13963 | ConvertHalfVec = true; | ||||
13964 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); | ||||
13965 | break; | ||||
13966 | case BO_Shl: | ||||
13967 | case BO_Shr: | ||||
13968 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); | ||||
13969 | break; | ||||
13970 | case BO_LE: | ||||
13971 | case BO_LT: | ||||
13972 | case BO_GE: | ||||
13973 | case BO_GT: | ||||
13974 | ConvertHalfVec = true; | ||||
13975 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
13976 | break; | ||||
13977 | case BO_EQ: | ||||
13978 | case BO_NE: | ||||
13979 | ConvertHalfVec = true; | ||||
13980 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
13981 | break; | ||||
13982 | case BO_Cmp: | ||||
13983 | ConvertHalfVec = true; | ||||
13984 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); | ||||
13985 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast <void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 13985, __PRETTY_FUNCTION__)); | ||||
13986 | break; | ||||
13987 | case BO_And: | ||||
13988 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); | ||||
13989 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
13990 | case BO_Xor: | ||||
13991 | case BO_Or: | ||||
13992 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
13993 | break; | ||||
13994 | case BO_LAnd: | ||||
13995 | case BO_LOr: | ||||
13996 | ConvertHalfVec = true; | ||||
13997 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); | ||||
13998 | break; | ||||
13999 | case BO_MulAssign: | ||||
14000 | case BO_DivAssign: | ||||
14001 | ConvertHalfVec = true; | ||||
14002 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, | ||||
14003 | Opc == BO_DivAssign); | ||||
14004 | CompLHSTy = CompResultTy; | ||||
14005 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14006 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14007 | break; | ||||
14008 | case BO_RemAssign: | ||||
14009 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); | ||||
14010 | CompLHSTy = CompResultTy; | ||||
14011 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14012 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14013 | break; | ||||
14014 | case BO_AddAssign: | ||||
14015 | ConvertHalfVec = true; | ||||
14016 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); | ||||
14017 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14018 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14019 | break; | ||||
14020 | case BO_SubAssign: | ||||
14021 | ConvertHalfVec = true; | ||||
14022 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); | ||||
14023 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14024 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14025 | break; | ||||
14026 | case BO_ShlAssign: | ||||
14027 | case BO_ShrAssign: | ||||
14028 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); | ||||
14029 | CompLHSTy = CompResultTy; | ||||
14030 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14031 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14032 | break; | ||||
14033 | case BO_AndAssign: | ||||
14034 | case BO_OrAssign: // fallthrough | ||||
14035 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); | ||||
14036 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14037 | case BO_XorAssign: | ||||
14038 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); | ||||
14039 | CompLHSTy = CompResultTy; | ||||
14040 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) | ||||
14041 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); | ||||
14042 | break; | ||||
14043 | case BO_Comma: | ||||
14044 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); | ||||
14045 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { | ||||
14046 | VK = RHS.get()->getValueKind(); | ||||
14047 | OK = RHS.get()->getObjectKind(); | ||||
14048 | } | ||||
14049 | break; | ||||
14050 | } | ||||
14051 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) | ||||
14052 | return ExprError(); | ||||
14053 | |||||
14054 | // Some of the binary operations require promoting operands of half vector to | ||||
14055 | // float vectors and truncating the result back to half vector. For now, we do | ||||
14056 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or | ||||
14057 | // arm64). | ||||
14058 | assert((((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14061, __PRETTY_FUNCTION__)) | ||||
14059 | (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14061, __PRETTY_FUNCTION__)) | ||||
14060 | isVector(LHS.get()->getType(), Context.HalfTy)) &&(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14061, __PRETTY_FUNCTION__)) | ||||
14061 | "both sides are half vectors or neither sides are")(((Opc == BO_Comma || isVector(RHS.get()->getType(), Context .HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) ) && "both sides are half vectors or neither sides are" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14061, __PRETTY_FUNCTION__)); | ||||
14062 | ConvertHalfVec = | ||||
14063 | needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); | ||||
14064 | |||||
14065 | // Check for array bounds violations for both sides of the BinaryOperator | ||||
14066 | CheckArrayAccess(LHS.get()); | ||||
14067 | CheckArrayAccess(RHS.get()); | ||||
14068 | |||||
14069 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { | ||||
14070 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, | ||||
14071 | &Context.Idents.get("object_setClass"), | ||||
14072 | SourceLocation(), LookupOrdinaryName); | ||||
14073 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { | ||||
14074 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); | ||||
14075 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) | ||||
14076 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), | ||||
14077 | "object_setClass(") | ||||
14078 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), | ||||
14079 | ",") | ||||
14080 | << FixItHint::CreateInsertion(RHSLocEnd, ")"); | ||||
14081 | } | ||||
14082 | else | ||||
14083 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); | ||||
14084 | } | ||||
14085 | else if (const ObjCIvarRefExpr *OIRE = | ||||
14086 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) | ||||
14087 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); | ||||
14088 | |||||
14089 | // Opc is not a compound assignment if CompResultTy is null. | ||||
14090 | if (CompResultTy.isNull()) { | ||||
14091 | if (ConvertHalfVec) | ||||
14092 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, | ||||
14093 | OpLoc, CurFPFeatureOverrides()); | ||||
14094 | return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, | ||||
14095 | VK, OK, OpLoc, CurFPFeatureOverrides()); | ||||
14096 | } | ||||
14097 | |||||
14098 | // Handle compound assignments. | ||||
14099 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != | ||||
14100 | OK_ObjCProperty) { | ||||
14101 | VK = VK_LValue; | ||||
14102 | OK = LHS.get()->getObjectKind(); | ||||
14103 | } | ||||
14104 | |||||
14105 | // The LHS is not converted to the result type for fixed-point compound | ||||
14106 | // assignment as the common type is computed on demand. Reset the CompLHSTy | ||||
14107 | // to the LHS type we would have gotten after unary conversions. | ||||
14108 | if (CompResultTy->isFixedPointType()) | ||||
14109 | CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); | ||||
14110 | |||||
14111 | if (ConvertHalfVec) | ||||
14112 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, | ||||
14113 | OpLoc, CurFPFeatureOverrides()); | ||||
14114 | |||||
14115 | return CompoundAssignOperator::Create( | ||||
14116 | Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, | ||||
14117 | CurFPFeatureOverrides(), CompLHSTy, CompResultTy); | ||||
14118 | } | ||||
14119 | |||||
14120 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison | ||||
14121 | /// operators are mixed in a way that suggests that the programmer forgot that | ||||
14122 | /// comparison operators have higher precedence. The most typical example of | ||||
14123 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". | ||||
14124 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14125 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14126 | Expr *RHSExpr) { | ||||
14127 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); | ||||
14128 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); | ||||
14129 | |||||
14130 | // Check that one of the sides is a comparison operator and the other isn't. | ||||
14131 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); | ||||
14132 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); | ||||
14133 | if (isLeftComp == isRightComp) | ||||
14134 | return; | ||||
14135 | |||||
14136 | // Bitwise operations are sometimes used as eager logical ops. | ||||
14137 | // Don't diagnose this. | ||||
14138 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); | ||||
14139 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); | ||||
14140 | if (isLeftBitwise || isRightBitwise) | ||||
14141 | return; | ||||
14142 | |||||
14143 | SourceRange DiagRange = isLeftComp | ||||
14144 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) | ||||
14145 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); | ||||
14146 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); | ||||
14147 | SourceRange ParensRange = | ||||
14148 | isLeftComp | ||||
14149 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) | ||||
14150 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); | ||||
14151 | |||||
14152 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) | ||||
14153 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; | ||||
14154 | SuggestParentheses(Self, OpLoc, | ||||
14155 | Self.PDiag(diag::note_precedence_silence) << OpStr, | ||||
14156 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); | ||||
14157 | SuggestParentheses(Self, OpLoc, | ||||
14158 | Self.PDiag(diag::note_precedence_bitwise_first) | ||||
14159 | << BinaryOperator::getOpcodeStr(Opc), | ||||
14160 | ParensRange); | ||||
14161 | } | ||||
14162 | |||||
14163 | /// It accepts a '&&' expr that is inside a '||' one. | ||||
14164 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression | ||||
14165 | /// in parentheses. | ||||
14166 | static void | ||||
14167 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, | ||||
14168 | BinaryOperator *Bop) { | ||||
14169 | assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> ( 0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14169, __PRETTY_FUNCTION__)); | ||||
14170 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) | ||||
14171 | << Bop->getSourceRange() << OpLoc; | ||||
14172 | SuggestParentheses(Self, Bop->getOperatorLoc(), | ||||
14173 | Self.PDiag(diag::note_precedence_silence) | ||||
14174 | << Bop->getOpcodeStr(), | ||||
14175 | Bop->getSourceRange()); | ||||
14176 | } | ||||
14177 | |||||
14178 | /// Returns true if the given expression can be evaluated as a constant | ||||
14179 | /// 'true'. | ||||
14180 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { | ||||
14181 | bool Res; | ||||
14182 | return !E->isValueDependent() && | ||||
14183 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; | ||||
14184 | } | ||||
14185 | |||||
14186 | /// Returns true if the given expression can be evaluated as a constant | ||||
14187 | /// 'false'. | ||||
14188 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { | ||||
14189 | bool Res; | ||||
14190 | return !E->isValueDependent() && | ||||
14191 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; | ||||
14192 | } | ||||
14193 | |||||
14194 | /// Look for '&&' in the left hand of a '||' expr. | ||||
14195 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, | ||||
14196 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14197 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { | ||||
14198 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14199 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. | ||||
14200 | if (EvaluatesAsFalse(S, RHSExpr)) | ||||
14201 | return; | ||||
14202 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. | ||||
14203 | if (!EvaluatesAsTrue(S, Bop->getLHS())) | ||||
14204 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14205 | } else if (Bop->getOpcode() == BO_LOr) { | ||||
14206 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { | ||||
14207 | // If it's "a || b && 1 || c" we didn't warn earlier for | ||||
14208 | // "a || b && 1", but warn now. | ||||
14209 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) | ||||
14210 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); | ||||
14211 | } | ||||
14212 | } | ||||
14213 | } | ||||
14214 | } | ||||
14215 | |||||
14216 | /// Look for '&&' in the right hand of a '||' expr. | ||||
14217 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, | ||||
14218 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14219 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { | ||||
14220 | if (Bop->getOpcode() == BO_LAnd) { | ||||
14221 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. | ||||
14222 | if (EvaluatesAsFalse(S, LHSExpr)) | ||||
14223 | return; | ||||
14224 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. | ||||
14225 | if (!EvaluatesAsTrue(S, Bop->getRHS())) | ||||
14226 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); | ||||
14227 | } | ||||
14228 | } | ||||
14229 | } | ||||
14230 | |||||
14231 | /// Look for bitwise op in the left or right hand of a bitwise op with | ||||
14232 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps | ||||
14233 | /// the '&' expression in parentheses. | ||||
14234 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, | ||||
14235 | SourceLocation OpLoc, Expr *SubExpr) { | ||||
14236 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14237 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { | ||||
14238 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) | ||||
14239 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) | ||||
14240 | << Bop->getSourceRange() << OpLoc; | ||||
14241 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14242 | S.PDiag(diag::note_precedence_silence) | ||||
14243 | << Bop->getOpcodeStr(), | ||||
14244 | Bop->getSourceRange()); | ||||
14245 | } | ||||
14246 | } | ||||
14247 | } | ||||
14248 | |||||
14249 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, | ||||
14250 | Expr *SubExpr, StringRef Shift) { | ||||
14251 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { | ||||
14252 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { | ||||
14253 | StringRef Op = Bop->getOpcodeStr(); | ||||
14254 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) | ||||
14255 | << Bop->getSourceRange() << OpLoc << Shift << Op; | ||||
14256 | SuggestParentheses(S, Bop->getOperatorLoc(), | ||||
14257 | S.PDiag(diag::note_precedence_silence) << Op, | ||||
14258 | Bop->getSourceRange()); | ||||
14259 | } | ||||
14260 | } | ||||
14261 | } | ||||
14262 | |||||
14263 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, | ||||
14264 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14265 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); | ||||
14266 | if (!OCE) | ||||
14267 | return; | ||||
14268 | |||||
14269 | FunctionDecl *FD = OCE->getDirectCallee(); | ||||
14270 | if (!FD || !FD->isOverloadedOperator()) | ||||
14271 | return; | ||||
14272 | |||||
14273 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); | ||||
14274 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) | ||||
14275 | return; | ||||
14276 | |||||
14277 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) | ||||
14278 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() | ||||
14279 | << (Kind == OO_LessLess); | ||||
14280 | SuggestParentheses(S, OCE->getOperatorLoc(), | ||||
14281 | S.PDiag(diag::note_precedence_silence) | ||||
14282 | << (Kind == OO_LessLess ? "<<" : ">>"), | ||||
14283 | OCE->getSourceRange()); | ||||
14284 | SuggestParentheses( | ||||
14285 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), | ||||
14286 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); | ||||
14287 | } | ||||
14288 | |||||
14289 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky | ||||
14290 | /// precedence. | ||||
14291 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, | ||||
14292 | SourceLocation OpLoc, Expr *LHSExpr, | ||||
14293 | Expr *RHSExpr){ | ||||
14294 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". | ||||
14295 | if (BinaryOperator::isBitwiseOp(Opc)) | ||||
14296 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); | ||||
14297 | |||||
14298 | // Diagnose "arg1 & arg2 | arg3" | ||||
14299 | if ((Opc == BO_Or || Opc == BO_Xor) && | ||||
14300 | !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14301 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); | ||||
14302 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); | ||||
14303 | } | ||||
14304 | |||||
14305 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. | ||||
14306 | // We don't warn for 'assert(a || b && "bad")' since this is safe. | ||||
14307 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { | ||||
14308 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14309 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14310 | } | ||||
14311 | |||||
14312 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) | ||||
14313 | || Opc == BO_Shr) { | ||||
14314 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); | ||||
14315 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); | ||||
14316 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); | ||||
14317 | } | ||||
14318 | |||||
14319 | // Warn on overloaded shift operators and comparisons, such as: | ||||
14320 | // cout << 5 == 4; | ||||
14321 | if (BinaryOperator::isComparisonOp(Opc)) | ||||
14322 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); | ||||
14323 | } | ||||
14324 | |||||
14325 | // Binary Operators. 'Tok' is the token for the operator. | ||||
14326 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, | ||||
14327 | tok::TokenKind Kind, | ||||
14328 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14329 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); | ||||
14330 | assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression") ? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14330, __PRETTY_FUNCTION__)); | ||||
14331 | assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression" ) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14331, __PRETTY_FUNCTION__)); | ||||
14332 | |||||
14333 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" | ||||
14334 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); | ||||
14335 | |||||
14336 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); | ||||
14337 | } | ||||
14338 | |||||
14339 | void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, | ||||
14340 | UnresolvedSetImpl &Functions) { | ||||
14341 | OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); | ||||
14342 | if (OverOp != OO_None && OverOp != OO_Equal) | ||||
14343 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
14344 | |||||
14345 | // In C++20 onwards, we may have a second operator to look up. | ||||
14346 | if (getLangOpts().CPlusPlus20) { | ||||
14347 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) | ||||
14348 | LookupOverloadedOperatorName(ExtraOp, S, Functions); | ||||
14349 | } | ||||
14350 | } | ||||
14351 | |||||
14352 | /// Build an overloaded binary operator expression in the given scope. | ||||
14353 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, | ||||
14354 | BinaryOperatorKind Opc, | ||||
14355 | Expr *LHS, Expr *RHS) { | ||||
14356 | switch (Opc) { | ||||
14357 | case BO_Assign: | ||||
14358 | case BO_DivAssign: | ||||
14359 | case BO_RemAssign: | ||||
14360 | case BO_SubAssign: | ||||
14361 | case BO_AndAssign: | ||||
14362 | case BO_OrAssign: | ||||
14363 | case BO_XorAssign: | ||||
14364 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); | ||||
14365 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); | ||||
14366 | break; | ||||
14367 | default: | ||||
14368 | break; | ||||
14369 | } | ||||
14370 | |||||
14371 | // Find all of the overloaded operators visible from this point. | ||||
14372 | UnresolvedSet<16> Functions; | ||||
14373 | S.LookupBinOp(Sc, OpLoc, Opc, Functions); | ||||
14374 | |||||
14375 | // Build the (potentially-overloaded, potentially-dependent) | ||||
14376 | // binary operation. | ||||
14377 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); | ||||
14378 | } | ||||
14379 | |||||
14380 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, | ||||
14381 | BinaryOperatorKind Opc, | ||||
14382 | Expr *LHSExpr, Expr *RHSExpr) { | ||||
14383 | ExprResult LHS, RHS; | ||||
14384 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); | ||||
14385 | if (!LHS.isUsable() || !RHS.isUsable()) | ||||
14386 | return ExprError(); | ||||
14387 | LHSExpr = LHS.get(); | ||||
14388 | RHSExpr = RHS.get(); | ||||
14389 | |||||
14390 | // We want to end up calling one of checkPseudoObjectAssignment | ||||
14391 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if | ||||
14392 | // both expressions are overloadable or either is type-dependent), | ||||
14393 | // or CreateBuiltinBinOp (in any other case). We also want to get | ||||
14394 | // any placeholder types out of the way. | ||||
14395 | |||||
14396 | // Handle pseudo-objects in the LHS. | ||||
14397 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { | ||||
14398 | // Assignments with a pseudo-object l-value need special analysis. | ||||
14399 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
14400 | BinaryOperator::isAssignmentOp(Opc)) | ||||
14401 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14402 | |||||
14403 | // Don't resolve overloads if the other type is overloadable. | ||||
14404 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { | ||||
14405 | // We can't actually test that if we still have a placeholder, | ||||
14406 | // though. Fortunately, none of the exceptions we see in that | ||||
14407 | // code below are valid when the LHS is an overload set. Note | ||||
14408 | // that an overload set can be dependently-typed, but it never | ||||
14409 | // instantiates to having an overloadable type. | ||||
14410 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14411 | if (resolvedRHS.isInvalid()) return ExprError(); | ||||
14412 | RHSExpr = resolvedRHS.get(); | ||||
14413 | |||||
14414 | if (RHSExpr->isTypeDependent() || | ||||
14415 | RHSExpr->getType()->isOverloadableType()) | ||||
14416 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14417 | } | ||||
14418 | |||||
14419 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function | ||||
14420 | // template, diagnose the missing 'template' keyword instead of diagnosing | ||||
14421 | // an invalid use of a bound member function. | ||||
14422 | // | ||||
14423 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due | ||||
14424 | // to C++1z [over.over]/1.4, but we already checked for that case above. | ||||
14425 | if (Opc == BO_LT && inTemplateInstantiation() && | ||||
14426 | (pty->getKind() == BuiltinType::BoundMember || | ||||
14427 | pty->getKind() == BuiltinType::Overload)) { | ||||
14428 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); | ||||
14429 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && | ||||
14430 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { | ||||
14431 | return isa<FunctionTemplateDecl>(ND); | ||||
14432 | })) { | ||||
14433 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() | ||||
14434 | : OE->getNameLoc(), | ||||
14435 | diag::err_template_kw_missing) | ||||
14436 | << OE->getName().getAsString() << ""; | ||||
14437 | return ExprError(); | ||||
14438 | } | ||||
14439 | } | ||||
14440 | |||||
14441 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); | ||||
14442 | if (LHS.isInvalid()) return ExprError(); | ||||
14443 | LHSExpr = LHS.get(); | ||||
14444 | } | ||||
14445 | |||||
14446 | // Handle pseudo-objects in the RHS. | ||||
14447 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { | ||||
14448 | // An overload in the RHS can potentially be resolved by the type | ||||
14449 | // being assigned to. | ||||
14450 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { | ||||
14451 | if (getLangOpts().CPlusPlus && | ||||
14452 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || | ||||
14453 | LHSExpr->getType()->isOverloadableType())) | ||||
14454 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14455 | |||||
14456 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14457 | } | ||||
14458 | |||||
14459 | // Don't resolve overloads if the other type is overloadable. | ||||
14460 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && | ||||
14461 | LHSExpr->getType()->isOverloadableType()) | ||||
14462 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14463 | |||||
14464 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); | ||||
14465 | if (!resolvedRHS.isUsable()) return ExprError(); | ||||
14466 | RHSExpr = resolvedRHS.get(); | ||||
14467 | } | ||||
14468 | |||||
14469 | if (getLangOpts().CPlusPlus) { | ||||
14470 | // If either expression is type-dependent, always build an | ||||
14471 | // overloaded op. | ||||
14472 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) | ||||
14473 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14474 | |||||
14475 | // Otherwise, build an overloaded op if either expression has an | ||||
14476 | // overloadable type. | ||||
14477 | if (LHSExpr->getType()->isOverloadableType() || | ||||
14478 | RHSExpr->getType()->isOverloadableType()) | ||||
14479 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14480 | } | ||||
14481 | |||||
14482 | if (getLangOpts().RecoveryAST && | ||||
14483 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { | ||||
14484 | assert(!getLangOpts().CPlusPlus)((!getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14484, __PRETTY_FUNCTION__)); | ||||
14485 | assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14486, __PRETTY_FUNCTION__)) | ||||
14486 | "Should only occur in error-recovery path.")(((LHSExpr->containsErrors() || RHSExpr->containsErrors ()) && "Should only occur in error-recovery path.") ? static_cast<void> (0) : __assert_fail ("(LHSExpr->containsErrors() || RHSExpr->containsErrors()) && \"Should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14486, __PRETTY_FUNCTION__)); | ||||
14487 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | ||||
14488 | // C [6.15.16] p3: | ||||
14489 | // An assignment expression has the value of the left operand after the | ||||
14490 | // assignment, but is not an lvalue. | ||||
14491 | return CompoundAssignOperator::Create( | ||||
14492 | Context, LHSExpr, RHSExpr, Opc, | ||||
14493 | LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, | ||||
14494 | OpLoc, CurFPFeatureOverrides()); | ||||
14495 | QualType ResultType; | ||||
14496 | switch (Opc) { | ||||
14497 | case BO_Assign: | ||||
14498 | ResultType = LHSExpr->getType().getUnqualifiedType(); | ||||
14499 | break; | ||||
14500 | case BO_LT: | ||||
14501 | case BO_GT: | ||||
14502 | case BO_LE: | ||||
14503 | case BO_GE: | ||||
14504 | case BO_EQ: | ||||
14505 | case BO_NE: | ||||
14506 | case BO_LAnd: | ||||
14507 | case BO_LOr: | ||||
14508 | // These operators have a fixed result type regardless of operands. | ||||
14509 | ResultType = Context.IntTy; | ||||
14510 | break; | ||||
14511 | case BO_Comma: | ||||
14512 | ResultType = RHSExpr->getType(); | ||||
14513 | break; | ||||
14514 | default: | ||||
14515 | ResultType = Context.DependentTy; | ||||
14516 | break; | ||||
14517 | } | ||||
14518 | return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, | ||||
14519 | VK_RValue, OK_Ordinary, OpLoc, | ||||
14520 | CurFPFeatureOverrides()); | ||||
14521 | } | ||||
14522 | |||||
14523 | // Build a built-in binary operation. | ||||
14524 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); | ||||
14525 | } | ||||
14526 | |||||
14527 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { | ||||
14528 | if (T.isNull() || T->isDependentType()) | ||||
14529 | return false; | ||||
14530 | |||||
14531 | if (!T->isPromotableIntegerType()) | ||||
14532 | return true; | ||||
14533 | |||||
14534 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); | ||||
14535 | } | ||||
14536 | |||||
14537 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, | ||||
14538 | UnaryOperatorKind Opc, | ||||
14539 | Expr *InputExpr) { | ||||
14540 | ExprResult Input = InputExpr; | ||||
14541 | ExprValueKind VK = VK_RValue; | ||||
14542 | ExprObjectKind OK = OK_Ordinary; | ||||
14543 | QualType resultType; | ||||
14544 | bool CanOverflow = false; | ||||
14545 | |||||
14546 | bool ConvertHalfVec = false; | ||||
14547 | if (getLangOpts().OpenCL) { | ||||
14548 | QualType Ty = InputExpr->getType(); | ||||
14549 | // The only legal unary operation for atomics is '&'. | ||||
14550 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || | ||||
14551 | // OpenCL special types - image, sampler, pipe, and blocks are to be used | ||||
14552 | // only with a builtin functions and therefore should be disallowed here. | ||||
14553 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() | ||||
14554 | || Ty->isBlockPointerType())) { | ||||
14555 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14556 | << InputExpr->getType() | ||||
14557 | << Input.get()->getSourceRange()); | ||||
14558 | } | ||||
14559 | } | ||||
14560 | |||||
14561 | switch (Opc) { | ||||
14562 | case UO_PreInc: | ||||
14563 | case UO_PreDec: | ||||
14564 | case UO_PostInc: | ||||
14565 | case UO_PostDec: | ||||
14566 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, | ||||
14567 | OpLoc, | ||||
14568 | Opc == UO_PreInc || | ||||
14569 | Opc == UO_PostInc, | ||||
14570 | Opc == UO_PreInc || | ||||
14571 | Opc == UO_PreDec); | ||||
14572 | CanOverflow = isOverflowingIntegerType(Context, resultType); | ||||
14573 | break; | ||||
14574 | case UO_AddrOf: | ||||
14575 | resultType = CheckAddressOfOperand(Input, OpLoc); | ||||
14576 | CheckAddressOfNoDeref(InputExpr); | ||||
14577 | RecordModifiableNonNullParam(*this, InputExpr); | ||||
14578 | break; | ||||
14579 | case UO_Deref: { | ||||
14580 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14581 | if (Input.isInvalid()) return ExprError(); | ||||
14582 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); | ||||
14583 | break; | ||||
14584 | } | ||||
14585 | case UO_Plus: | ||||
14586 | case UO_Minus: | ||||
14587 | CanOverflow = Opc == UO_Minus && | ||||
14588 | isOverflowingIntegerType(Context, Input.get()->getType()); | ||||
14589 | Input = UsualUnaryConversions(Input.get()); | ||||
14590 | if (Input.isInvalid()) return ExprError(); | ||||
14591 | // Unary plus and minus require promoting an operand of half vector to a | ||||
14592 | // float vector and truncating the result back to a half vector. For now, we | ||||
14593 | // do this only when HalfArgsAndReturns is set (that is, when the target is | ||||
14594 | // arm or arm64). | ||||
14595 | ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); | ||||
14596 | |||||
14597 | // If the operand is a half vector, promote it to a float vector. | ||||
14598 | if (ConvertHalfVec) | ||||
14599 | Input = convertVector(Input.get(), Context.FloatTy, *this); | ||||
14600 | resultType = Input.get()->getType(); | ||||
14601 | if (resultType->isDependentType()) | ||||
14602 | break; | ||||
14603 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 | ||||
14604 | break; | ||||
14605 | else if (resultType->isVectorType() && | ||||
14606 | // The z vector extensions don't allow + or - with bool vectors. | ||||
14607 | (!Context.getLangOpts().ZVector || | ||||
14608 | resultType->castAs<VectorType>()->getVectorKind() != | ||||
14609 | VectorType::AltiVecBool)) | ||||
14610 | break; | ||||
14611 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 | ||||
14612 | Opc == UO_Plus && | ||||
14613 | resultType->isPointerType()) | ||||
14614 | break; | ||||
14615 | |||||
14616 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14617 | << resultType << Input.get()->getSourceRange()); | ||||
14618 | |||||
14619 | case UO_Not: // bitwise complement | ||||
14620 | Input = UsualUnaryConversions(Input.get()); | ||||
14621 | if (Input.isInvalid()) | ||||
14622 | return ExprError(); | ||||
14623 | resultType = Input.get()->getType(); | ||||
14624 | if (resultType->isDependentType()) | ||||
14625 | break; | ||||
14626 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. | ||||
14627 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) | ||||
14628 | // C99 does not support '~' for complex conjugation. | ||||
14629 | Diag(OpLoc, diag::ext_integer_complement_complex) | ||||
14630 | << resultType << Input.get()->getSourceRange(); | ||||
14631 | else if (resultType->hasIntegerRepresentation()) | ||||
14632 | break; | ||||
14633 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { | ||||
14634 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate | ||||
14635 | // on vector float types. | ||||
14636 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14637 | if (!T->isIntegerType()) | ||||
14638 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14639 | << resultType << Input.get()->getSourceRange()); | ||||
14640 | } else { | ||||
14641 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14642 | << resultType << Input.get()->getSourceRange()); | ||||
14643 | } | ||||
14644 | break; | ||||
14645 | |||||
14646 | case UO_LNot: // logical negation | ||||
14647 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). | ||||
14648 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); | ||||
14649 | if (Input.isInvalid()) return ExprError(); | ||||
14650 | resultType = Input.get()->getType(); | ||||
14651 | |||||
14652 | // Though we still have to promote half FP to float... | ||||
14653 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { | ||||
14654 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); | ||||
14655 | resultType = Context.FloatTy; | ||||
14656 | } | ||||
14657 | |||||
14658 | if (resultType->isDependentType()) | ||||
14659 | break; | ||||
14660 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { | ||||
14661 | // C99 6.5.3.3p1: ok, fallthrough; | ||||
14662 | if (Context.getLangOpts().CPlusPlus) { | ||||
14663 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: | ||||
14664 | // operand contextually converted to bool. | ||||
14665 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, | ||||
14666 | ScalarTypeToBooleanCastKind(resultType)); | ||||
14667 | } else if (Context.getLangOpts().OpenCL && | ||||
14668 | Context.getLangOpts().OpenCLVersion < 120) { | ||||
14669 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14670 | // operate on scalar float types. | ||||
14671 | if (!resultType->isIntegerType() && !resultType->isPointerType()) | ||||
14672 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14673 | << resultType << Input.get()->getSourceRange()); | ||||
14674 | } | ||||
14675 | } else if (resultType->isExtVectorType()) { | ||||
14676 | if (Context.getLangOpts().OpenCL && | ||||
14677 | Context.getLangOpts().OpenCLVersion < 120 && | ||||
14678 | !Context.getLangOpts().OpenCLCPlusPlus) { | ||||
14679 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not | ||||
14680 | // operate on vector float types. | ||||
14681 | QualType T = resultType->castAs<ExtVectorType>()->getElementType(); | ||||
14682 | if (!T->isIntegerType()) | ||||
14683 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14684 | << resultType << Input.get()->getSourceRange()); | ||||
14685 | } | ||||
14686 | // Vector logical not returns the signed variant of the operand type. | ||||
14687 | resultType = GetSignedVectorType(resultType); | ||||
14688 | break; | ||||
14689 | } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { | ||||
14690 | const VectorType *VTy = resultType->castAs<VectorType>(); | ||||
14691 | if (VTy->getVectorKind() != VectorType::GenericVector) | ||||
14692 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14693 | << resultType << Input.get()->getSourceRange()); | ||||
14694 | |||||
14695 | // Vector logical not returns the signed variant of the operand type. | ||||
14696 | resultType = GetSignedVectorType(resultType); | ||||
14697 | break; | ||||
14698 | } else { | ||||
14699 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) | ||||
14700 | << resultType << Input.get()->getSourceRange()); | ||||
14701 | } | ||||
14702 | |||||
14703 | // LNot always has type int. C99 6.5.3.3p5. | ||||
14704 | // In C++, it's bool. C++ 5.3.1p8 | ||||
14705 | resultType = Context.getLogicalOperationType(); | ||||
14706 | break; | ||||
14707 | case UO_Real: | ||||
14708 | case UO_Imag: | ||||
14709 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); | ||||
14710 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary | ||||
14711 | // complex l-values to ordinary l-values and all other values to r-values. | ||||
14712 | if (Input.isInvalid()) return ExprError(); | ||||
14713 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { | ||||
14714 | if (Input.get()->getValueKind() != VK_RValue && | ||||
14715 | Input.get()->getObjectKind() == OK_Ordinary) | ||||
14716 | VK = Input.get()->getValueKind(); | ||||
14717 | } else if (!getLangOpts().CPlusPlus) { | ||||
14718 | // In C, a volatile scalar is read by __imag. In C++, it is not. | ||||
14719 | Input = DefaultLvalueConversion(Input.get()); | ||||
14720 | } | ||||
14721 | break; | ||||
14722 | case UO_Extension: | ||||
14723 | resultType = Input.get()->getType(); | ||||
14724 | VK = Input.get()->getValueKind(); | ||||
14725 | OK = Input.get()->getObjectKind(); | ||||
14726 | break; | ||||
14727 | case UO_Coawait: | ||||
14728 | // It's unnecessary to represent the pass-through operator co_await in the | ||||
14729 | // AST; just return the input expression instead. | ||||
14730 | assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14732, __PRETTY_FUNCTION__)) | ||||
14731 | "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14732, __PRETTY_FUNCTION__)) | ||||
14732 | "building operator co_await")((!Input.get()->getType()->isDependentType() && "the co_await expression must be non-dependant before " "building operator co_await" ) ? static_cast<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-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14732, __PRETTY_FUNCTION__)); | ||||
14733 | return Input; | ||||
14734 | } | ||||
14735 | if (resultType.isNull() || Input.isInvalid()) | ||||
14736 | return ExprError(); | ||||
14737 | |||||
14738 | // Check for array bounds violations in the operand of the UnaryOperator, | ||||
14739 | // except for the '*' and '&' operators that have to be handled specially | ||||
14740 | // by CheckArrayAccess (as there are special cases like &array[arraysize] | ||||
14741 | // that are explicitly defined as valid by the standard). | ||||
14742 | if (Opc != UO_AddrOf && Opc != UO_Deref) | ||||
14743 | CheckArrayAccess(Input.get()); | ||||
14744 | |||||
14745 | auto *UO = | ||||
14746 | UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, | ||||
14747 | OpLoc, CanOverflow, CurFPFeatureOverrides()); | ||||
14748 | |||||
14749 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && | ||||
14750 | !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && | ||||
14751 | !isUnevaluatedContext()) | ||||
14752 | ExprEvalContexts.back().PossibleDerefs.insert(UO); | ||||
14753 | |||||
14754 | // Convert the result back to a half vector. | ||||
14755 | if (ConvertHalfVec) | ||||
14756 | return convertVector(UO, Context.HalfTy, *this); | ||||
14757 | return UO; | ||||
14758 | } | ||||
14759 | |||||
14760 | /// Determine whether the given expression is a qualified member | ||||
14761 | /// access expression, of a form that could be turned into a pointer to member | ||||
14762 | /// with the address-of operator. | ||||
14763 | bool Sema::isQualifiedMemberAccess(Expr *E) { | ||||
14764 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
14765 | if (!DRE->getQualifier()) | ||||
14766 | return false; | ||||
14767 | |||||
14768 | ValueDecl *VD = DRE->getDecl(); | ||||
14769 | if (!VD->isCXXClassMember()) | ||||
14770 | return false; | ||||
14771 | |||||
14772 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) | ||||
14773 | return true; | ||||
14774 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) | ||||
14775 | return Method->isInstance(); | ||||
14776 | |||||
14777 | return false; | ||||
14778 | } | ||||
14779 | |||||
14780 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | ||||
14781 | if (!ULE->getQualifier()) | ||||
14782 | return false; | ||||
14783 | |||||
14784 | for (NamedDecl *D : ULE->decls()) { | ||||
14785 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { | ||||
14786 | if (Method->isInstance()) | ||||
14787 | return true; | ||||
14788 | } else { | ||||
14789 | // Overload set does not contain methods. | ||||
14790 | break; | ||||
14791 | } | ||||
14792 | } | ||||
14793 | |||||
14794 | return false; | ||||
14795 | } | ||||
14796 | |||||
14797 | return false; | ||||
14798 | } | ||||
14799 | |||||
14800 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
14801 | UnaryOperatorKind Opc, Expr *Input) { | ||||
14802 | // First things first: handle placeholders so that the | ||||
14803 | // overloaded-operator check considers the right type. | ||||
14804 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { | ||||
14805 | // Increment and decrement of pseudo-object references. | ||||
14806 | if (pty->getKind() == BuiltinType::PseudoObject && | ||||
14807 | UnaryOperator::isIncrementDecrementOp(Opc)) | ||||
14808 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); | ||||
14809 | |||||
14810 | // extension is always a builtin operator. | ||||
14811 | if (Opc == UO_Extension) | ||||
14812 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14813 | |||||
14814 | // & gets special logic for several kinds of placeholder. | ||||
14815 | // The builtin code knows what to do. | ||||
14816 | if (Opc == UO_AddrOf && | ||||
14817 | (pty->getKind() == BuiltinType::Overload || | ||||
14818 | pty->getKind() == BuiltinType::UnknownAny || | ||||
14819 | pty->getKind() == BuiltinType::BoundMember)) | ||||
14820 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14821 | |||||
14822 | // Anything else needs to be handled now. | ||||
14823 | ExprResult Result = CheckPlaceholderExpr(Input); | ||||
14824 | if (Result.isInvalid()) return ExprError(); | ||||
14825 | Input = Result.get(); | ||||
14826 | } | ||||
14827 | |||||
14828 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && | ||||
14829 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && | ||||
14830 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { | ||||
14831 | // Find all of the overloaded operators visible from this point. | ||||
14832 | UnresolvedSet<16> Functions; | ||||
14833 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); | ||||
14834 | if (S && OverOp != OO_None) | ||||
14835 | LookupOverloadedOperatorName(OverOp, S, Functions); | ||||
14836 | |||||
14837 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); | ||||
14838 | } | ||||
14839 | |||||
14840 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | ||||
14841 | } | ||||
14842 | |||||
14843 | // Unary Operators. 'Tok' is the token for the operator. | ||||
14844 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | ||||
14845 | tok::TokenKind Op, Expr *Input) { | ||||
14846 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); | ||||
14847 | } | ||||
14848 | |||||
14849 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | ||||
14850 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | ||||
14851 | LabelDecl *TheDecl) { | ||||
14852 | TheDecl->markUsed(Context); | ||||
14853 | // Create the AST node. The address of a label always has type 'void*'. | ||||
14854 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, | ||||
14855 | Context.getPointerType(Context.VoidTy)); | ||||
14856 | } | ||||
14857 | |||||
14858 | void Sema::ActOnStartStmtExpr() { | ||||
14859 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
14860 | } | ||||
14861 | |||||
14862 | void Sema::ActOnStmtExprError() { | ||||
14863 | // Note that function is also called by TreeTransform when leaving a | ||||
14864 | // StmtExpr scope without rebuilding anything. | ||||
14865 | |||||
14866 | DiscardCleanupsInEvaluationContext(); | ||||
14867 | PopExpressionEvaluationContext(); | ||||
14868 | } | ||||
14869 | |||||
14870 | ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, | ||||
14871 | SourceLocation RPLoc) { | ||||
14872 | return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); | ||||
14873 | } | ||||
14874 | |||||
14875 | ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | ||||
14876 | SourceLocation RPLoc, unsigned TemplateDepth) { | ||||
14877 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!") ? static_cast<void> (0) : __assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14877, __PRETTY_FUNCTION__)); | ||||
14878 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); | ||||
14879 | |||||
14880 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
14881 | DiscardCleanupsInEvaluationContext(); | ||||
14882 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14883, __PRETTY_FUNCTION__)) | ||||
14883 | "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 14883, __PRETTY_FUNCTION__)); | ||||
14884 | PopExpressionEvaluationContext(); | ||||
14885 | |||||
14886 | // FIXME: there are a variety of strange constraints to enforce here, for | ||||
14887 | // example, it is not possible to goto into a stmt expression apparently. | ||||
14888 | // More semantic analysis is needed. | ||||
14889 | |||||
14890 | // If there are sub-stmts in the compound stmt, take the type of the last one | ||||
14891 | // as the type of the stmtexpr. | ||||
14892 | QualType Ty = Context.VoidTy; | ||||
14893 | bool StmtExprMayBindToTemp = false; | ||||
14894 | if (!Compound->body_empty()) { | ||||
14895 | // For GCC compatibility we get the last Stmt excluding trailing NullStmts. | ||||
14896 | if (const auto *LastStmt = | ||||
14897 | dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { | ||||
14898 | if (const Expr *Value = LastStmt->getExprStmt()) { | ||||
14899 | StmtExprMayBindToTemp = true; | ||||
14900 | Ty = Value->getType(); | ||||
14901 | } | ||||
14902 | } | ||||
14903 | } | ||||
14904 | |||||
14905 | // FIXME: Check that expression type is complete/non-abstract; statement | ||||
14906 | // expressions are not lvalues. | ||||
14907 | Expr *ResStmtExpr = | ||||
14908 | new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); | ||||
14909 | if (StmtExprMayBindToTemp) | ||||
14910 | return MaybeBindToTemporary(ResStmtExpr); | ||||
14911 | return ResStmtExpr; | ||||
14912 | } | ||||
14913 | |||||
14914 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { | ||||
14915 | if (ER.isInvalid()) | ||||
14916 | return ExprError(); | ||||
14917 | |||||
14918 | // Do function/array conversion on the last expression, but not | ||||
14919 | // lvalue-to-rvalue. However, initialize an unqualified type. | ||||
14920 | ER = DefaultFunctionArrayConversion(ER.get()); | ||||
14921 | if (ER.isInvalid()) | ||||
14922 | return ExprError(); | ||||
14923 | Expr *E = ER.get(); | ||||
14924 | |||||
14925 | if (E->isTypeDependent()) | ||||
14926 | return E; | ||||
14927 | |||||
14928 | // In ARC, if the final expression ends in a consume, splice | ||||
14929 | // the consume out and bind it later. In the alternate case | ||||
14930 | // (when dealing with a retainable type), the result | ||||
14931 | // initialization will create a produce. In both cases the | ||||
14932 | // result will be +1, and we'll need to balance that out with | ||||
14933 | // a bind. | ||||
14934 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); | ||||
14935 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) | ||||
14936 | return Cast->getSubExpr(); | ||||
14937 | |||||
14938 | // FIXME: Provide a better location for the initialization. | ||||
14939 | return PerformCopyInitialization( | ||||
14940 | InitializedEntity::InitializeStmtExprResult( | ||||
14941 | E->getBeginLoc(), E->getType().getUnqualifiedType()), | ||||
14942 | SourceLocation(), E); | ||||
14943 | } | ||||
14944 | |||||
14945 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | ||||
14946 | TypeSourceInfo *TInfo, | ||||
14947 | ArrayRef<OffsetOfComponent> Components, | ||||
14948 | SourceLocation RParenLoc) { | ||||
14949 | QualType ArgTy = TInfo->getType(); | ||||
14950 | bool Dependent = ArgTy->isDependentType(); | ||||
14951 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); | ||||
14952 | |||||
14953 | // We must have at least one component that refers to the type, and the first | ||||
14954 | // one is known to be a field designator. Verify that the ArgTy represents | ||||
14955 | // a struct/union/class. | ||||
14956 | if (!Dependent && !ArgTy->isRecordType()) | ||||
14957 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) | ||||
14958 | << ArgTy << TypeRange); | ||||
14959 | |||||
14960 | // Type must be complete per C99 7.17p3 because a declaring a variable | ||||
14961 | // with an incomplete type would be ill-formed. | ||||
14962 | if (!Dependent | ||||
14963 | && RequireCompleteType(BuiltinLoc, ArgTy, | ||||
14964 | diag::err_offsetof_incomplete_type, TypeRange)) | ||||
14965 | return ExprError(); | ||||
14966 | |||||
14967 | bool DidWarnAboutNonPOD = false; | ||||
14968 | QualType CurrentType = ArgTy; | ||||
14969 | SmallVector<OffsetOfNode, 4> Comps; | ||||
14970 | SmallVector<Expr*, 4> Exprs; | ||||
14971 | for (const OffsetOfComponent &OC : Components) { | ||||
14972 | if (OC.isBrackets) { | ||||
14973 | // Offset of an array sub-field. TODO: Should we allow vector elements? | ||||
14974 | if (!CurrentType->isDependentType()) { | ||||
14975 | const ArrayType *AT = Context.getAsArrayType(CurrentType); | ||||
14976 | if(!AT) | ||||
14977 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) | ||||
14978 | << CurrentType); | ||||
14979 | CurrentType = AT->getElementType(); | ||||
14980 | } else | ||||
14981 | CurrentType = Context.DependentTy; | ||||
14982 | |||||
14983 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); | ||||
14984 | if (IdxRval.isInvalid()) | ||||
14985 | return ExprError(); | ||||
14986 | Expr *Idx = IdxRval.get(); | ||||
14987 | |||||
14988 | // The expression must be an integral expression. | ||||
14989 | // FIXME: An integral constant expression? | ||||
14990 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && | ||||
14991 | !Idx->getType()->isIntegerType()) | ||||
14992 | return ExprError( | ||||
14993 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) | ||||
14994 | << Idx->getSourceRange()); | ||||
14995 | |||||
14996 | // Record this array index. | ||||
14997 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); | ||||
14998 | Exprs.push_back(Idx); | ||||
14999 | continue; | ||||
15000 | } | ||||
15001 | |||||
15002 | // Offset of a field. | ||||
15003 | if (CurrentType->isDependentType()) { | ||||
15004 | // We have the offset of a field, but we can't look into the dependent | ||||
15005 | // type. Just record the identifier of the field. | ||||
15006 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); | ||||
15007 | CurrentType = Context.DependentTy; | ||||
15008 | continue; | ||||
15009 | } | ||||
15010 | |||||
15011 | // We need to have a complete type to look into. | ||||
15012 | if (RequireCompleteType(OC.LocStart, CurrentType, | ||||
15013 | diag::err_offsetof_incomplete_type)) | ||||
15014 | return ExprError(); | ||||
15015 | |||||
15016 | // Look for the designated field. | ||||
15017 | const RecordType *RC = CurrentType->getAs<RecordType>(); | ||||
15018 | if (!RC) | ||||
15019 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) | ||||
15020 | << CurrentType); | ||||
15021 | RecordDecl *RD = RC->getDecl(); | ||||
15022 | |||||
15023 | // C++ [lib.support.types]p5: | ||||
15024 | // The macro offsetof accepts a restricted set of type arguments in this | ||||
15025 | // International Standard. type shall be a POD structure or a POD union | ||||
15026 | // (clause 9). | ||||
15027 | // C++11 [support.types]p4: | ||||
15028 | // If type is not a standard-layout class (Clause 9), the results are | ||||
15029 | // undefined. | ||||
15030 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
15031 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); | ||||
15032 | unsigned DiagID = | ||||
15033 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type | ||||
15034 | : diag::ext_offsetof_non_pod_type; | ||||
15035 | |||||
15036 | if (!IsSafe && !DidWarnAboutNonPOD && | ||||
15037 | DiagRuntimeBehavior(BuiltinLoc, nullptr, | ||||
15038 | PDiag(DiagID) | ||||
15039 | << SourceRange(Components[0].LocStart, OC.LocEnd) | ||||
15040 | << CurrentType)) | ||||
15041 | DidWarnAboutNonPOD = true; | ||||
15042 | } | ||||
15043 | |||||
15044 | // Look for the field. | ||||
15045 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); | ||||
15046 | LookupQualifiedName(R, RD); | ||||
15047 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); | ||||
15048 | IndirectFieldDecl *IndirectMemberDecl = nullptr; | ||||
15049 | if (!MemberDecl) { | ||||
15050 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) | ||||
15051 | MemberDecl = IndirectMemberDecl->getAnonField(); | ||||
15052 | } | ||||
15053 | |||||
15054 | if (!MemberDecl) | ||||
15055 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) | ||||
15056 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, | ||||
15057 | OC.LocEnd)); | ||||
15058 | |||||
15059 | // C99 7.17p3: | ||||
15060 | // (If the specified member is a bit-field, the behavior is undefined.) | ||||
15061 | // | ||||
15062 | // We diagnose this as an error. | ||||
15063 | if (MemberDecl->isBitField()) { | ||||
15064 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) | ||||
15065 | << MemberDecl->getDeclName() | ||||
15066 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15067 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); | ||||
15068 | return ExprError(); | ||||
15069 | } | ||||
15070 | |||||
15071 | RecordDecl *Parent = MemberDecl->getParent(); | ||||
15072 | if (IndirectMemberDecl) | ||||
15073 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); | ||||
15074 | |||||
15075 | // If the member was found in a base class, introduce OffsetOfNodes for | ||||
15076 | // the base class indirections. | ||||
15077 | CXXBasePaths Paths; | ||||
15078 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), | ||||
15079 | Paths)) { | ||||
15080 | if (Paths.getDetectedVirtual()) { | ||||
15081 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) | ||||
15082 | << MemberDecl->getDeclName() | ||||
15083 | << SourceRange(BuiltinLoc, RParenLoc); | ||||
15084 | return ExprError(); | ||||
15085 | } | ||||
15086 | |||||
15087 | CXXBasePath &Path = Paths.front(); | ||||
15088 | for (const CXXBasePathElement &B : Path) | ||||
15089 | Comps.push_back(OffsetOfNode(B.Base)); | ||||
15090 | } | ||||
15091 | |||||
15092 | if (IndirectMemberDecl) { | ||||
15093 | for (auto *FI : IndirectMemberDecl->chain()) { | ||||
15094 | assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15094, __PRETTY_FUNCTION__)); | ||||
15095 | Comps.push_back(OffsetOfNode(OC.LocStart, | ||||
15096 | cast<FieldDecl>(FI), OC.LocEnd)); | ||||
15097 | } | ||||
15098 | } else | ||||
15099 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); | ||||
15100 | |||||
15101 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
15102 | } | ||||
15103 | |||||
15104 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, | ||||
15105 | Comps, Exprs, RParenLoc); | ||||
15106 | } | ||||
15107 | |||||
15108 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, | ||||
15109 | SourceLocation BuiltinLoc, | ||||
15110 | SourceLocation TypeLoc, | ||||
15111 | ParsedType ParsedArgTy, | ||||
15112 | ArrayRef<OffsetOfComponent> Components, | ||||
15113 | SourceLocation RParenLoc) { | ||||
15114 | |||||
15115 | TypeSourceInfo *ArgTInfo; | ||||
15116 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); | ||||
15117 | if (ArgTy.isNull()) | ||||
15118 | return ExprError(); | ||||
15119 | |||||
15120 | if (!ArgTInfo) | ||||
15121 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); | ||||
15122 | |||||
15123 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); | ||||
15124 | } | ||||
15125 | |||||
15126 | |||||
15127 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, | ||||
15128 | Expr *CondExpr, | ||||
15129 | Expr *LHSExpr, Expr *RHSExpr, | ||||
15130 | SourceLocation RPLoc) { | ||||
15131 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)") ? static_cast<void> (0) : __assert_fail ("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15131, __PRETTY_FUNCTION__)); | ||||
15132 | |||||
15133 | ExprValueKind VK = VK_RValue; | ||||
15134 | ExprObjectKind OK = OK_Ordinary; | ||||
15135 | QualType resType; | ||||
15136 | bool CondIsTrue = false; | ||||
15137 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { | ||||
15138 | resType = Context.DependentTy; | ||||
15139 | } else { | ||||
15140 | // The conditional expression is required to be a constant expression. | ||||
15141 | llvm::APSInt condEval(32); | ||||
15142 | ExprResult CondICE = VerifyIntegerConstantExpression( | ||||
15143 | CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); | ||||
15144 | if (CondICE.isInvalid()) | ||||
15145 | return ExprError(); | ||||
15146 | CondExpr = CondICE.get(); | ||||
15147 | CondIsTrue = condEval.getZExtValue(); | ||||
15148 | |||||
15149 | // If the condition is > zero, then the AST type is the same as the LHSExpr. | ||||
15150 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; | ||||
15151 | |||||
15152 | resType = ActiveExpr->getType(); | ||||
15153 | VK = ActiveExpr->getValueKind(); | ||||
15154 | OK = ActiveExpr->getObjectKind(); | ||||
15155 | } | ||||
15156 | |||||
15157 | return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, | ||||
15158 | resType, VK, OK, RPLoc, CondIsTrue); | ||||
15159 | } | ||||
15160 | |||||
15161 | //===----------------------------------------------------------------------===// | ||||
15162 | // Clang Extensions. | ||||
15163 | //===----------------------------------------------------------------------===// | ||||
15164 | |||||
15165 | /// ActOnBlockStart - This callback is invoked when a block literal is started. | ||||
15166 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15167 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); | ||||
15168 | |||||
15169 | if (LangOpts.CPlusPlus) { | ||||
15170 | MangleNumberingContext *MCtx; | ||||
15171 | Decl *ManglingContextDecl; | ||||
15172 | std::tie(MCtx, ManglingContextDecl) = | ||||
15173 | getCurrentMangleNumberContext(Block->getDeclContext()); | ||||
15174 | if (MCtx) { | ||||
15175 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); | ||||
15176 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); | ||||
15177 | } | ||||
15178 | } | ||||
15179 | |||||
15180 | PushBlockScope(CurScope, Block); | ||||
15181 | CurContext->addDecl(Block); | ||||
15182 | if (CurScope) | ||||
15183 | PushDeclContext(CurScope, Block); | ||||
15184 | else | ||||
15185 | CurContext = Block; | ||||
15186 | |||||
15187 | getCurBlock()->HasImplicitReturnType = true; | ||||
15188 | |||||
15189 | // Enter a new evaluation context to insulate the block from any | ||||
15190 | // cleanups from the enclosing full-expression. | ||||
15191 | PushExpressionEvaluationContext( | ||||
15192 | ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15193 | } | ||||
15194 | |||||
15195 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | ||||
15196 | Scope *CurScope) { | ||||
15197 | assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15198, __PRETTY_FUNCTION__)) | ||||
15198 | "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15198, __PRETTY_FUNCTION__)); | ||||
15199 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral)((ParamInfo.getContext() == DeclaratorContext::BlockLiteral) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteral" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15199, __PRETTY_FUNCTION__)); | ||||
15200 | BlockScopeInfo *CurBlock = getCurBlock(); | ||||
15201 | |||||
15202 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); | ||||
15203 | QualType T = Sig->getType(); | ||||
15204 | |||||
15205 | // FIXME: We should allow unexpanded parameter packs here, but that would, | ||||
15206 | // in turn, make the block expression contain unexpanded parameter packs. | ||||
15207 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { | ||||
15208 | // Drop the parameters. | ||||
15209 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15210 | EPI.HasTrailingReturn = false; | ||||
15211 | EPI.TypeQuals.addConst(); | ||||
15212 | T = Context.getFunctionType(Context.DependentTy, None, EPI); | ||||
15213 | Sig = Context.getTrivialTypeSourceInfo(T); | ||||
15214 | } | ||||
15215 | |||||
15216 | // GetTypeForDeclarator always produces a function type for a block | ||||
15217 | // literal signature. Furthermore, it is always a FunctionProtoType | ||||
15218 | // unless the function was written with a typedef. | ||||
15219 | assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15220, __PRETTY_FUNCTION__)) | ||||
15220 | "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15220, __PRETTY_FUNCTION__)); | ||||
15221 | |||||
15222 | // Look for an explicit signature in that function type. | ||||
15223 | FunctionProtoTypeLoc ExplicitSignature; | ||||
15224 | |||||
15225 | if ((ExplicitSignature = Sig->getTypeLoc() | ||||
15226 | .getAsAdjusted<FunctionProtoTypeLoc>())) { | ||||
15227 | |||||
15228 | // Check whether that explicit signature was synthesized by | ||||
15229 | // GetTypeForDeclarator. If so, don't save that as part of the | ||||
15230 | // written signature. | ||||
15231 | if (ExplicitSignature.getLocalRangeBegin() == | ||||
15232 | ExplicitSignature.getLocalRangeEnd()) { | ||||
15233 | // This would be much cheaper if we stored TypeLocs instead of | ||||
15234 | // TypeSourceInfos. | ||||
15235 | TypeLoc Result = ExplicitSignature.getReturnLoc(); | ||||
15236 | unsigned Size = Result.getFullDataSize(); | ||||
15237 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); | ||||
15238 | Sig->getTypeLoc().initializeFullCopy(Result, Size); | ||||
15239 | |||||
15240 | ExplicitSignature = FunctionProtoTypeLoc(); | ||||
15241 | } | ||||
15242 | } | ||||
15243 | |||||
15244 | CurBlock->TheDecl->setSignatureAsWritten(Sig); | ||||
15245 | CurBlock->FunctionType = T; | ||||
15246 | |||||
15247 | const auto *Fn = T->castAs<FunctionType>(); | ||||
15248 | QualType RetTy = Fn->getReturnType(); | ||||
15249 | bool isVariadic = | ||||
15250 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); | ||||
15251 | |||||
15252 | CurBlock->TheDecl->setIsVariadic(isVariadic); | ||||
15253 | |||||
15254 | // Context.DependentTy is used as a placeholder for a missing block | ||||
15255 | // return type. TODO: what should we do with declarators like: | ||||
15256 | // ^ * { ... } | ||||
15257 | // If the answer is "apply template argument deduction".... | ||||
15258 | if (RetTy != Context.DependentTy) { | ||||
15259 | CurBlock->ReturnType = RetTy; | ||||
15260 | CurBlock->TheDecl->setBlockMissingReturnType(false); | ||||
15261 | CurBlock->HasImplicitReturnType = false; | ||||
15262 | } | ||||
15263 | |||||
15264 | // Push block parameters from the declarator if we had them. | ||||
15265 | SmallVector<ParmVarDecl*, 8> Params; | ||||
15266 | if (ExplicitSignature) { | ||||
15267 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { | ||||
15268 | ParmVarDecl *Param = ExplicitSignature.getParam(I); | ||||
15269 | if (Param->getIdentifier() == nullptr && !Param->isImplicit() && | ||||
15270 | !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { | ||||
15271 | // Diagnose this as an extension in C17 and earlier. | ||||
15272 | if (!getLangOpts().C2x) | ||||
15273 | Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); | ||||
15274 | } | ||||
15275 | Params.push_back(Param); | ||||
15276 | } | ||||
15277 | |||||
15278 | // Fake up parameter variables if we have a typedef, like | ||||
15279 | // ^ fntype { ... } | ||||
15280 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { | ||||
15281 | for (const auto &I : Fn->param_types()) { | ||||
15282 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( | ||||
15283 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); | ||||
15284 | Params.push_back(Param); | ||||
15285 | } | ||||
15286 | } | ||||
15287 | |||||
15288 | // Set the parameters on the block decl. | ||||
15289 | if (!Params.empty()) { | ||||
15290 | CurBlock->TheDecl->setParams(Params); | ||||
15291 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), | ||||
15292 | /*CheckParameterNames=*/false); | ||||
15293 | } | ||||
15294 | |||||
15295 | // Finally we can process decl attributes. | ||||
15296 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); | ||||
15297 | |||||
15298 | // Put the parameter variables in scope. | ||||
15299 | for (auto AI : CurBlock->TheDecl->parameters()) { | ||||
15300 | AI->setOwningFunction(CurBlock->TheDecl); | ||||
15301 | |||||
15302 | // If this has an identifier, add it to the scope stack. | ||||
15303 | if (AI->getIdentifier()) { | ||||
15304 | CheckShadow(CurBlock->TheScope, AI); | ||||
15305 | |||||
15306 | PushOnScopeChains(AI, CurBlock->TheScope); | ||||
15307 | } | ||||
15308 | } | ||||
15309 | } | ||||
15310 | |||||
15311 | /// ActOnBlockError - If there is an error parsing a block, this callback | ||||
15312 | /// is invoked to pop the information about the block from the action impl. | ||||
15313 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { | ||||
15314 | // Leave the expression-evaluation context. | ||||
15315 | DiscardCleanupsInEvaluationContext(); | ||||
15316 | PopExpressionEvaluationContext(); | ||||
15317 | |||||
15318 | // Pop off CurBlock, handle nested blocks. | ||||
15319 | PopDeclContext(); | ||||
15320 | PopFunctionScopeInfo(); | ||||
15321 | } | ||||
15322 | |||||
15323 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | ||||
15324 | /// literal was successfully completed. ^(int x){...} | ||||
15325 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, | ||||
15326 | Stmt *Body, Scope *CurScope) { | ||||
15327 | // If blocks are disabled, emit an error. | ||||
15328 | if (!LangOpts.Blocks) | ||||
15329 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
15330 | |||||
15331 | // Leave the expression-evaluation context. | ||||
15332 | if (hasAnyUnrecoverableErrorsInThisFunction()) | ||||
15333 | DiscardCleanupsInEvaluationContext(); | ||||
15334 | assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15335, __PRETTY_FUNCTION__)) | ||||
15335 | "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15335, __PRETTY_FUNCTION__)); | ||||
15336 | PopExpressionEvaluationContext(); | ||||
15337 | |||||
15338 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); | ||||
15339 | BlockDecl *BD = BSI->TheDecl; | ||||
15340 | |||||
15341 | if (BSI->HasImplicitReturnType) | ||||
15342 | deduceClosureReturnType(*BSI); | ||||
15343 | |||||
15344 | QualType RetTy = Context.VoidTy; | ||||
15345 | if (!BSI->ReturnType.isNull()) | ||||
15346 | RetTy = BSI->ReturnType; | ||||
15347 | |||||
15348 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); | ||||
15349 | QualType BlockTy; | ||||
15350 | |||||
15351 | // If the user wrote a function type in some form, try to use that. | ||||
15352 | if (!BSI->FunctionType.isNull()) { | ||||
15353 | const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); | ||||
15354 | |||||
15355 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); | ||||
15356 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); | ||||
15357 | |||||
15358 | // Turn protoless block types into nullary block types. | ||||
15359 | if (isa<FunctionNoProtoType>(FTy)) { | ||||
15360 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15361 | EPI.ExtInfo = Ext; | ||||
15362 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15363 | |||||
15364 | // Otherwise, if we don't need to change anything about the function type, | ||||
15365 | // preserve its sugar structure. | ||||
15366 | } else if (FTy->getReturnType() == RetTy && | ||||
15367 | (!NoReturn || FTy->getNoReturnAttr())) { | ||||
15368 | BlockTy = BSI->FunctionType; | ||||
15369 | |||||
15370 | // Otherwise, make the minimal modifications to the function type. | ||||
15371 | } else { | ||||
15372 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); | ||||
15373 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
15374 | EPI.TypeQuals = Qualifiers(); | ||||
15375 | EPI.ExtInfo = Ext; | ||||
15376 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); | ||||
15377 | } | ||||
15378 | |||||
15379 | // If we don't have a function type, just build one from nothing. | ||||
15380 | } else { | ||||
15381 | FunctionProtoType::ExtProtoInfo EPI; | ||||
15382 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); | ||||
15383 | BlockTy = Context.getFunctionType(RetTy, None, EPI); | ||||
15384 | } | ||||
15385 | |||||
15386 | DiagnoseUnusedParameters(BD->parameters()); | ||||
15387 | BlockTy = Context.getBlockPointerType(BlockTy); | ||||
15388 | |||||
15389 | // If needed, diagnose invalid gotos and switches in the block. | ||||
15390 | if (getCurFunction()->NeedsScopeChecking() && | ||||
15391 | !PP.isCodeCompletionEnabled()) | ||||
15392 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); | ||||
15393 | |||||
15394 | BD->setBody(cast<CompoundStmt>(Body)); | ||||
15395 | |||||
15396 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
15397 | DiagnoseUnguardedAvailabilityViolations(BD); | ||||
15398 | |||||
15399 | // Try to apply the named return value optimization. We have to check again | ||||
15400 | // if we can do this, though, because blocks keep return statements around | ||||
15401 | // to deduce an implicit return type. | ||||
15402 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && | ||||
15403 | !BD->isDependentContext()) | ||||
15404 | computeNRVO(Body, BSI); | ||||
15405 | |||||
15406 | if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
15407 | RetTy.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
15408 | checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, | ||||
15409 | NTCUK_Destruct|NTCUK_Copy); | ||||
15410 | |||||
15411 | PopDeclContext(); | ||||
15412 | |||||
15413 | // Set the captured variables on the block. | ||||
15414 | SmallVector<BlockDecl::Capture, 4> Captures; | ||||
15415 | for (Capture &Cap : BSI->Captures) { | ||||
15416 | if (Cap.isInvalid() || Cap.isThisCapture()) | ||||
15417 | continue; | ||||
15418 | |||||
15419 | VarDecl *Var = Cap.getVariable(); | ||||
15420 | Expr *CopyExpr = nullptr; | ||||
15421 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { | ||||
15422 | if (const RecordType *Record = | ||||
15423 | Cap.getCaptureType()->getAs<RecordType>()) { | ||||
15424 | // The capture logic needs the destructor, so make sure we mark it. | ||||
15425 | // Usually this is unnecessary because most local variables have | ||||
15426 | // their destructors marked at declaration time, but parameters are | ||||
15427 | // an exception because it's technically only the call site that | ||||
15428 | // actually requires the destructor. | ||||
15429 | if (isa<ParmVarDecl>(Var)) | ||||
15430 | FinalizeVarWithDestructor(Var, Record); | ||||
15431 | |||||
15432 | // Enter a separate potentially-evaluated context while building block | ||||
15433 | // initializers to isolate their cleanups from those of the block | ||||
15434 | // itself. | ||||
15435 | // FIXME: Is this appropriate even when the block itself occurs in an | ||||
15436 | // unevaluated operand? | ||||
15437 | EnterExpressionEvaluationContext EvalContext( | ||||
15438 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15439 | |||||
15440 | SourceLocation Loc = Cap.getLocation(); | ||||
15441 | |||||
15442 | ExprResult Result = BuildDeclarationNameExpr( | ||||
15443 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); | ||||
15444 | |||||
15445 | // According to the blocks spec, the capture of a variable from | ||||
15446 | // the stack requires a const copy constructor. This is not true | ||||
15447 | // of the copy/move done to move a __block variable to the heap. | ||||
15448 | if (!Result.isInvalid() && | ||||
15449 | !Result.get()->getType().isConstQualified()) { | ||||
15450 | Result = ImpCastExprToType(Result.get(), | ||||
15451 | Result.get()->getType().withConst(), | ||||
15452 | CK_NoOp, VK_LValue); | ||||
15453 | } | ||||
15454 | |||||
15455 | if (!Result.isInvalid()) { | ||||
15456 | Result = PerformCopyInitialization( | ||||
15457 | InitializedEntity::InitializeBlock(Var->getLocation(), | ||||
15458 | Cap.getCaptureType(), false), | ||||
15459 | Loc, Result.get()); | ||||
15460 | } | ||||
15461 | |||||
15462 | // Build a full-expression copy expression if initialization | ||||
15463 | // succeeded and used a non-trivial constructor. Recover from | ||||
15464 | // errors by pretending that the copy isn't necessary. | ||||
15465 | if (!Result.isInvalid() && | ||||
15466 | !cast<CXXConstructExpr>(Result.get())->getConstructor() | ||||
15467 | ->isTrivial()) { | ||||
15468 | Result = MaybeCreateExprWithCleanups(Result); | ||||
15469 | CopyExpr = Result.get(); | ||||
15470 | } | ||||
15471 | } | ||||
15472 | } | ||||
15473 | |||||
15474 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), | ||||
15475 | CopyExpr); | ||||
15476 | Captures.push_back(NewCap); | ||||
15477 | } | ||||
15478 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); | ||||
15479 | |||||
15480 | // Pop the block scope now but keep it alive to the end of this function. | ||||
15481 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
15482 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); | ||||
15483 | |||||
15484 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); | ||||
15485 | |||||
15486 | // If the block isn't obviously global, i.e. it captures anything at | ||||
15487 | // all, then we need to do a few things in the surrounding context: | ||||
15488 | if (Result->getBlockDecl()->hasCaptures()) { | ||||
15489 | // First, this expression has a new cleanup object. | ||||
15490 | ExprCleanupObjects.push_back(Result->getBlockDecl()); | ||||
15491 | Cleanup.setExprNeedsCleanups(true); | ||||
15492 | |||||
15493 | // It also gets a branch-protected scope if any of the captured | ||||
15494 | // variables needs destruction. | ||||
15495 | for (const auto &CI : Result->getBlockDecl()->captures()) { | ||||
15496 | const VarDecl *var = CI.getVariable(); | ||||
15497 | if (var->getType().isDestructedType() != QualType::DK_none) { | ||||
15498 | setFunctionHasBranchProtectedScope(); | ||||
15499 | break; | ||||
15500 | } | ||||
15501 | } | ||||
15502 | } | ||||
15503 | |||||
15504 | if (getCurFunction()) | ||||
15505 | getCurFunction()->addBlock(BD); | ||||
15506 | |||||
15507 | return Result; | ||||
15508 | } | ||||
15509 | |||||
15510 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | ||||
15511 | SourceLocation RPLoc) { | ||||
15512 | TypeSourceInfo *TInfo; | ||||
15513 | GetTypeFromParser(Ty, &TInfo); | ||||
15514 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); | ||||
15515 | } | ||||
15516 | |||||
15517 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, | ||||
15518 | Expr *E, TypeSourceInfo *TInfo, | ||||
15519 | SourceLocation RPLoc) { | ||||
15520 | Expr *OrigExpr = E; | ||||
15521 | bool IsMS = false; | ||||
15522 | |||||
15523 | // CUDA device code does not support varargs. | ||||
15524 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { | ||||
15525 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { | ||||
15526 | CUDAFunctionTarget T = IdentifyCUDATarget(F); | ||||
15527 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) | ||||
15528 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); | ||||
15529 | } | ||||
15530 | } | ||||
15531 | |||||
15532 | // NVPTX does not support va_arg expression. | ||||
15533 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && | ||||
15534 | Context.getTargetInfo().getTriple().isNVPTX()) | ||||
15535 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); | ||||
15536 | |||||
15537 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() | ||||
15538 | // as Microsoft ABI on an actual Microsoft platform, where | ||||
15539 | // __builtin_ms_va_list and __builtin_va_list are the same.) | ||||
15540 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && | ||||
15541 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { | ||||
15542 | QualType MSVaListType = Context.getBuiltinMSVaListType(); | ||||
15543 | if (Context.hasSameType(MSVaListType, E->getType())) { | ||||
15544 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15545 | return ExprError(); | ||||
15546 | IsMS = true; | ||||
15547 | } | ||||
15548 | } | ||||
15549 | |||||
15550 | // Get the va_list type | ||||
15551 | QualType VaListType = Context.getBuiltinVaListType(); | ||||
15552 | if (!IsMS) { | ||||
15553 | if (VaListType->isArrayType()) { | ||||
15554 | // Deal with implicit array decay; for example, on x86-64, | ||||
15555 | // va_list is an array, but it's supposed to decay to | ||||
15556 | // a pointer for va_arg. | ||||
15557 | VaListType = Context.getArrayDecayedType(VaListType); | ||||
15558 | // Make sure the input expression also decays appropriately. | ||||
15559 | ExprResult Result = UsualUnaryConversions(E); | ||||
15560 | if (Result.isInvalid()) | ||||
15561 | return ExprError(); | ||||
15562 | E = Result.get(); | ||||
15563 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { | ||||
15564 | // If va_list is a record type and we are compiling in C++ mode, | ||||
15565 | // check the argument using reference binding. | ||||
15566 | InitializedEntity Entity = InitializedEntity::InitializeParameter( | ||||
15567 | Context, Context.getLValueReferenceType(VaListType), false); | ||||
15568 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); | ||||
15569 | if (Init.isInvalid()) | ||||
15570 | return ExprError(); | ||||
15571 | E = Init.getAs<Expr>(); | ||||
15572 | } else { | ||||
15573 | // Otherwise, the va_list argument must be an l-value because | ||||
15574 | // it is modified by va_arg. | ||||
15575 | if (!E->isTypeDependent() && | ||||
15576 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) | ||||
15577 | return ExprError(); | ||||
15578 | } | ||||
15579 | } | ||||
15580 | |||||
15581 | if (!IsMS && !E->isTypeDependent() && | ||||
15582 | !Context.hasSameType(VaListType, E->getType())) | ||||
15583 | return ExprError( | ||||
15584 | Diag(E->getBeginLoc(), | ||||
15585 | diag::err_first_argument_to_va_arg_not_of_type_va_list) | ||||
15586 | << OrigExpr->getType() << E->getSourceRange()); | ||||
15587 | |||||
15588 | if (!TInfo->getType()->isDependentType()) { | ||||
15589 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), | ||||
15590 | diag::err_second_parameter_to_va_arg_incomplete, | ||||
15591 | TInfo->getTypeLoc())) | ||||
15592 | return ExprError(); | ||||
15593 | |||||
15594 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), | ||||
15595 | TInfo->getType(), | ||||
15596 | diag::err_second_parameter_to_va_arg_abstract, | ||||
15597 | TInfo->getTypeLoc())) | ||||
15598 | return ExprError(); | ||||
15599 | |||||
15600 | if (!TInfo->getType().isPODType(Context)) { | ||||
15601 | Diag(TInfo->getTypeLoc().getBeginLoc(), | ||||
15602 | TInfo->getType()->isObjCLifetimeType() | ||||
15603 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified | ||||
15604 | : diag::warn_second_parameter_to_va_arg_not_pod) | ||||
15605 | << TInfo->getType() | ||||
15606 | << TInfo->getTypeLoc().getSourceRange(); | ||||
15607 | } | ||||
15608 | |||||
15609 | // Check for va_arg where arguments of the given type will be promoted | ||||
15610 | // (i.e. this va_arg is guaranteed to have undefined behavior). | ||||
15611 | QualType PromoteType; | ||||
15612 | if (TInfo->getType()->isPromotableIntegerType()) { | ||||
15613 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); | ||||
15614 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) | ||||
15615 | PromoteType = QualType(); | ||||
15616 | } | ||||
15617 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) | ||||
15618 | PromoteType = Context.DoubleTy; | ||||
15619 | if (!PromoteType.isNull()) | ||||
15620 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, | ||||
15621 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) | ||||
15622 | << TInfo->getType() | ||||
15623 | << PromoteType | ||||
15624 | << TInfo->getTypeLoc().getSourceRange()); | ||||
15625 | } | ||||
15626 | |||||
15627 | QualType T = TInfo->getType().getNonLValueExprType(Context); | ||||
15628 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); | ||||
15629 | } | ||||
15630 | |||||
15631 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { | ||||
15632 | // The type of __null will be int or long, depending on the size of | ||||
15633 | // pointers on the target. | ||||
15634 | QualType Ty; | ||||
15635 | unsigned pw = Context.getTargetInfo().getPointerWidth(0); | ||||
15636 | if (pw == Context.getTargetInfo().getIntWidth()) | ||||
15637 | Ty = Context.IntTy; | ||||
15638 | else if (pw == Context.getTargetInfo().getLongWidth()) | ||||
15639 | Ty = Context.LongTy; | ||||
15640 | else if (pw == Context.getTargetInfo().getLongLongWidth()) | ||||
15641 | Ty = Context.LongLongTy; | ||||
15642 | else { | ||||
15643 | llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15643); | ||||
15644 | } | ||||
15645 | |||||
15646 | return new (Context) GNUNullExpr(Ty, TokenLoc); | ||||
15647 | } | ||||
15648 | |||||
15649 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15650 | SourceLocation BuiltinLoc, | ||||
15651 | SourceLocation RPLoc) { | ||||
15652 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); | ||||
15653 | } | ||||
15654 | |||||
15655 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, | ||||
15656 | SourceLocation BuiltinLoc, | ||||
15657 | SourceLocation RPLoc, | ||||
15658 | DeclContext *ParentContext) { | ||||
15659 | return new (Context) | ||||
15660 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); | ||||
15661 | } | ||||
15662 | |||||
15663 | bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, | ||||
15664 | bool Diagnose) { | ||||
15665 | if (!getLangOpts().ObjC) | ||||
15666 | return false; | ||||
15667 | |||||
15668 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); | ||||
15669 | if (!PT) | ||||
15670 | return false; | ||||
15671 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); | ||||
15672 | |||||
15673 | // Ignore any parens, implicit casts (should only be | ||||
15674 | // array-to-pointer decays), and not-so-opaque values. The last is | ||||
15675 | // important for making this trigger for property assignments. | ||||
15676 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); | ||||
15677 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) | ||||
15678 | if (OV->getSourceExpr()) | ||||
15679 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); | ||||
15680 | |||||
15681 | if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { | ||||
15682 | if (!PT->isObjCIdType() && | ||||
15683 | !(ID && ID->getIdentifier()->isStr("NSString"))) | ||||
15684 | return false; | ||||
15685 | if (!SL->isAscii()) | ||||
15686 | return false; | ||||
15687 | |||||
15688 | if (Diagnose) { | ||||
15689 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
15690 | << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); | ||||
15691 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); | ||||
15692 | } | ||||
15693 | return true; | ||||
15694 | } | ||||
15695 | |||||
15696 | if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || | ||||
15697 | isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || | ||||
15698 | isa<CXXBoolLiteralExpr>(SrcExpr)) && | ||||
15699 | !SrcExpr->isNullPointerConstant( | ||||
15700 | getASTContext(), Expr::NPC_NeverValueDependent)) { | ||||
15701 | if (!ID || !ID->getIdentifier()->isStr("NSNumber")) | ||||
15702 | return false; | ||||
15703 | if (Diagnose) { | ||||
15704 | Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) | ||||
15705 | << /*number*/1 | ||||
15706 | << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); | ||||
15707 | Expr *NumLit = | ||||
15708 | BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); | ||||
15709 | if (NumLit) | ||||
15710 | Exp = NumLit; | ||||
15711 | } | ||||
15712 | return true; | ||||
15713 | } | ||||
15714 | |||||
15715 | return false; | ||||
15716 | } | ||||
15717 | |||||
15718 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, | ||||
15719 | const Expr *SrcExpr) { | ||||
15720 | if (!DstType->isFunctionPointerType() || | ||||
15721 | !SrcExpr->getType()->isFunctionType()) | ||||
15722 | return false; | ||||
15723 | |||||
15724 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); | ||||
15725 | if (!DRE) | ||||
15726 | return false; | ||||
15727 | |||||
15728 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
15729 | if (!FD) | ||||
15730 | return false; | ||||
15731 | |||||
15732 | return !S.checkAddressOfFunctionIsAvailable(FD, | ||||
15733 | /*Complain=*/true, | ||||
15734 | SrcExpr->getBeginLoc()); | ||||
15735 | } | ||||
15736 | |||||
15737 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, | ||||
15738 | SourceLocation Loc, | ||||
15739 | QualType DstType, QualType SrcType, | ||||
15740 | Expr *SrcExpr, AssignmentAction Action, | ||||
15741 | bool *Complained) { | ||||
15742 | if (Complained) | ||||
15743 | *Complained = false; | ||||
15744 | |||||
15745 | // Decode the result (notice that AST's are still created for extensions). | ||||
15746 | bool CheckInferredResultType = false; | ||||
15747 | bool isInvalid = false; | ||||
15748 | unsigned DiagKind = 0; | ||||
15749 | ConversionFixItGenerator ConvHints; | ||||
15750 | bool MayHaveConvFixit = false; | ||||
15751 | bool MayHaveFunctionDiff = false; | ||||
15752 | const ObjCInterfaceDecl *IFace = nullptr; | ||||
15753 | const ObjCProtocolDecl *PDecl = nullptr; | ||||
15754 | |||||
15755 | switch (ConvTy) { | ||||
15756 | case Compatible: | ||||
15757 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); | ||||
15758 | return false; | ||||
15759 | |||||
15760 | case PointerToInt: | ||||
15761 | if (getLangOpts().CPlusPlus) { | ||||
15762 | DiagKind = diag::err_typecheck_convert_pointer_int; | ||||
15763 | isInvalid = true; | ||||
15764 | } else { | ||||
15765 | DiagKind = diag::ext_typecheck_convert_pointer_int; | ||||
15766 | } | ||||
15767 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15768 | MayHaveConvFixit = true; | ||||
15769 | break; | ||||
15770 | case IntToPointer: | ||||
15771 | if (getLangOpts().CPlusPlus) { | ||||
15772 | DiagKind = diag::err_typecheck_convert_int_pointer; | ||||
15773 | isInvalid = true; | ||||
15774 | } else { | ||||
15775 | DiagKind = diag::ext_typecheck_convert_int_pointer; | ||||
15776 | } | ||||
15777 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15778 | MayHaveConvFixit = true; | ||||
15779 | break; | ||||
15780 | case IncompatibleFunctionPointer: | ||||
15781 | if (getLangOpts().CPlusPlus) { | ||||
15782 | DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; | ||||
15783 | isInvalid = true; | ||||
15784 | } else { | ||||
15785 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; | ||||
15786 | } | ||||
15787 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15788 | MayHaveConvFixit = true; | ||||
15789 | break; | ||||
15790 | case IncompatiblePointer: | ||||
15791 | if (Action == AA_Passing_CFAudited) { | ||||
15792 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; | ||||
15793 | } else if (getLangOpts().CPlusPlus) { | ||||
15794 | DiagKind = diag::err_typecheck_convert_incompatible_pointer; | ||||
15795 | isInvalid = true; | ||||
15796 | } else { | ||||
15797 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; | ||||
15798 | } | ||||
15799 | CheckInferredResultType = DstType->isObjCObjectPointerType() && | ||||
15800 | SrcType->isObjCObjectPointerType(); | ||||
15801 | if (!CheckInferredResultType) { | ||||
15802 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15803 | } else if (CheckInferredResultType) { | ||||
15804 | SrcType = SrcType.getUnqualifiedType(); | ||||
15805 | DstType = DstType.getUnqualifiedType(); | ||||
15806 | } | ||||
15807 | MayHaveConvFixit = true; | ||||
15808 | break; | ||||
15809 | case IncompatiblePointerSign: | ||||
15810 | if (getLangOpts().CPlusPlus) { | ||||
15811 | DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; | ||||
15812 | isInvalid = true; | ||||
15813 | } else { | ||||
15814 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; | ||||
15815 | } | ||||
15816 | break; | ||||
15817 | case FunctionVoidPointer: | ||||
15818 | if (getLangOpts().CPlusPlus) { | ||||
15819 | DiagKind = diag::err_typecheck_convert_pointer_void_func; | ||||
15820 | isInvalid = true; | ||||
15821 | } else { | ||||
15822 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; | ||||
15823 | } | ||||
15824 | break; | ||||
15825 | case IncompatiblePointerDiscardsQualifiers: { | ||||
15826 | // Perform array-to-pointer decay if necessary. | ||||
15827 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); | ||||
15828 | |||||
15829 | isInvalid = true; | ||||
15830 | |||||
15831 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); | ||||
15832 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); | ||||
15833 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { | ||||
15834 | DiagKind = diag::err_typecheck_incompatible_address_space; | ||||
15835 | break; | ||||
15836 | |||||
15837 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { | ||||
15838 | DiagKind = diag::err_typecheck_incompatible_ownership; | ||||
15839 | break; | ||||
15840 | } | ||||
15841 | |||||
15842 | llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 15842); | ||||
15843 | // fallthrough | ||||
15844 | } | ||||
15845 | case CompatiblePointerDiscardsQualifiers: | ||||
15846 | // If the qualifiers lost were because we were applying the | ||||
15847 | // (deprecated) C++ conversion from a string literal to a char* | ||||
15848 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: | ||||
15849 | // Ideally, this check would be performed in | ||||
15850 | // checkPointerTypesForAssignment. However, that would require a | ||||
15851 | // bit of refactoring (so that the second argument is an | ||||
15852 | // expression, rather than a type), which should be done as part | ||||
15853 | // of a larger effort to fix checkPointerTypesForAssignment for | ||||
15854 | // C++ semantics. | ||||
15855 | if (getLangOpts().CPlusPlus && | ||||
15856 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) | ||||
15857 | return false; | ||||
15858 | if (getLangOpts().CPlusPlus) { | ||||
15859 | DiagKind = diag::err_typecheck_convert_discards_qualifiers; | ||||
15860 | isInvalid = true; | ||||
15861 | } else { | ||||
15862 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; | ||||
15863 | } | ||||
15864 | |||||
15865 | break; | ||||
15866 | case IncompatibleNestedPointerQualifiers: | ||||
15867 | if (getLangOpts().CPlusPlus) { | ||||
15868 | isInvalid = true; | ||||
15869 | DiagKind = diag::err_nested_pointer_qualifier_mismatch; | ||||
15870 | } else { | ||||
15871 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; | ||||
15872 | } | ||||
15873 | break; | ||||
15874 | case IncompatibleNestedPointerAddressSpaceMismatch: | ||||
15875 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; | ||||
15876 | isInvalid = true; | ||||
15877 | break; | ||||
15878 | case IntToBlockPointer: | ||||
15879 | DiagKind = diag::err_int_to_block_pointer; | ||||
15880 | isInvalid = true; | ||||
15881 | break; | ||||
15882 | case IncompatibleBlockPointer: | ||||
15883 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; | ||||
15884 | isInvalid = true; | ||||
15885 | break; | ||||
15886 | case IncompatibleObjCQualifiedId: { | ||||
15887 | if (SrcType->isObjCQualifiedIdType()) { | ||||
15888 | const ObjCObjectPointerType *srcOPT = | ||||
15889 | SrcType->castAs<ObjCObjectPointerType>(); | ||||
15890 | for (auto *srcProto : srcOPT->quals()) { | ||||
15891 | PDecl = srcProto; | ||||
15892 | break; | ||||
15893 | } | ||||
15894 | if (const ObjCInterfaceType *IFaceT = | ||||
15895 | DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
15896 | IFace = IFaceT->getDecl(); | ||||
15897 | } | ||||
15898 | else if (DstType->isObjCQualifiedIdType()) { | ||||
15899 | const ObjCObjectPointerType *dstOPT = | ||||
15900 | DstType->castAs<ObjCObjectPointerType>(); | ||||
15901 | for (auto *dstProto : dstOPT->quals()) { | ||||
15902 | PDecl = dstProto; | ||||
15903 | break; | ||||
15904 | } | ||||
15905 | if (const ObjCInterfaceType *IFaceT = | ||||
15906 | SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) | ||||
15907 | IFace = IFaceT->getDecl(); | ||||
15908 | } | ||||
15909 | if (getLangOpts().CPlusPlus) { | ||||
15910 | DiagKind = diag::err_incompatible_qualified_id; | ||||
15911 | isInvalid = true; | ||||
15912 | } else { | ||||
15913 | DiagKind = diag::warn_incompatible_qualified_id; | ||||
15914 | } | ||||
15915 | break; | ||||
15916 | } | ||||
15917 | case IncompatibleVectors: | ||||
15918 | if (getLangOpts().CPlusPlus) { | ||||
15919 | DiagKind = diag::err_incompatible_vectors; | ||||
15920 | isInvalid = true; | ||||
15921 | } else { | ||||
15922 | DiagKind = diag::warn_incompatible_vectors; | ||||
15923 | } | ||||
15924 | break; | ||||
15925 | case IncompatibleObjCWeakRef: | ||||
15926 | DiagKind = diag::err_arc_weak_unavailable_assign; | ||||
15927 | isInvalid = true; | ||||
15928 | break; | ||||
15929 | case Incompatible: | ||||
15930 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { | ||||
15931 | if (Complained) | ||||
15932 | *Complained = true; | ||||
15933 | return true; | ||||
15934 | } | ||||
15935 | |||||
15936 | DiagKind = diag::err_typecheck_convert_incompatible; | ||||
15937 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); | ||||
15938 | MayHaveConvFixit = true; | ||||
15939 | isInvalid = true; | ||||
15940 | MayHaveFunctionDiff = true; | ||||
15941 | break; | ||||
15942 | } | ||||
15943 | |||||
15944 | QualType FirstType, SecondType; | ||||
15945 | switch (Action) { | ||||
15946 | case AA_Assigning: | ||||
15947 | case AA_Initializing: | ||||
15948 | // The destination type comes first. | ||||
15949 | FirstType = DstType; | ||||
15950 | SecondType = SrcType; | ||||
15951 | break; | ||||
15952 | |||||
15953 | case AA_Returning: | ||||
15954 | case AA_Passing: | ||||
15955 | case AA_Passing_CFAudited: | ||||
15956 | case AA_Converting: | ||||
15957 | case AA_Sending: | ||||
15958 | case AA_Casting: | ||||
15959 | // The source type comes first. | ||||
15960 | FirstType = SrcType; | ||||
15961 | SecondType = DstType; | ||||
15962 | break; | ||||
15963 | } | ||||
15964 | |||||
15965 | PartialDiagnostic FDiag = PDiag(DiagKind); | ||||
15966 | if (Action == AA_Passing_CFAudited) | ||||
15967 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); | ||||
15968 | else | ||||
15969 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); | ||||
15970 | |||||
15971 | if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || | ||||
15972 | DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { | ||||
15973 | auto isPlainChar = [](const clang::Type *Type) { | ||||
15974 | return Type->isSpecificBuiltinType(BuiltinType::Char_S) || | ||||
15975 | Type->isSpecificBuiltinType(BuiltinType::Char_U); | ||||
15976 | }; | ||||
15977 | FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || | ||||
15978 | isPlainChar(SecondType->getPointeeOrArrayElementType())); | ||||
15979 | } | ||||
15980 | |||||
15981 | // If we can fix the conversion, suggest the FixIts. | ||||
15982 | if (!ConvHints.isNull()) { | ||||
15983 | for (FixItHint &H : ConvHints.Hints) | ||||
15984 | FDiag << H; | ||||
15985 | } | ||||
15986 | |||||
15987 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } | ||||
15988 | |||||
15989 | if (MayHaveFunctionDiff) | ||||
15990 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); | ||||
15991 | |||||
15992 | Diag(Loc, FDiag); | ||||
15993 | if ((DiagKind == diag::warn_incompatible_qualified_id || | ||||
15994 | DiagKind == diag::err_incompatible_qualified_id) && | ||||
15995 | PDecl && IFace && !IFace->hasDefinition()) | ||||
15996 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) | ||||
15997 | << IFace << PDecl; | ||||
15998 | |||||
15999 | if (SecondType == Context.OverloadTy) | ||||
16000 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, | ||||
16001 | FirstType, /*TakingAddress=*/true); | ||||
16002 | |||||
16003 | if (CheckInferredResultType) | ||||
16004 | EmitRelatedResultTypeNote(SrcExpr); | ||||
16005 | |||||
16006 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) | ||||
16007 | EmitRelatedResultTypeNoteForReturn(DstType); | ||||
16008 | |||||
16009 | if (Complained) | ||||
16010 | *Complained = true; | ||||
16011 | return isInvalid; | ||||
16012 | } | ||||
16013 | |||||
16014 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16015 | llvm::APSInt *Result, | ||||
16016 | AllowFoldKind CanFold) { | ||||
16017 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { | ||||
16018 | public: | ||||
16019 | SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16020 | QualType T) override { | ||||
16021 | return S.Diag(Loc, diag::err_ice_not_integral) | ||||
16022 | << T << S.LangOpts.CPlusPlus; | ||||
16023 | } | ||||
16024 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16025 | return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16026 | } | ||||
16027 | } Diagnoser; | ||||
16028 | |||||
16029 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16030 | } | ||||
16031 | |||||
16032 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, | ||||
16033 | llvm::APSInt *Result, | ||||
16034 | unsigned DiagID, | ||||
16035 | AllowFoldKind CanFold) { | ||||
16036 | class IDDiagnoser : public VerifyICEDiagnoser { | ||||
16037 | unsigned DiagID; | ||||
16038 | |||||
16039 | public: | ||||
16040 | IDDiagnoser(unsigned DiagID) | ||||
16041 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } | ||||
16042 | |||||
16043 | SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { | ||||
16044 | return S.Diag(Loc, DiagID); | ||||
16045 | } | ||||
16046 | } Diagnoser(DiagID); | ||||
16047 | |||||
16048 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); | ||||
16049 | } | ||||
16050 | |||||
16051 | Sema::SemaDiagnosticBuilder | ||||
16052 | Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
16053 | QualType T) { | ||||
16054 | return diagnoseNotICE(S, Loc); | ||||
16055 | } | ||||
16056 | |||||
16057 | Sema::SemaDiagnosticBuilder | ||||
16058 | Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { | ||||
16059 | return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; | ||||
16060 | } | ||||
16061 | |||||
16062 | ExprResult | ||||
16063 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | ||||
16064 | VerifyICEDiagnoser &Diagnoser, | ||||
16065 | AllowFoldKind CanFold) { | ||||
16066 | SourceLocation DiagLoc = E->getBeginLoc(); | ||||
16067 | |||||
16068 | if (getLangOpts().CPlusPlus11) { | ||||
16069 | // C++11 [expr.const]p5: | ||||
16070 | // If an expression of literal class type is used in a context where an | ||||
16071 | // integral constant expression is required, then that class type shall | ||||
16072 | // have a single non-explicit conversion function to an integral or | ||||
16073 | // unscoped enumeration type | ||||
16074 | ExprResult Converted; | ||||
16075 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { | ||||
16076 | VerifyICEDiagnoser &BaseDiagnoser; | ||||
16077 | public: | ||||
16078 | CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) | ||||
16079 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, | ||||
16080 | BaseDiagnoser.Suppress, true), | ||||
16081 | BaseDiagnoser(BaseDiagnoser) {} | ||||
16082 | |||||
16083 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | ||||
16084 | QualType T) override { | ||||
16085 | return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); | ||||
16086 | } | ||||
16087 | |||||
16088 | SemaDiagnosticBuilder diagnoseIncomplete( | ||||
16089 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16090 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; | ||||
16091 | } | ||||
16092 | |||||
16093 | SemaDiagnosticBuilder diagnoseExplicitConv( | ||||
16094 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16095 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; | ||||
16096 | } | ||||
16097 | |||||
16098 | SemaDiagnosticBuilder noteExplicitConv( | ||||
16099 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16100 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16101 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16102 | } | ||||
16103 | |||||
16104 | SemaDiagnosticBuilder diagnoseAmbiguous( | ||||
16105 | Sema &S, SourceLocation Loc, QualType T) override { | ||||
16106 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; | ||||
16107 | } | ||||
16108 | |||||
16109 | SemaDiagnosticBuilder noteAmbiguous( | ||||
16110 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | ||||
16111 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) | ||||
16112 | << ConvTy->isEnumeralType() << ConvTy; | ||||
16113 | } | ||||
16114 | |||||
16115 | SemaDiagnosticBuilder diagnoseConversion( | ||||
16116 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | ||||
16117 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16117); | ||||
16118 | } | ||||
16119 | } ConvertDiagnoser(Diagnoser); | ||||
16120 | |||||
16121 | Converted = PerformContextualImplicitConversion(DiagLoc, E, | ||||
16122 | ConvertDiagnoser); | ||||
16123 | if (Converted.isInvalid()) | ||||
16124 | return Converted; | ||||
16125 | E = Converted.get(); | ||||
16126 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) | ||||
16127 | return ExprError(); | ||||
16128 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
16129 | // An ICE must be of integral or unscoped enumeration type. | ||||
16130 | if (!Diagnoser.Suppress) | ||||
16131 | Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) | ||||
16132 | << E->getSourceRange(); | ||||
16133 | return ExprError(); | ||||
16134 | } | ||||
16135 | |||||
16136 | ExprResult RValueExpr = DefaultLvalueConversion(E); | ||||
16137 | if (RValueExpr.isInvalid()) | ||||
16138 | return ExprError(); | ||||
16139 | |||||
16140 | E = RValueExpr.get(); | ||||
16141 | |||||
16142 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice | ||||
16143 | // in the non-ICE case. | ||||
16144 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { | ||||
16145 | if (Result) | ||||
16146 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); | ||||
16147 | if (!isa<ConstantExpr>(E)) | ||||
16148 | E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) | ||||
16149 | : ConstantExpr::Create(Context, E); | ||||
16150 | return E; | ||||
16151 | } | ||||
16152 | |||||
16153 | Expr::EvalResult EvalResult; | ||||
16154 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16155 | EvalResult.Diag = &Notes; | ||||
16156 | |||||
16157 | // Try to evaluate the expression, and produce diagnostics explaining why it's | ||||
16158 | // not a constant expression as a side-effect. | ||||
16159 | bool Folded = | ||||
16160 | E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && | ||||
16161 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; | ||||
16162 | |||||
16163 | if (!isa<ConstantExpr>(E)) | ||||
16164 | E = ConstantExpr::Create(Context, E, EvalResult.Val); | ||||
16165 | |||||
16166 | // In C++11, we can rely on diagnostics being produced for any expression | ||||
16167 | // which is not a constant expression. If no diagnostics were produced, then | ||||
16168 | // this is a constant expression. | ||||
16169 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { | ||||
16170 | if (Result) | ||||
16171 | *Result = EvalResult.Val.getInt(); | ||||
16172 | return E; | ||||
16173 | } | ||||
16174 | |||||
16175 | // If our only note is the usual "invalid subexpression" note, just point | ||||
16176 | // the caret at its location rather than producing an essentially | ||||
16177 | // redundant note. | ||||
16178 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
16179 | diag::note_invalid_subexpr_in_const_expr) { | ||||
16180 | DiagLoc = Notes[0].first; | ||||
16181 | Notes.clear(); | ||||
16182 | } | ||||
16183 | |||||
16184 | if (!Folded || !CanFold) { | ||||
16185 | if (!Diagnoser.Suppress) { | ||||
16186 | Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); | ||||
16187 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16188 | Diag(Note.first, Note.second); | ||||
16189 | } | ||||
16190 | |||||
16191 | return ExprError(); | ||||
16192 | } | ||||
16193 | |||||
16194 | Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); | ||||
16195 | for (const PartialDiagnosticAt &Note : Notes) | ||||
16196 | Diag(Note.first, Note.second); | ||||
16197 | |||||
16198 | if (Result) | ||||
16199 | *Result = EvalResult.Val.getInt(); | ||||
16200 | return E; | ||||
16201 | } | ||||
16202 | |||||
16203 | namespace { | ||||
16204 | // Handle the case where we conclude a expression which we speculatively | ||||
16205 | // considered to be unevaluated is actually evaluated. | ||||
16206 | class TransformToPE : public TreeTransform<TransformToPE> { | ||||
16207 | typedef TreeTransform<TransformToPE> BaseTransform; | ||||
16208 | |||||
16209 | public: | ||||
16210 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } | ||||
16211 | |||||
16212 | // Make sure we redo semantic analysis | ||||
16213 | bool AlwaysRebuild() { return true; } | ||||
16214 | bool ReplacingOriginal() { return true; } | ||||
16215 | |||||
16216 | // We need to special-case DeclRefExprs referring to FieldDecls which | ||||
16217 | // are not part of a member pointer formation; normal TreeTransforming | ||||
16218 | // doesn't catch this case because of the way we represent them in the AST. | ||||
16219 | // FIXME: This is a bit ugly; is it really the best way to handle this | ||||
16220 | // case? | ||||
16221 | // | ||||
16222 | // Error on DeclRefExprs referring to FieldDecls. | ||||
16223 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16224 | if (isa<FieldDecl>(E->getDecl()) && | ||||
16225 | !SemaRef.isUnevaluatedContext()) | ||||
16226 | return SemaRef.Diag(E->getLocation(), | ||||
16227 | diag::err_invalid_non_static_member_use) | ||||
16228 | << E->getDecl() << E->getSourceRange(); | ||||
16229 | |||||
16230 | return BaseTransform::TransformDeclRefExpr(E); | ||||
16231 | } | ||||
16232 | |||||
16233 | // Exception: filter out member pointer formation | ||||
16234 | ExprResult TransformUnaryOperator(UnaryOperator *E) { | ||||
16235 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) | ||||
16236 | return E; | ||||
16237 | |||||
16238 | return BaseTransform::TransformUnaryOperator(E); | ||||
16239 | } | ||||
16240 | |||||
16241 | // The body of a lambda-expression is in a separate expression evaluation | ||||
16242 | // context so never needs to be transformed. | ||||
16243 | // FIXME: Ideally we wouldn't transform the closure type either, and would | ||||
16244 | // just recreate the capture expressions and lambda expression. | ||||
16245 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { | ||||
16246 | return SkipLambdaBody(E, Body); | ||||
16247 | } | ||||
16248 | }; | ||||
16249 | } | ||||
16250 | |||||
16251 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { | ||||
16252 | assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16253, __PRETTY_FUNCTION__)) | ||||
16253 | "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions" ) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16253, __PRETTY_FUNCTION__)); | ||||
16254 | ExprEvalContexts.back().Context = | ||||
16255 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; | ||||
16256 | if (isUnevaluatedContext()) | ||||
16257 | return E; | ||||
16258 | return TransformToPE(*this).TransformExpr(E); | ||||
16259 | } | ||||
16260 | |||||
16261 | void | ||||
16262 | Sema::PushExpressionEvaluationContext( | ||||
16263 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, | ||||
16264 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16265 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, | ||||
16266 | LambdaContextDecl, ExprContext); | ||||
16267 | Cleanup.reset(); | ||||
16268 | if (!MaybeODRUseExprs.empty()) | ||||
16269 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); | ||||
16270 | } | ||||
16271 | |||||
16272 | void | ||||
16273 | Sema::PushExpressionEvaluationContext( | ||||
16274 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | ||||
16275 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { | ||||
16276 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; | ||||
16277 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); | ||||
16278 | } | ||||
16279 | |||||
16280 | namespace { | ||||
16281 | |||||
16282 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { | ||||
16283 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); | ||||
16284 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { | ||||
16285 | if (E->getOpcode() == UO_Deref) | ||||
16286 | return CheckPossibleDeref(S, E->getSubExpr()); | ||||
16287 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { | ||||
16288 | return CheckPossibleDeref(S, E->getBase()); | ||||
16289 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { | ||||
16290 | return CheckPossibleDeref(S, E->getBase()); | ||||
16291 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { | ||||
16292 | QualType Inner; | ||||
16293 | QualType Ty = E->getType(); | ||||
16294 | if (const auto *Ptr = Ty->getAs<PointerType>()) | ||||
16295 | Inner = Ptr->getPointeeType(); | ||||
16296 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) | ||||
16297 | Inner = Arr->getElementType(); | ||||
16298 | else | ||||
16299 | return nullptr; | ||||
16300 | |||||
16301 | if (Inner->hasAttr(attr::NoDeref)) | ||||
16302 | return E; | ||||
16303 | } | ||||
16304 | return nullptr; | ||||
16305 | } | ||||
16306 | |||||
16307 | } // namespace | ||||
16308 | |||||
16309 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { | ||||
16310 | for (const Expr *E : Rec.PossibleDerefs) { | ||||
16311 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); | ||||
16312 | if (DeclRef) { | ||||
16313 | const ValueDecl *Decl = DeclRef->getDecl(); | ||||
16314 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) | ||||
16315 | << Decl->getName() << E->getSourceRange(); | ||||
16316 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); | ||||
16317 | } else { | ||||
16318 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) | ||||
16319 | << E->getSourceRange(); | ||||
16320 | } | ||||
16321 | } | ||||
16322 | Rec.PossibleDerefs.clear(); | ||||
16323 | } | ||||
16324 | |||||
16325 | /// Check whether E, which is either a discarded-value expression or an | ||||
16326 | /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, | ||||
16327 | /// and if so, remove it from the list of volatile-qualified assignments that | ||||
16328 | /// we are going to warn are deprecated. | ||||
16329 | void Sema::CheckUnusedVolatileAssignment(Expr *E) { | ||||
16330 | if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) | ||||
16331 | return; | ||||
16332 | |||||
16333 | // Note: ignoring parens here is not justified by the standard rules, but | ||||
16334 | // ignoring parentheses seems like a more reasonable approach, and this only | ||||
16335 | // drives a deprecation warning so doesn't affect conformance. | ||||
16336 | if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { | ||||
16337 | if (BO->getOpcode() == BO_Assign) { | ||||
16338 | auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; | ||||
16339 | LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), | ||||
16340 | LHSs.end()); | ||||
16341 | } | ||||
16342 | } | ||||
16343 | } | ||||
16344 | |||||
16345 | ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { | ||||
16346 | if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || | ||||
16347 | RebuildingImmediateInvocation) | ||||
16348 | return E; | ||||
16349 | |||||
16350 | /// Opportunistically remove the callee from ReferencesToConsteval if we can. | ||||
16351 | /// It's OK if this fails; we'll also remove this in | ||||
16352 | /// HandleImmediateInvocations, but catching it here allows us to avoid | ||||
16353 | /// walking the AST looking for it in simple cases. | ||||
16354 | if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) | ||||
16355 | if (auto *DeclRef = | ||||
16356 | dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) | ||||
16357 | ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); | ||||
16358 | |||||
16359 | E = MaybeCreateExprWithCleanups(E); | ||||
16360 | |||||
16361 | ConstantExpr *Res = ConstantExpr::Create( | ||||
16362 | getASTContext(), E.get(), | ||||
16363 | ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), | ||||
16364 | getASTContext()), | ||||
16365 | /*IsImmediateInvocation*/ true); | ||||
16366 | ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); | ||||
16367 | return Res; | ||||
16368 | } | ||||
16369 | |||||
16370 | static void EvaluateAndDiagnoseImmediateInvocation( | ||||
16371 | Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { | ||||
16372 | llvm::SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
16373 | Expr::EvalResult Eval; | ||||
16374 | Eval.Diag = &Notes; | ||||
16375 | ConstantExpr *CE = Candidate.getPointer(); | ||||
16376 | bool Result = CE->EvaluateAsConstantExpr( | ||||
16377 | Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); | ||||
16378 | if (!Result || !Notes.empty()) { | ||||
16379 | Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); | ||||
16380 | if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) | ||||
16381 | InnerExpr = FunctionalCast->getSubExpr(); | ||||
16382 | FunctionDecl *FD = nullptr; | ||||
16383 | if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) | ||||
16384 | FD = cast<FunctionDecl>(Call->getCalleeDecl()); | ||||
16385 | else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) | ||||
16386 | FD = Call->getConstructor(); | ||||
16387 | else | ||||
16388 | llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16388); | ||||
16389 | assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail ("FD->isConsteval()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16389, __PRETTY_FUNCTION__)); | ||||
16390 | SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; | ||||
16391 | for (auto &Note : Notes) | ||||
16392 | SemaRef.Diag(Note.first, Note.second); | ||||
16393 | return; | ||||
16394 | } | ||||
16395 | CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); | ||||
16396 | } | ||||
16397 | |||||
16398 | static void RemoveNestedImmediateInvocation( | ||||
16399 | Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, | ||||
16400 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { | ||||
16401 | struct ComplexRemove : TreeTransform<ComplexRemove> { | ||||
16402 | using Base = TreeTransform<ComplexRemove>; | ||||
16403 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16404 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; | ||||
16405 | SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator | ||||
16406 | CurrentII; | ||||
16407 | ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, | ||||
16408 | SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, | ||||
16409 | SmallVector<Sema::ImmediateInvocationCandidate, | ||||
16410 | 4>::reverse_iterator Current) | ||||
16411 | : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} | ||||
16412 | void RemoveImmediateInvocation(ConstantExpr* E) { | ||||
16413 | auto It = std::find_if(CurrentII, IISet.rend(), | ||||
16414 | [E](Sema::ImmediateInvocationCandidate Elem) { | ||||
16415 | return Elem.getPointer() == E; | ||||
16416 | }); | ||||
16417 | assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16419, __PRETTY_FUNCTION__)) | ||||
16418 | "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16419, __PRETTY_FUNCTION__)) | ||||
16419 | "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should " "be present") ? static_cast<void> (0) : __assert_fail ( "It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16419, __PRETTY_FUNCTION__)); | ||||
16420 | It->setInt(1); // Mark as deleted | ||||
16421 | } | ||||
16422 | ExprResult TransformConstantExpr(ConstantExpr *E) { | ||||
16423 | if (!E->isImmediateInvocation()) | ||||
16424 | return Base::TransformConstantExpr(E); | ||||
16425 | RemoveImmediateInvocation(E); | ||||
16426 | return Base::TransformExpr(E->getSubExpr()); | ||||
16427 | } | ||||
16428 | /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so | ||||
16429 | /// we need to remove its DeclRefExpr from the DRSet. | ||||
16430 | ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
16431 | DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); | ||||
16432 | return Base::TransformCXXOperatorCallExpr(E); | ||||
16433 | } | ||||
16434 | /// Base::TransformInitializer skip ConstantExpr so we need to visit them | ||||
16435 | /// here. | ||||
16436 | ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { | ||||
16437 | if (!Init) | ||||
16438 | return Init; | ||||
16439 | /// ConstantExpr are the first layer of implicit node to be removed so if | ||||
16440 | /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. | ||||
16441 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
16442 | if (CE->isImmediateInvocation()) | ||||
16443 | RemoveImmediateInvocation(CE); | ||||
16444 | return Base::TransformInitializer(Init, NotCopyInit); | ||||
16445 | } | ||||
16446 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { | ||||
16447 | DRSet.erase(E); | ||||
16448 | return E; | ||||
16449 | } | ||||
16450 | bool AlwaysRebuild() { return false; } | ||||
16451 | bool ReplacingOriginal() { return true; } | ||||
16452 | bool AllowSkippingCXXConstructExpr() { | ||||
16453 | bool Res = AllowSkippingFirstCXXConstructExpr; | ||||
16454 | AllowSkippingFirstCXXConstructExpr = true; | ||||
16455 | return Res; | ||||
16456 | } | ||||
16457 | bool AllowSkippingFirstCXXConstructExpr = true; | ||||
16458 | } Transformer(SemaRef, Rec.ReferenceToConsteval, | ||||
16459 | Rec.ImmediateInvocationCandidates, It); | ||||
16460 | |||||
16461 | /// CXXConstructExpr with a single argument are getting skipped by | ||||
16462 | /// TreeTransform in some situtation because they could be implicit. This | ||||
16463 | /// can only occur for the top-level CXXConstructExpr because it is used | ||||
16464 | /// nowhere in the expression being transformed therefore will not be rebuilt. | ||||
16465 | /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from | ||||
16466 | /// skipping the first CXXConstructExpr. | ||||
16467 | if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) | ||||
16468 | Transformer.AllowSkippingFirstCXXConstructExpr = false; | ||||
16469 | |||||
16470 | ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); | ||||
16471 | assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail ("Res.isUsable()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16471, __PRETTY_FUNCTION__)); | ||||
16472 | Res = SemaRef.MaybeCreateExprWithCleanups(Res); | ||||
16473 | It->getPointer()->setSubExpr(Res.get()); | ||||
16474 | } | ||||
16475 | |||||
16476 | static void | ||||
16477 | HandleImmediateInvocations(Sema &SemaRef, | ||||
16478 | Sema::ExpressionEvaluationContextRecord &Rec) { | ||||
16479 | if ((Rec.ImmediateInvocationCandidates.size() == 0 && | ||||
16480 | Rec.ReferenceToConsteval.size() == 0) || | ||||
16481 | SemaRef.RebuildingImmediateInvocation) | ||||
16482 | return; | ||||
16483 | |||||
16484 | /// When we have more then 1 ImmediateInvocationCandidates we need to check | ||||
16485 | /// for nested ImmediateInvocationCandidates. when we have only 1 we only | ||||
16486 | /// need to remove ReferenceToConsteval in the immediate invocation. | ||||
16487 | if (Rec.ImmediateInvocationCandidates.size() > 1) { | ||||
16488 | |||||
16489 | /// Prevent sema calls during the tree transform from adding pointers that | ||||
16490 | /// are already in the sets. | ||||
16491 | llvm::SaveAndRestore<bool> DisableIITracking( | ||||
16492 | SemaRef.RebuildingImmediateInvocation, true); | ||||
16493 | |||||
16494 | /// Prevent diagnostic during tree transfrom as they are duplicates | ||||
16495 | Sema::TentativeAnalysisScope DisableDiag(SemaRef); | ||||
16496 | |||||
16497 | for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); | ||||
16498 | It != Rec.ImmediateInvocationCandidates.rend(); It++) | ||||
16499 | if (!It->getInt()) | ||||
16500 | RemoveNestedImmediateInvocation(SemaRef, Rec, It); | ||||
16501 | } else if (Rec.ImmediateInvocationCandidates.size() == 1 && | ||||
16502 | Rec.ReferenceToConsteval.size()) { | ||||
16503 | struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { | ||||
16504 | llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; | ||||
16505 | SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} | ||||
16506 | bool VisitDeclRefExpr(DeclRefExpr *E) { | ||||
16507 | DRSet.erase(E); | ||||
16508 | return DRSet.size(); | ||||
16509 | } | ||||
16510 | } Visitor(Rec.ReferenceToConsteval); | ||||
16511 | Visitor.TraverseStmt( | ||||
16512 | Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); | ||||
16513 | } | ||||
16514 | for (auto CE : Rec.ImmediateInvocationCandidates) | ||||
16515 | if (!CE.getInt()) | ||||
16516 | EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); | ||||
16517 | for (auto DR : Rec.ReferenceToConsteval) { | ||||
16518 | auto *FD = cast<FunctionDecl>(DR->getDecl()); | ||||
16519 | SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) | ||||
16520 | << FD; | ||||
16521 | SemaRef.Diag(FD->getLocation(), diag::note_declared_at); | ||||
16522 | } | ||||
16523 | } | ||||
16524 | |||||
16525 | void Sema::PopExpressionEvaluationContext() { | ||||
16526 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); | ||||
16527 | unsigned NumTypos = Rec.NumTypos; | ||||
16528 | |||||
16529 | if (!Rec.Lambdas.empty()) { | ||||
16530 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; | ||||
16531 | if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || | ||||
16532 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { | ||||
16533 | unsigned D; | ||||
16534 | if (Rec.isUnevaluated()) { | ||||
16535 | // C++11 [expr.prim.lambda]p2: | ||||
16536 | // A lambda-expression shall not appear in an unevaluated operand | ||||
16537 | // (Clause 5). | ||||
16538 | D = diag::err_lambda_unevaluated_operand; | ||||
16539 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { | ||||
16540 | // C++1y [expr.const]p2: | ||||
16541 | // A conditional-expression e is a core constant expression unless the | ||||
16542 | // evaluation of e, following the rules of the abstract machine, would | ||||
16543 | // evaluate [...] a lambda-expression. | ||||
16544 | D = diag::err_lambda_in_constant_expression; | ||||
16545 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { | ||||
16546 | // C++17 [expr.prim.lamda]p2: | ||||
16547 | // A lambda-expression shall not appear [...] in a template-argument. | ||||
16548 | D = diag::err_lambda_in_invalid_context; | ||||
16549 | } else | ||||
16550 | llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message." , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16550); | ||||
16551 | |||||
16552 | for (const auto *L : Rec.Lambdas) | ||||
16553 | Diag(L->getBeginLoc(), D); | ||||
16554 | } | ||||
16555 | } | ||||
16556 | |||||
16557 | WarnOnPendingNoDerefs(Rec); | ||||
16558 | HandleImmediateInvocations(*this, Rec); | ||||
16559 | |||||
16560 | // Warn on any volatile-qualified simple-assignments that are not discarded- | ||||
16561 | // value expressions nor unevaluated operands (those cases get removed from | ||||
16562 | // this list by CheckUnusedVolatileAssignment). | ||||
16563 | for (auto *BO : Rec.VolatileAssignmentLHSs) | ||||
16564 | Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) | ||||
16565 | << BO->getType(); | ||||
16566 | |||||
16567 | // When are coming out of an unevaluated context, clear out any | ||||
16568 | // temporaries that we may have created as part of the evaluation of | ||||
16569 | // the expression in that context: they aren't relevant because they | ||||
16570 | // will never be constructed. | ||||
16571 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { | ||||
16572 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, | ||||
16573 | ExprCleanupObjects.end()); | ||||
16574 | Cleanup = Rec.ParentCleanup; | ||||
16575 | CleanupVarDeclMarking(); | ||||
16576 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); | ||||
16577 | // Otherwise, merge the contexts together. | ||||
16578 | } else { | ||||
16579 | Cleanup.mergeFrom(Rec.ParentCleanup); | ||||
16580 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), | ||||
16581 | Rec.SavedMaybeODRUseExprs.end()); | ||||
16582 | } | ||||
16583 | |||||
16584 | // Pop the current expression evaluation context off the stack. | ||||
16585 | ExprEvalContexts.pop_back(); | ||||
16586 | |||||
16587 | // The global expression evaluation context record is never popped. | ||||
16588 | ExprEvalContexts.back().NumTypos += NumTypos; | ||||
16589 | } | ||||
16590 | |||||
16591 | void Sema::DiscardCleanupsInEvaluationContext() { | ||||
16592 | ExprCleanupObjects.erase( | ||||
16593 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, | ||||
16594 | ExprCleanupObjects.end()); | ||||
16595 | Cleanup.reset(); | ||||
16596 | MaybeODRUseExprs.clear(); | ||||
16597 | } | ||||
16598 | |||||
16599 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { | ||||
16600 | ExprResult Result = CheckPlaceholderExpr(E); | ||||
16601 | if (Result.isInvalid()) | ||||
16602 | return ExprError(); | ||||
16603 | E = Result.get(); | ||||
16604 | if (!E->getType()->isVariablyModifiedType()) | ||||
16605 | return E; | ||||
16606 | return TransformToPotentiallyEvaluated(E); | ||||
16607 | } | ||||
16608 | |||||
16609 | /// Are we in a context that is potentially constant evaluated per C++20 | ||||
16610 | /// [expr.const]p12? | ||||
16611 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { | ||||
16612 | /// C++2a [expr.const]p12: | ||||
16613 | // An expression or conversion is potentially constant evaluated if it is | ||||
16614 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
16615 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
16616 | // -- a manifestly constant-evaluated expression, | ||||
16617 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
16618 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
16619 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
16620 | // -- a potentially-evaluated expression, | ||||
16621 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
16622 | // -- an immediate subexpression of a braced-init-list, | ||||
16623 | |||||
16624 | // -- [FIXME] an expression of the form & cast-expression that occurs | ||||
16625 | // within a templated entity | ||||
16626 | // -- a subexpression of one of the above that is not a subexpression of | ||||
16627 | // a nested unevaluated operand. | ||||
16628 | return true; | ||||
16629 | |||||
16630 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
16631 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
16632 | // Expressions in this context are never evaluated. | ||||
16633 | return false; | ||||
16634 | } | ||||
16635 | llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16635); | ||||
16636 | } | ||||
16637 | |||||
16638 | /// Return true if this function has a calling convention that requires mangling | ||||
16639 | /// in the size of the parameter pack. | ||||
16640 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { | ||||
16641 | // These manglings don't do anything on non-Windows or non-x86 platforms, so | ||||
16642 | // we don't need parameter type sizes. | ||||
16643 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); | ||||
16644 | if (!TT.isOSWindows() || !TT.isX86()) | ||||
16645 | return false; | ||||
16646 | |||||
16647 | // If this is C++ and this isn't an extern "C" function, parameters do not | ||||
16648 | // need to be complete. In this case, C++ mangling will apply, which doesn't | ||||
16649 | // use the size of the parameters. | ||||
16650 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) | ||||
16651 | return false; | ||||
16652 | |||||
16653 | // Stdcall, fastcall, and vectorcall need this special treatment. | ||||
16654 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
16655 | switch (CC) { | ||||
16656 | case CC_X86StdCall: | ||||
16657 | case CC_X86FastCall: | ||||
16658 | case CC_X86VectorCall: | ||||
16659 | return true; | ||||
16660 | default: | ||||
16661 | break; | ||||
16662 | } | ||||
16663 | return false; | ||||
16664 | } | ||||
16665 | |||||
16666 | /// Require that all of the parameter types of function be complete. Normally, | ||||
16667 | /// parameter types are only required to be complete when a function is called | ||||
16668 | /// or defined, but to mangle functions with certain calling conventions, the | ||||
16669 | /// mangler needs to know the size of the parameter list. In this situation, | ||||
16670 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles | ||||
16671 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually | ||||
16672 | /// result in a linker error. Clang doesn't implement this behavior, and instead | ||||
16673 | /// attempts to error at compile time. | ||||
16674 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, | ||||
16675 | SourceLocation Loc) { | ||||
16676 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { | ||||
16677 | FunctionDecl *FD; | ||||
16678 | ParmVarDecl *Param; | ||||
16679 | |||||
16680 | public: | ||||
16681 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) | ||||
16682 | : FD(FD), Param(Param) {} | ||||
16683 | |||||
16684 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
16685 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); | ||||
16686 | StringRef CCName; | ||||
16687 | switch (CC) { | ||||
16688 | case CC_X86StdCall: | ||||
16689 | CCName = "stdcall"; | ||||
16690 | break; | ||||
16691 | case CC_X86FastCall: | ||||
16692 | CCName = "fastcall"; | ||||
16693 | break; | ||||
16694 | case CC_X86VectorCall: | ||||
16695 | CCName = "vectorcall"; | ||||
16696 | break; | ||||
16697 | default: | ||||
16698 | llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16698); | ||||
16699 | } | ||||
16700 | |||||
16701 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) | ||||
16702 | << Param->getDeclName() << FD->getDeclName() << CCName; | ||||
16703 | } | ||||
16704 | }; | ||||
16705 | |||||
16706 | for (ParmVarDecl *Param : FD->parameters()) { | ||||
16707 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); | ||||
16708 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); | ||||
16709 | } | ||||
16710 | } | ||||
16711 | |||||
16712 | namespace { | ||||
16713 | enum class OdrUseContext { | ||||
16714 | /// Declarations in this context are not odr-used. | ||||
16715 | None, | ||||
16716 | /// Declarations in this context are formally odr-used, but this is a | ||||
16717 | /// dependent context. | ||||
16718 | Dependent, | ||||
16719 | /// Declarations in this context are odr-used but not actually used (yet). | ||||
16720 | FormallyOdrUsed, | ||||
16721 | /// Declarations in this context are used. | ||||
16722 | Used | ||||
16723 | }; | ||||
16724 | } | ||||
16725 | |||||
16726 | /// Are we within a context in which references to resolved functions or to | ||||
16727 | /// variables result in odr-use? | ||||
16728 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { | ||||
16729 | OdrUseContext Result; | ||||
16730 | |||||
16731 | switch (SemaRef.ExprEvalContexts.back().Context) { | ||||
16732 | case Sema::ExpressionEvaluationContext::Unevaluated: | ||||
16733 | case Sema::ExpressionEvaluationContext::UnevaluatedList: | ||||
16734 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
16735 | return OdrUseContext::None; | ||||
16736 | |||||
16737 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: | ||||
16738 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
16739 | Result = OdrUseContext::Used; | ||||
16740 | break; | ||||
16741 | |||||
16742 | case Sema::ExpressionEvaluationContext::DiscardedStatement: | ||||
16743 | Result = OdrUseContext::FormallyOdrUsed; | ||||
16744 | break; | ||||
16745 | |||||
16746 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
16747 | // A default argument formally results in odr-use, but doesn't actually | ||||
16748 | // result in a use in any real sense until it itself is used. | ||||
16749 | Result = OdrUseContext::FormallyOdrUsed; | ||||
16750 | break; | ||||
16751 | } | ||||
16752 | |||||
16753 | if (SemaRef.CurContext->isDependentContext()) | ||||
16754 | return OdrUseContext::Dependent; | ||||
16755 | |||||
16756 | return Result; | ||||
16757 | } | ||||
16758 | |||||
16759 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { | ||||
16760 | if (!Func->isConstexpr()) | ||||
16761 | return false; | ||||
16762 | |||||
16763 | if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) | ||||
16764 | return true; | ||||
16765 | auto *CCD = dyn_cast<CXXConstructorDecl>(Func); | ||||
16766 | return CCD && CCD->getInheritedConstructor(); | ||||
16767 | } | ||||
16768 | |||||
16769 | /// Mark a function referenced, and check whether it is odr-used | ||||
16770 | /// (C++ [basic.def.odr]p2, C99 6.9p3) | ||||
16771 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | ||||
16772 | bool MightBeOdrUse) { | ||||
16773 | assert(Func && "No function?")((Func && "No function?") ? static_cast<void> ( 0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 16773, __PRETTY_FUNCTION__)); | ||||
16774 | |||||
16775 | Func->setReferenced(); | ||||
16776 | |||||
16777 | // Recursive functions aren't really used until they're used from some other | ||||
16778 | // context. | ||||
16779 | bool IsRecursiveCall = CurContext == Func; | ||||
16780 | |||||
16781 | // C++11 [basic.def.odr]p3: | ||||
16782 | // A function whose name appears as a potentially-evaluated expression is | ||||
16783 | // odr-used if it is the unique lookup result or the selected member of a | ||||
16784 | // set of overloaded functions [...]. | ||||
16785 | // | ||||
16786 | // We (incorrectly) mark overload resolution as an unevaluated context, so we | ||||
16787 | // can just check that here. | ||||
16788 | OdrUseContext OdrUse = | ||||
16789 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; | ||||
16790 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) | ||||
16791 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16792 | |||||
16793 | // Trivial default constructors and destructors are never actually used. | ||||
16794 | // FIXME: What about other special members? | ||||
16795 | if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && | ||||
16796 | OdrUse == OdrUseContext::Used) { | ||||
16797 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) | ||||
16798 | if (Constructor->isDefaultConstructor()) | ||||
16799 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16800 | if (isa<CXXDestructorDecl>(Func)) | ||||
16801 | OdrUse = OdrUseContext::FormallyOdrUsed; | ||||
16802 | } | ||||
16803 | |||||
16804 | // C++20 [expr.const]p12: | ||||
16805 | // A function [...] is needed for constant evaluation if it is [...] a | ||||
16806 | // constexpr function that is named by an expression that is potentially | ||||
16807 | // constant evaluated | ||||
16808 | bool NeededForConstantEvaluation = | ||||
16809 | isPotentiallyConstantEvaluatedContext(*this) && | ||||
16810 | isImplicitlyDefinableConstexprFunction(Func); | ||||
16811 | |||||
16812 | // Determine whether we require a function definition to exist, per | ||||
16813 | // C++11 [temp.inst]p3: | ||||
16814 | // Unless a function template specialization has been explicitly | ||||
16815 | // instantiated or explicitly specialized, the function template | ||||
16816 | // specialization is implicitly instantiated when the specialization is | ||||
16817 | // referenced in a context that requires a function definition to exist. | ||||
16818 | // C++20 [temp.inst]p7: | ||||
16819 | // The existence of a definition of a [...] function is considered to | ||||
16820 | // affect the semantics of the program if the [...] function is needed for | ||||
16821 | // constant evaluation by an expression | ||||
16822 | // C++20 [basic.def.odr]p10: | ||||
16823 | // Every program shall contain exactly one definition of every non-inline | ||||
16824 | // function or variable that is odr-used in that program outside of a | ||||
16825 | // discarded statement | ||||
16826 | // C++20 [special]p1: | ||||
16827 | // The implementation will implicitly define [defaulted special members] | ||||
16828 | // if they are odr-used or needed for constant evaluation. | ||||
16829 | // | ||||
16830 | // Note that we skip the implicit instantiation of templates that are only | ||||
16831 | // used in unused default arguments or by recursive calls to themselves. | ||||
16832 | // This is formally non-conforming, but seems reasonable in practice. | ||||
16833 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || | ||||
16834 | NeededForConstantEvaluation); | ||||
16835 | |||||
16836 | // C++14 [temp.expl.spec]p6: | ||||
16837 | // If a template [...] is explicitly specialized then that specialization | ||||
16838 | // shall be declared before the first use of that specialization that would | ||||
16839 | // cause an implicit instantiation to take place, in every translation unit | ||||
16840 | // in which such a use occurs | ||||
16841 | if (NeedDefinition && | ||||
16842 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || | ||||
16843 | Func->getMemberSpecializationInfo())) | ||||
16844 | checkSpecializationVisibility(Loc, Func); | ||||
16845 | |||||
16846 | if (getLangOpts().CUDA) | ||||
16847 | CheckCUDACall(Loc, Func); | ||||
16848 | |||||
16849 | if (getLangOpts().SYCLIsDevice) | ||||
16850 | checkSYCLDeviceFunction(Loc, Func); | ||||
16851 | |||||
16852 | // If we need a definition, try to create one. | ||||
16853 | if (NeedDefinition && !Func->getBody()) { | ||||
16854 | runWithSufficientStackSpace(Loc, [&] { | ||||
16855 | if (CXXConstructorDecl *Constructor = | ||||
16856 | dyn_cast<CXXConstructorDecl>(Func)) { | ||||
16857 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); | ||||
16858 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { | ||||
16859 | if (Constructor->isDefaultConstructor()) { | ||||
16860 | if (Constructor->isTrivial() && | ||||
16861 | !Constructor->hasAttr<DLLExportAttr>()) | ||||
16862 | return; | ||||
16863 | DefineImplicitDefaultConstructor(Loc, Constructor); | ||||
16864 | } else if (Constructor->isCopyConstructor()) { | ||||
16865 | DefineImplicitCopyConstructor(Loc, Constructor); | ||||
16866 | } else if (Constructor->isMoveConstructor()) { | ||||
16867 | DefineImplicitMoveConstructor(Loc, Constructor); | ||||
16868 | } | ||||
16869 | } else if (Constructor->getInheritedConstructor()) { | ||||
16870 | DefineInheritingConstructor(Loc, Constructor); | ||||
16871 | } | ||||
16872 | } else if (CXXDestructorDecl *Destructor = | ||||
16873 | dyn_cast<CXXDestructorDecl>(Func)) { | ||||
16874 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); | ||||
16875 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { | ||||
16876 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) | ||||
16877 | return; | ||||
16878 | DefineImplicitDestructor(Loc, Destructor); | ||||
16879 | } | ||||
16880 | if (Destructor->isVirtual() && getLangOpts().AppleKext) | ||||
16881 | MarkVTableUsed(Loc, Destructor->getParent()); | ||||
16882 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { | ||||
16883 | if (MethodDecl->isOverloadedOperator() && | ||||
16884 | MethodDecl->getOverloadedOperator() == OO_Equal) { | ||||
16885 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); | ||||
16886 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { | ||||
16887 | if (MethodDecl->isCopyAssignmentOperator()) | ||||
16888 | DefineImplicitCopyAssignment(Loc, MethodDecl); | ||||
16889 | else if (MethodDecl->isMoveAssignmentOperator()) | ||||
16890 | DefineImplicitMoveAssignment(Loc, MethodDecl); | ||||
16891 | } | ||||
16892 | } else if (isa<CXXConversionDecl>(MethodDecl) && | ||||
16893 | MethodDecl->getParent()->isLambda()) { | ||||
16894 | CXXConversionDecl *Conversion = | ||||
16895 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); | ||||
16896 | if (Conversion->isLambdaToBlockPointerConversion()) | ||||
16897 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); | ||||
16898 | else | ||||
16899 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); | ||||
16900 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) | ||||
16901 | MarkVTableUsed(Loc, MethodDecl->getParent()); | ||||
16902 | } | ||||
16903 | |||||
16904 | if (Func->isDefaulted() && !Func->isDeleted()) { | ||||
16905 | DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); | ||||
16906 | if (DCK != DefaultedComparisonKind::None) | ||||
16907 | DefineDefaultedComparison(Loc, Func, DCK); | ||||
16908 | } | ||||
16909 | |||||
16910 | // Implicit instantiation of function templates and member functions of | ||||
16911 | // class templates. | ||||
16912 | if (Func->isImplicitlyInstantiable()) { | ||||
16913 | TemplateSpecializationKind TSK = | ||||
16914 | Func->getTemplateSpecializationKindForInstantiation(); | ||||
16915 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); | ||||
16916 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
16917 | if (FirstInstantiation) { | ||||
16918 | PointOfInstantiation = Loc; | ||||
16919 | if (auto *MSI = Func->getMemberSpecializationInfo()) | ||||
16920 | MSI->setPointOfInstantiation(Loc); | ||||
16921 | // FIXME: Notify listener. | ||||
16922 | else | ||||
16923 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
16924 | } else if (TSK != TSK_ImplicitInstantiation) { | ||||
16925 | // Use the point of use as the point of instantiation, instead of the | ||||
16926 | // point of explicit instantiation (which we track as the actual point | ||||
16927 | // of instantiation). This gives better backtraces in diagnostics. | ||||
16928 | PointOfInstantiation = Loc; | ||||
16929 | } | ||||
16930 | |||||
16931 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || | ||||
16932 | Func->isConstexpr()) { | ||||
16933 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && | ||||
16934 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && | ||||
16935 | CodeSynthesisContexts.size()) | ||||
16936 | PendingLocalImplicitInstantiations.push_back( | ||||
16937 | std::make_pair(Func, PointOfInstantiation)); | ||||
16938 | else if (Func->isConstexpr()) | ||||
16939 | // Do not defer instantiations of constexpr functions, to avoid the | ||||
16940 | // expression evaluator needing to call back into Sema if it sees a | ||||
16941 | // call to such a function. | ||||
16942 | InstantiateFunctionDefinition(PointOfInstantiation, Func); | ||||
16943 | else { | ||||
16944 | Func->setInstantiationIsPending(true); | ||||
16945 | PendingInstantiations.push_back( | ||||
16946 | std::make_pair(Func, PointOfInstantiation)); | ||||
16947 | // Notify the consumer that a function was implicitly instantiated. | ||||
16948 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); | ||||
16949 | } | ||||
16950 | } | ||||
16951 | } else { | ||||
16952 | // Walk redefinitions, as some of them may be instantiable. | ||||
16953 | for (auto i : Func->redecls()) { | ||||
16954 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) | ||||
16955 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); | ||||
16956 | } | ||||
16957 | } | ||||
16958 | }); | ||||
16959 | } | ||||
16960 | |||||
16961 | // C++14 [except.spec]p17: | ||||
16962 | // An exception-specification is considered to be needed when: | ||||
16963 | // - the function is odr-used or, if it appears in an unevaluated operand, | ||||
16964 | // would be odr-used if the expression were potentially-evaluated; | ||||
16965 | // | ||||
16966 | // Note, we do this even if MightBeOdrUse is false. That indicates that the | ||||
16967 | // function is a pure virtual function we're calling, and in that case the | ||||
16968 | // function was selected by overload resolution and we need to resolve its | ||||
16969 | // exception specification for a different reason. | ||||
16970 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); | ||||
16971 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) | ||||
16972 | ResolveExceptionSpec(Loc, FPT); | ||||
16973 | |||||
16974 | // If this is the first "real" use, act on that. | ||||
16975 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { | ||||
16976 | // Keep track of used but undefined functions. | ||||
16977 | if (!Func->isDefined()) { | ||||
16978 | if (mightHaveNonExternalLinkage(Func)) | ||||
16979 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
16980 | else if (Func->getMostRecentDecl()->isInlined() && | ||||
16981 | !LangOpts.GNUInline && | ||||
16982 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) | ||||
16983 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
16984 | else if (isExternalWithNoLinkageType(Func)) | ||||
16985 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); | ||||
16986 | } | ||||
16987 | |||||
16988 | // Some x86 Windows calling conventions mangle the size of the parameter | ||||
16989 | // pack into the name. Computing the size of the parameters requires the | ||||
16990 | // parameter types to be complete. Check that now. | ||||
16991 | if (funcHasParameterSizeMangling(*this, Func)) | ||||
16992 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); | ||||
16993 | |||||
16994 | // In the MS C++ ABI, the compiler emits destructor variants where they are | ||||
16995 | // used. If the destructor is used here but defined elsewhere, mark the | ||||
16996 | // virtual base destructors referenced. If those virtual base destructors | ||||
16997 | // are inline, this will ensure they are defined when emitting the complete | ||||
16998 | // destructor variant. This checking may be redundant if the destructor is | ||||
16999 | // provided later in this TU. | ||||
17000 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
17001 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { | ||||
17002 | CXXRecordDecl *Parent = Dtor->getParent(); | ||||
17003 | if (Parent->getNumVBases() > 0 && !Dtor->getBody()) | ||||
17004 | CheckCompleteDestructorVariant(Loc, Dtor); | ||||
17005 | } | ||||
17006 | } | ||||
17007 | |||||
17008 | Func->markUsed(Context); | ||||
17009 | } | ||||
17010 | } | ||||
17011 | |||||
17012 | /// Directly mark a variable odr-used. Given a choice, prefer to use | ||||
17013 | /// MarkVariableReferenced since it does additional checks and then | ||||
17014 | /// calls MarkVarDeclODRUsed. | ||||
17015 | /// If the variable must be captured: | ||||
17016 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext | ||||
17017 | /// - else capture it in the DeclContext that maps to the | ||||
17018 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. | ||||
17019 | static void | ||||
17020 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, | ||||
17021 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { | ||||
17022 | // Keep track of used but undefined variables. | ||||
17023 | // FIXME: We shouldn't suppress this warning for static data members. | ||||
17024 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && | ||||
17025 | (!Var->isExternallyVisible() || Var->isInline() || | ||||
17026 | SemaRef.isExternalWithNoLinkageType(Var)) && | ||||
17027 | !(Var->isStaticDataMember() && Var->hasInit())) { | ||||
17028 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; | ||||
17029 | if (old.isInvalid()) | ||||
17030 | old = Loc; | ||||
17031 | } | ||||
17032 | QualType CaptureType, DeclRefType; | ||||
17033 | if (SemaRef.LangOpts.OpenMP) | ||||
17034 | SemaRef.tryCaptureOpenMPLambdas(Var); | ||||
17035 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, | ||||
17036 | /*EllipsisLoc*/ SourceLocation(), | ||||
17037 | /*BuildAndDiagnose*/ true, | ||||
17038 | CaptureType, DeclRefType, | ||||
17039 | FunctionScopeIndexToStopAt); | ||||
17040 | |||||
17041 | Var->markUsed(SemaRef.Context); | ||||
17042 | } | ||||
17043 | |||||
17044 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, | ||||
17045 | SourceLocation Loc, | ||||
17046 | unsigned CapturingScopeIndex) { | ||||
17047 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); | ||||
17048 | } | ||||
17049 | |||||
17050 | static void | ||||
17051 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, | ||||
17052 | ValueDecl *var, DeclContext *DC) { | ||||
17053 | DeclContext *VarDC = var->getDeclContext(); | ||||
17054 | |||||
17055 | // If the parameter still belongs to the translation unit, then | ||||
17056 | // we're actually just using one parameter in the declaration of | ||||
17057 | // the next. | ||||
17058 | if (isa<ParmVarDecl>(var) && | ||||
17059 | isa<TranslationUnitDecl>(VarDC)) | ||||
17060 | return; | ||||
17061 | |||||
17062 | // For C code, don't diagnose about capture if we're not actually in code | ||||
17063 | // right now; it's impossible to write a non-constant expression outside of | ||||
17064 | // function context, so we'll get other (more useful) diagnostics later. | ||||
17065 | // | ||||
17066 | // For C++, things get a bit more nasty... it would be nice to suppress this | ||||
17067 | // diagnostic for certain cases like using a local variable in an array bound | ||||
17068 | // for a member of a local class, but the correct predicate is not obvious. | ||||
17069 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) | ||||
17070 | return; | ||||
17071 | |||||
17072 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; | ||||
17073 | unsigned ContextKind = 3; // unknown | ||||
17074 | if (isa<CXXMethodDecl>(VarDC) && | ||||
17075 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { | ||||
17076 | ContextKind = 2; | ||||
17077 | } else if (isa<FunctionDecl>(VarDC)) { | ||||
17078 | ContextKind = 0; | ||||
17079 | } else if (isa<BlockDecl>(VarDC)) { | ||||
17080 | ContextKind = 1; | ||||
17081 | } | ||||
17082 | |||||
17083 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) | ||||
17084 | << var << ValueKind << ContextKind << VarDC; | ||||
17085 | S.Diag(var->getLocation(), diag::note_entity_declared_at) | ||||
17086 | << var; | ||||
17087 | |||||
17088 | // FIXME: Add additional diagnostic info about class etc. which prevents | ||||
17089 | // capture. | ||||
17090 | } | ||||
17091 | |||||
17092 | |||||
17093 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17094 | bool &SubCapturesAreNested, | ||||
17095 | QualType &CaptureType, | ||||
17096 | QualType &DeclRefType) { | ||||
17097 | // Check whether we've already captured it. | ||||
17098 | if (CSI->CaptureMap.count(Var)) { | ||||
17099 | // If we found a capture, any subcaptures are nested. | ||||
17100 | SubCapturesAreNested = true; | ||||
17101 | |||||
17102 | // Retrieve the capture type for this variable. | ||||
17103 | CaptureType = CSI->getCapture(Var).getCaptureType(); | ||||
17104 | |||||
17105 | // Compute the type of an expression that refers to this variable. | ||||
17106 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17107 | |||||
17108 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy | ||||
17109 | // are mutable in the sense that user can change their value - they are | ||||
17110 | // private instances of the captured declarations. | ||||
17111 | const Capture &Cap = CSI->getCapture(Var); | ||||
17112 | if (Cap.isCopyCapture() && | ||||
17113 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && | ||||
17114 | !(isa<CapturedRegionScopeInfo>(CSI) && | ||||
17115 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) | ||||
17116 | DeclRefType.addConst(); | ||||
17117 | return true; | ||||
17118 | } | ||||
17119 | return false; | ||||
17120 | } | ||||
17121 | |||||
17122 | // Only block literals, captured statements, and lambda expressions can | ||||
17123 | // capture; other scopes don't work. | ||||
17124 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, | ||||
17125 | SourceLocation Loc, | ||||
17126 | const bool Diagnose, Sema &S) { | ||||
17127 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) | ||||
17128 | return getLambdaAwareParentOfDeclContext(DC); | ||||
17129 | else if (Var->hasLocalStorage()) { | ||||
17130 | if (Diagnose) | ||||
17131 | diagnoseUncapturableValueReference(S, Loc, Var, DC); | ||||
17132 | } | ||||
17133 | return nullptr; | ||||
17134 | } | ||||
17135 | |||||
17136 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
17137 | // certain types of variables (unnamed, variably modified types etc.) | ||||
17138 | // so check for eligibility. | ||||
17139 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, | ||||
17140 | SourceLocation Loc, | ||||
17141 | const bool Diagnose, Sema &S) { | ||||
17142 | |||||
17143 | bool IsBlock = isa<BlockScopeInfo>(CSI); | ||||
17144 | bool IsLambda = isa<LambdaScopeInfo>(CSI); | ||||
17145 | |||||
17146 | // Lambdas are not allowed to capture unnamed variables | ||||
17147 | // (e.g. anonymous unions). | ||||
17148 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm | ||||
17149 | // assuming that's the intent. | ||||
17150 | if (IsLambda && !Var->getDeclName()) { | ||||
17151 | if (Diagnose) { | ||||
17152 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); | ||||
17153 | S.Diag(Var->getLocation(), diag::note_declared_at); | ||||
17154 | } | ||||
17155 | return false; | ||||
17156 | } | ||||
17157 | |||||
17158 | // Prohibit variably-modified types in blocks; they're difficult to deal with. | ||||
17159 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { | ||||
17160 | if (Diagnose) { | ||||
17161 | S.Diag(Loc, diag::err_ref_vm_type); | ||||
17162 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17163 | } | ||||
17164 | return false; | ||||
17165 | } | ||||
17166 | // Prohibit structs with flexible array members too. | ||||
17167 | // We cannot capture what is in the tail end of the struct. | ||||
17168 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { | ||||
17169 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
17170 | if (Diagnose) { | ||||
17171 | if (IsBlock) | ||||
17172 | S.Diag(Loc, diag::err_ref_flexarray_type); | ||||
17173 | else | ||||
17174 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; | ||||
17175 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17176 | } | ||||
17177 | return false; | ||||
17178 | } | ||||
17179 | } | ||||
17180 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17181 | // Lambdas and captured statements are not allowed to capture __block | ||||
17182 | // variables; they don't support the expected semantics. | ||||
17183 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { | ||||
17184 | if (Diagnose) { | ||||
17185 | S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; | ||||
17186 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17187 | } | ||||
17188 | return false; | ||||
17189 | } | ||||
17190 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks | ||||
17191 | if (S.getLangOpts().OpenCL && IsBlock && | ||||
17192 | Var->getType()->isBlockPointerType()) { | ||||
17193 | if (Diagnose) | ||||
17194 | S.Diag(Loc, diag::err_opencl_block_ref_block); | ||||
17195 | return false; | ||||
17196 | } | ||||
17197 | |||||
17198 | return true; | ||||
17199 | } | ||||
17200 | |||||
17201 | // Returns true if the capture by block was successful. | ||||
17202 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, | ||||
17203 | SourceLocation Loc, | ||||
17204 | const bool BuildAndDiagnose, | ||||
17205 | QualType &CaptureType, | ||||
17206 | QualType &DeclRefType, | ||||
17207 | const bool Nested, | ||||
17208 | Sema &S, bool Invalid) { | ||||
17209 | bool ByRef = false; | ||||
17210 | |||||
17211 | // Blocks are not allowed to capture arrays, excepting OpenCL. | ||||
17212 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference | ||||
17213 | // (decayed to pointers). | ||||
17214 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { | ||||
17215 | if (BuildAndDiagnose) { | ||||
17216 | S.Diag(Loc, diag::err_ref_array_type); | ||||
17217 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17218 | Invalid = true; | ||||
17219 | } else { | ||||
17220 | return false; | ||||
17221 | } | ||||
17222 | } | ||||
17223 | |||||
17224 | // Forbid the block-capture of autoreleasing variables. | ||||
17225 | if (!Invalid && | ||||
17226 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17227 | if (BuildAndDiagnose) { | ||||
17228 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) | ||||
17229 | << /*block*/ 0; | ||||
17230 | S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17231 | Invalid = true; | ||||
17232 | } else { | ||||
17233 | return false; | ||||
17234 | } | ||||
17235 | } | ||||
17236 | |||||
17237 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. | ||||
17238 | if (const auto *PT = CaptureType->getAs<PointerType>()) { | ||||
17239 | QualType PointeeTy = PT->getPointeeType(); | ||||
17240 | |||||
17241 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && | ||||
17242 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && | ||||
17243 | !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { | ||||
17244 | if (BuildAndDiagnose) { | ||||
17245 | SourceLocation VarLoc = Var->getLocation(); | ||||
17246 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); | ||||
17247 | S.Diag(VarLoc, diag::note_declare_parameter_strong); | ||||
17248 | } | ||||
17249 | } | ||||
17250 | } | ||||
17251 | |||||
17252 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); | ||||
17253 | if (HasBlocksAttr || CaptureType->isReferenceType() || | ||||
17254 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { | ||||
17255 | // Block capture by reference does not change the capture or | ||||
17256 | // declaration reference types. | ||||
17257 | ByRef = true; | ||||
17258 | } else { | ||||
17259 | // Block capture by copy introduces 'const'. | ||||
17260 | CaptureType = CaptureType.getNonReferenceType().withConst(); | ||||
17261 | DeclRefType = CaptureType; | ||||
17262 | } | ||||
17263 | |||||
17264 | // Actually capture the variable. | ||||
17265 | if (BuildAndDiagnose) | ||||
17266 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), | ||||
17267 | CaptureType, Invalid); | ||||
17268 | |||||
17269 | return !Invalid; | ||||
17270 | } | ||||
17271 | |||||
17272 | |||||
17273 | /// Capture the given variable in the captured region. | ||||
17274 | static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, | ||||
17275 | VarDecl *Var, | ||||
17276 | SourceLocation Loc, | ||||
17277 | const bool BuildAndDiagnose, | ||||
17278 | QualType &CaptureType, | ||||
17279 | QualType &DeclRefType, | ||||
17280 | const bool RefersToCapturedVariable, | ||||
17281 | Sema &S, bool Invalid) { | ||||
17282 | // By default, capture variables by reference. | ||||
17283 | bool ByRef = true; | ||||
17284 | // Using an LValue reference type is consistent with Lambdas (see below). | ||||
17285 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { | ||||
17286 | if (S.isOpenMPCapturedDecl(Var)) { | ||||
17287 | bool HasConst = DeclRefType.isConstQualified(); | ||||
17288 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
17289 | // Don't lose diagnostics about assignments to const. | ||||
17290 | if (HasConst) | ||||
17291 | DeclRefType.addConst(); | ||||
17292 | } | ||||
17293 | // Do not capture firstprivates in tasks. | ||||
17294 | if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != | ||||
17295 | OMPC_unknown) | ||||
17296 | return true; | ||||
17297 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, | ||||
17298 | RSI->OpenMPCaptureLevel); | ||||
17299 | } | ||||
17300 | |||||
17301 | if (ByRef) | ||||
17302 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17303 | else | ||||
17304 | CaptureType = DeclRefType; | ||||
17305 | |||||
17306 | // Actually capture the variable. | ||||
17307 | if (BuildAndDiagnose) | ||||
17308 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, | ||||
17309 | Loc, SourceLocation(), CaptureType, Invalid); | ||||
17310 | |||||
17311 | return !Invalid; | ||||
17312 | } | ||||
17313 | |||||
17314 | /// Capture the given variable in the lambda. | ||||
17315 | static bool captureInLambda(LambdaScopeInfo *LSI, | ||||
17316 | VarDecl *Var, | ||||
17317 | SourceLocation Loc, | ||||
17318 | const bool BuildAndDiagnose, | ||||
17319 | QualType &CaptureType, | ||||
17320 | QualType &DeclRefType, | ||||
17321 | const bool RefersToCapturedVariable, | ||||
17322 | const Sema::TryCaptureKind Kind, | ||||
17323 | SourceLocation EllipsisLoc, | ||||
17324 | const bool IsTopScope, | ||||
17325 | Sema &S, bool Invalid) { | ||||
17326 | // Determine whether we are capturing by reference or by value. | ||||
17327 | bool ByRef = false; | ||||
17328 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { | ||||
17329 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); | ||||
17330 | } else { | ||||
17331 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); | ||||
17332 | } | ||||
17333 | |||||
17334 | // Compute the type of the field that will capture this variable. | ||||
17335 | if (ByRef) { | ||||
17336 | // C++11 [expr.prim.lambda]p15: | ||||
17337 | // An entity is captured by reference if it is implicitly or | ||||
17338 | // explicitly captured but not captured by copy. It is | ||||
17339 | // unspecified whether additional unnamed non-static data | ||||
17340 | // members are declared in the closure type for entities | ||||
17341 | // captured by reference. | ||||
17342 | // | ||||
17343 | // FIXME: It is not clear whether we want to build an lvalue reference | ||||
17344 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears | ||||
17345 | // to do the former, while EDG does the latter. Core issue 1249 will | ||||
17346 | // clarify, but for now we follow GCC because it's a more permissive and | ||||
17347 | // easily defensible position. | ||||
17348 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); | ||||
17349 | } else { | ||||
17350 | // C++11 [expr.prim.lambda]p14: | ||||
17351 | // For each entity captured by copy, an unnamed non-static | ||||
17352 | // data member is declared in the closure type. The | ||||
17353 | // declaration order of these members is unspecified. The type | ||||
17354 | // of such a data member is the type of the corresponding | ||||
17355 | // captured entity if the entity is not a reference to an | ||||
17356 | // object, or the referenced type otherwise. [Note: If the | ||||
17357 | // captured entity is a reference to a function, the | ||||
17358 | // corresponding data member is also a reference to a | ||||
17359 | // function. - end note ] | ||||
17360 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ | ||||
17361 | if (!RefType->getPointeeType()->isFunctionType()) | ||||
17362 | CaptureType = RefType->getPointeeType(); | ||||
17363 | } | ||||
17364 | |||||
17365 | // Forbid the lambda copy-capture of autoreleasing variables. | ||||
17366 | if (!Invalid && | ||||
17367 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { | ||||
17368 | if (BuildAndDiagnose) { | ||||
17369 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; | ||||
17370 | S.Diag(Var->getLocation(), diag::note_previous_decl) | ||||
17371 | << Var->getDeclName(); | ||||
17372 | Invalid = true; | ||||
17373 | } else { | ||||
17374 | return false; | ||||
17375 | } | ||||
17376 | } | ||||
17377 | |||||
17378 | // Make sure that by-copy captures are of a complete and non-abstract type. | ||||
17379 | if (!Invalid && BuildAndDiagnose) { | ||||
17380 | if (!CaptureType->isDependentType() && | ||||
17381 | S.RequireCompleteSizedType( | ||||
17382 | Loc, CaptureType, | ||||
17383 | diag::err_capture_of_incomplete_or_sizeless_type, | ||||
17384 | Var->getDeclName())) | ||||
17385 | Invalid = true; | ||||
17386 | else if (S.RequireNonAbstractType(Loc, CaptureType, | ||||
17387 | diag::err_capture_of_abstract_type)) | ||||
17388 | Invalid = true; | ||||
17389 | } | ||||
17390 | } | ||||
17391 | |||||
17392 | // Compute the type of a reference to this captured variable. | ||||
17393 | if (ByRef) | ||||
17394 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17395 | else { | ||||
17396 | // C++ [expr.prim.lambda]p5: | ||||
17397 | // The closure type for a lambda-expression has a public inline | ||||
17398 | // function call operator [...]. This function call operator is | ||||
17399 | // declared const (9.3.1) if and only if the lambda-expression's | ||||
17400 | // parameter-declaration-clause is not followed by mutable. | ||||
17401 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17402 | if (!LSI->Mutable && !CaptureType->isReferenceType()) | ||||
17403 | DeclRefType.addConst(); | ||||
17404 | } | ||||
17405 | |||||
17406 | // Add the capture. | ||||
17407 | if (BuildAndDiagnose) | ||||
17408 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, | ||||
17409 | Loc, EllipsisLoc, CaptureType, Invalid); | ||||
17410 | |||||
17411 | return !Invalid; | ||||
17412 | } | ||||
17413 | |||||
17414 | bool Sema::tryCaptureVariable( | ||||
17415 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, | ||||
17416 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, | ||||
17417 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { | ||||
17418 | // An init-capture is notionally from the context surrounding its | ||||
17419 | // declaration, but its parent DC is the lambda class. | ||||
17420 | DeclContext *VarDC = Var->getDeclContext(); | ||||
17421 | if (Var->isInitCapture()) | ||||
17422 | VarDC = VarDC->getParent(); | ||||
17423 | |||||
17424 | DeclContext *DC = CurContext; | ||||
17425 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | ||||
17426 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; | ||||
17427 | // We need to sync up the Declaration Context with the | ||||
17428 | // FunctionScopeIndexToStopAt | ||||
17429 | if (FunctionScopeIndexToStopAt) { | ||||
17430 | unsigned FSIndex = FunctionScopes.size() - 1; | ||||
17431 | while (FSIndex != MaxFunctionScopesIndex) { | ||||
17432 | DC = getLambdaAwareParentOfDeclContext(DC); | ||||
17433 | --FSIndex; | ||||
17434 | } | ||||
17435 | } | ||||
17436 | |||||
17437 | |||||
17438 | // If the variable is declared in the current context, there is no need to | ||||
17439 | // capture it. | ||||
17440 | if (VarDC == DC) return true; | ||||
17441 | |||||
17442 | // Capture global variables if it is required to use private copy of this | ||||
17443 | // variable. | ||||
17444 | bool IsGlobal = !Var->hasLocalStorage(); | ||||
17445 | if (IsGlobal && | ||||
17446 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, | ||||
17447 | MaxFunctionScopesIndex))) | ||||
17448 | return true; | ||||
17449 | Var = Var->getCanonicalDecl(); | ||||
17450 | |||||
17451 | // Walk up the stack to determine whether we can capture the variable, | ||||
17452 | // performing the "simple" checks that don't depend on type. We stop when | ||||
17453 | // we've either hit the declared scope of the variable or find an existing | ||||
17454 | // capture of that variable. We start from the innermost capturing-entity | ||||
17455 | // (the DC) and ensure that all intervening capturing-entities | ||||
17456 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s | ||||
17457 | // declcontext can either capture the variable or have already captured | ||||
17458 | // the variable. | ||||
17459 | CaptureType = Var->getType(); | ||||
17460 | DeclRefType = CaptureType.getNonReferenceType(); | ||||
17461 | bool Nested = false; | ||||
17462 | bool Explicit = (Kind != TryCapture_Implicit); | ||||
17463 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; | ||||
17464 | do { | ||||
17465 | // Only block literals, captured statements, and lambda expressions can | ||||
17466 | // capture; other scopes don't work. | ||||
17467 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, | ||||
17468 | ExprLoc, | ||||
17469 | BuildAndDiagnose, | ||||
17470 | *this); | ||||
17471 | // We need to check for the parent *first* because, if we *have* | ||||
17472 | // private-captured a global variable, we need to recursively capture it in | ||||
17473 | // intermediate blocks, lambdas, etc. | ||||
17474 | if (!ParentDC) { | ||||
17475 | if (IsGlobal) { | ||||
17476 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; | ||||
17477 | break; | ||||
17478 | } | ||||
17479 | return true; | ||||
17480 | } | ||||
17481 | |||||
17482 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; | ||||
17483 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); | ||||
17484 | |||||
17485 | |||||
17486 | // Check whether we've already captured it. | ||||
17487 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, | ||||
17488 | DeclRefType)) { | ||||
17489 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); | ||||
17490 | break; | ||||
17491 | } | ||||
17492 | // If we are instantiating a generic lambda call operator body, | ||||
17493 | // we do not want to capture new variables. What was captured | ||||
17494 | // during either a lambdas transformation or initial parsing | ||||
17495 | // should be used. | ||||
17496 | if (isGenericLambdaCallOperatorSpecialization(DC)) { | ||||
17497 | if (BuildAndDiagnose) { | ||||
17498 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17499 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { | ||||
17500 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
17501 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17502 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); | ||||
17503 | } else | ||||
17504 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); | ||||
17505 | } | ||||
17506 | return true; | ||||
17507 | } | ||||
17508 | |||||
17509 | // Try to capture variable-length arrays types. | ||||
17510 | if (Var->getType()->isVariablyModifiedType()) { | ||||
17511 | // We're going to walk down into the type and look for VLA | ||||
17512 | // expressions. | ||||
17513 | QualType QTy = Var->getType(); | ||||
17514 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
17515 | QTy = PVD->getOriginalType(); | ||||
17516 | captureVariablyModifiedType(Context, QTy, CSI); | ||||
17517 | } | ||||
17518 | |||||
17519 | if (getLangOpts().OpenMP) { | ||||
17520 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
17521 | // OpenMP private variables should not be captured in outer scope, so | ||||
17522 | // just break here. Similarly, global variables that are captured in a | ||||
17523 | // target region should not be captured outside the scope of the region. | ||||
17524 | if (RSI->CapRegionKind == CR_OpenMP) { | ||||
17525 | OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( | ||||
17526 | Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); | ||||
17527 | // If the variable is private (i.e. not captured) and has variably | ||||
17528 | // modified type, we still need to capture the type for correct | ||||
17529 | // codegen in all regions, associated with the construct. Currently, | ||||
17530 | // it is captured in the innermost captured region only. | ||||
17531 | if (IsOpenMPPrivateDecl != OMPC_unknown && | ||||
17532 | Var->getType()->isVariablyModifiedType()) { | ||||
17533 | QualType QTy = Var->getType(); | ||||
17534 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) | ||||
17535 | QTy = PVD->getOriginalType(); | ||||
17536 | for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); | ||||
17537 | I < E; ++I) { | ||||
17538 | auto *OuterRSI = cast<CapturedRegionScopeInfo>( | ||||
17539 | FunctionScopes[FunctionScopesIndex - I]); | ||||
17540 | assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 17542, __PRETTY_FUNCTION__)) | ||||
17541 | "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 17542, __PRETTY_FUNCTION__)) | ||||
17542 | "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the " "OpenMP construct.") ? static_cast<void> (0) : __assert_fail ("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 17542, __PRETTY_FUNCTION__)); | ||||
17543 | captureVariablyModifiedType(Context, QTy, OuterRSI); | ||||
17544 | } | ||||
17545 | } | ||||
17546 | bool IsTargetCap = | ||||
17547 | IsOpenMPPrivateDecl != OMPC_private && | ||||
17548 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, | ||||
17549 | RSI->OpenMPCaptureLevel); | ||||
17550 | // Do not capture global if it is not privatized in outer regions. | ||||
17551 | bool IsGlobalCap = | ||||
17552 | IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, | ||||
17553 | RSI->OpenMPCaptureLevel); | ||||
17554 | |||||
17555 | // When we detect target captures we are looking from inside the | ||||
17556 | // target region, therefore we need to propagate the capture from the | ||||
17557 | // enclosing region. Therefore, the capture is not initially nested. | ||||
17558 | if (IsTargetCap) | ||||
17559 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); | ||||
17560 | |||||
17561 | if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || | ||||
17562 | (IsGlobal && !IsGlobalCap)) { | ||||
17563 | Nested = !IsTargetCap; | ||||
17564 | bool HasConst = DeclRefType.isConstQualified(); | ||||
17565 | DeclRefType = DeclRefType.getUnqualifiedType(); | ||||
17566 | // Don't lose diagnostics about assignments to const. | ||||
17567 | if (HasConst) | ||||
17568 | DeclRefType.addConst(); | ||||
17569 | CaptureType = Context.getLValueReferenceType(DeclRefType); | ||||
17570 | break; | ||||
17571 | } | ||||
17572 | } | ||||
17573 | } | ||||
17574 | } | ||||
17575 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { | ||||
17576 | // No capture-default, and this is not an explicit capture | ||||
17577 | // so cannot capture this variable. | ||||
17578 | if (BuildAndDiagnose) { | ||||
17579 | Diag(ExprLoc, diag::err_lambda_impcap) << Var; | ||||
17580 | Diag(Var->getLocation(), diag::note_previous_decl) << Var; | ||||
17581 | if (cast<LambdaScopeInfo>(CSI)->Lambda) | ||||
17582 | Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), | ||||
17583 | diag::note_lambda_decl); | ||||
17584 | // FIXME: If we error out because an outer lambda can not implicitly | ||||
17585 | // capture a variable that an inner lambda explicitly captures, we | ||||
17586 | // should have the inner lambda do the explicit capture - because | ||||
17587 | // it makes for cleaner diagnostics later. This would purely be done | ||||
17588 | // so that the diagnostic does not misleadingly claim that a variable | ||||
17589 | // can not be captured by a lambda implicitly even though it is captured | ||||
17590 | // explicitly. Suggestion: | ||||
17591 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit | ||||
17592 | // at the function head | ||||
17593 | // - cache the StartingDeclContext - this must be a lambda | ||||
17594 | // - captureInLambda in the innermost lambda the variable. | ||||
17595 | } | ||||
17596 | return true; | ||||
17597 | } | ||||
17598 | |||||
17599 | FunctionScopesIndex--; | ||||
17600 | DC = ParentDC; | ||||
17601 | Explicit = false; | ||||
17602 | } while (!VarDC->Equals(DC)); | ||||
17603 | |||||
17604 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) | ||||
17605 | // computing the type of the capture at each step, checking type-specific | ||||
17606 | // requirements, and adding captures if requested. | ||||
17607 | // If the variable had already been captured previously, we start capturing | ||||
17608 | // at the lambda nested within that one. | ||||
17609 | bool Invalid = false; | ||||
17610 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; | ||||
17611 | ++I) { | ||||
17612 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); | ||||
17613 | |||||
17614 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture | ||||
17615 | // certain types of variables (unnamed, variably modified types etc.) | ||||
17616 | // so check for eligibility. | ||||
17617 | if (!Invalid) | ||||
17618 | Invalid = | ||||
17619 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); | ||||
17620 | |||||
17621 | // After encountering an error, if we're actually supposed to capture, keep | ||||
17622 | // capturing in nested contexts to suppress any follow-on diagnostics. | ||||
17623 | if (Invalid && !BuildAndDiagnose) | ||||
17624 | return true; | ||||
17625 | |||||
17626 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { | ||||
17627 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
17628 | DeclRefType, Nested, *this, Invalid); | ||||
17629 | Nested = true; | ||||
17630 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { | ||||
17631 | Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, | ||||
17632 | CaptureType, DeclRefType, Nested, | ||||
17633 | *this, Invalid); | ||||
17634 | Nested = true; | ||||
17635 | } else { | ||||
17636 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); | ||||
17637 | Invalid = | ||||
17638 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, | ||||
17639 | DeclRefType, Nested, Kind, EllipsisLoc, | ||||
17640 | /*IsTopScope*/ I == N - 1, *this, Invalid); | ||||
17641 | Nested = true; | ||||
17642 | } | ||||
17643 | |||||
17644 | if (Invalid && !BuildAndDiagnose) | ||||
17645 | return true; | ||||
17646 | } | ||||
17647 | return Invalid; | ||||
17648 | } | ||||
17649 | |||||
17650 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | ||||
17651 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { | ||||
17652 | QualType CaptureType; | ||||
17653 | QualType DeclRefType; | ||||
17654 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, | ||||
17655 | /*BuildAndDiagnose=*/true, CaptureType, | ||||
17656 | DeclRefType, nullptr); | ||||
17657 | } | ||||
17658 | |||||
17659 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { | ||||
17660 | QualType CaptureType; | ||||
17661 | QualType DeclRefType; | ||||
17662 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
17663 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
17664 | DeclRefType, nullptr); | ||||
17665 | } | ||||
17666 | |||||
17667 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { | ||||
17668 | QualType CaptureType; | ||||
17669 | QualType DeclRefType; | ||||
17670 | |||||
17671 | // Determine whether we can capture this variable. | ||||
17672 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), | ||||
17673 | /*BuildAndDiagnose=*/false, CaptureType, | ||||
17674 | DeclRefType, nullptr)) | ||||
17675 | return QualType(); | ||||
17676 | |||||
17677 | return DeclRefType; | ||||
17678 | } | ||||
17679 | |||||
17680 | namespace { | ||||
17681 | // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. | ||||
17682 | // The produced TemplateArgumentListInfo* points to data stored within this | ||||
17683 | // object, so should only be used in contexts where the pointer will not be | ||||
17684 | // used after the CopiedTemplateArgs object is destroyed. | ||||
17685 | class CopiedTemplateArgs { | ||||
17686 | bool HasArgs; | ||||
17687 | TemplateArgumentListInfo TemplateArgStorage; | ||||
17688 | public: | ||||
17689 | template<typename RefExpr> | ||||
17690 | CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { | ||||
17691 | if (HasArgs) | ||||
17692 | E->copyTemplateArgumentsInto(TemplateArgStorage); | ||||
17693 | } | ||||
17694 | operator TemplateArgumentListInfo*() | ||||
17695 | #ifdef __has_cpp_attribute | ||||
17696 | #if0 __has_cpp_attribute(clang::lifetimebound)1 | ||||
17697 | [[clang::lifetimebound]] | ||||
17698 | #endif | ||||
17699 | #endif | ||||
17700 | { | ||||
17701 | return HasArgs ? &TemplateArgStorage : nullptr; | ||||
17702 | } | ||||
17703 | }; | ||||
17704 | } | ||||
17705 | |||||
17706 | /// Walk the set of potential results of an expression and mark them all as | ||||
17707 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. | ||||
17708 | /// | ||||
17709 | /// \return A new expression if we found any potential results, ExprEmpty() if | ||||
17710 | /// not, and ExprError() if we diagnosed an error. | ||||
17711 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, | ||||
17712 | NonOdrUseReason NOUR) { | ||||
17713 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is | ||||
17714 | // an object that satisfies the requirements for appearing in a | ||||
17715 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) | ||||
17716 | // is immediately applied." This function handles the lvalue-to-rvalue | ||||
17717 | // conversion part. | ||||
17718 | // | ||||
17719 | // If we encounter a node that claims to be an odr-use but shouldn't be, we | ||||
17720 | // transform it into the relevant kind of non-odr-use node and rebuild the | ||||
17721 | // tree of nodes leading to it. | ||||
17722 | // | ||||
17723 | // This is a mini-TreeTransform that only transforms a restricted subset of | ||||
17724 | // nodes (and only certain operands of them). | ||||
17725 | |||||
17726 | // Rebuild a subexpression. | ||||
17727 | auto Rebuild = [&](Expr *Sub) { | ||||
17728 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); | ||||
17729 | }; | ||||
17730 | |||||
17731 | // Check whether a potential result satisfies the requirements of NOUR. | ||||
17732 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { | ||||
17733 | // Any entity other than a VarDecl is always odr-used whenever it's named | ||||
17734 | // in a potentially-evaluated expression. | ||||
17735 | auto *VD = dyn_cast<VarDecl>(D); | ||||
17736 | if (!VD) | ||||
17737 | return true; | ||||
17738 | |||||
17739 | // C++2a [basic.def.odr]p4: | ||||
17740 | // A variable x whose name appears as a potentially-evalauted expression | ||||
17741 | // e is odr-used by e unless | ||||
17742 | // -- x is a reference that is usable in constant expressions, or | ||||
17743 | // -- x is a variable of non-reference type that is usable in constant | ||||
17744 | // expressions and has no mutable subobjects, and e is an element of | ||||
17745 | // the set of potential results of an expression of | ||||
17746 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
17747 | // conversion is applied, or | ||||
17748 | // -- x is a variable of non-reference type, and e is an element of the | ||||
17749 | // set of potential results of a discarded-value expression to which | ||||
17750 | // the lvalue-to-rvalue conversion is not applied | ||||
17751 | // | ||||
17752 | // We check the first bullet and the "potentially-evaluated" condition in | ||||
17753 | // BuildDeclRefExpr. We check the type requirements in the second bullet | ||||
17754 | // in CheckLValueToRValueConversionOperand below. | ||||
17755 | switch (NOUR) { | ||||
17756 | case NOUR_None: | ||||
17757 | case NOUR_Unevaluated: | ||||
17758 | llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 17758); | ||||
17759 | |||||
17760 | case NOUR_Constant: | ||||
17761 | // Constant references were handled when they were built. | ||||
17762 | if (VD->getType()->isReferenceType()) | ||||
17763 | return true; | ||||
17764 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) | ||||
17765 | if (RD->hasMutableFields()) | ||||
17766 | return true; | ||||
17767 | if (!VD->isUsableInConstantExpressions(S.Context)) | ||||
17768 | return true; | ||||
17769 | break; | ||||
17770 | |||||
17771 | case NOUR_Discarded: | ||||
17772 | if (VD->getType()->isReferenceType()) | ||||
17773 | return true; | ||||
17774 | break; | ||||
17775 | } | ||||
17776 | return false; | ||||
17777 | }; | ||||
17778 | |||||
17779 | // Mark that this expression does not constitute an odr-use. | ||||
17780 | auto MarkNotOdrUsed = [&] { | ||||
17781 | S.MaybeODRUseExprs.remove(E); | ||||
17782 | if (LambdaScopeInfo *LSI = S.getCurLambda()) | ||||
17783 | LSI->markVariableExprAsNonODRUsed(E); | ||||
17784 | }; | ||||
17785 | |||||
17786 | // C++2a [basic.def.odr]p2: | ||||
17787 | // The set of potential results of an expression e is defined as follows: | ||||
17788 | switch (E->getStmtClass()) { | ||||
17789 | // -- If e is an id-expression, ... | ||||
17790 | case Expr::DeclRefExprClass: { | ||||
17791 | auto *DRE = cast<DeclRefExpr>(E); | ||||
17792 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) | ||||
17793 | break; | ||||
17794 | |||||
17795 | // Rebuild as a non-odr-use DeclRefExpr. | ||||
17796 | MarkNotOdrUsed(); | ||||
17797 | return DeclRefExpr::Create( | ||||
17798 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), | ||||
17799 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), | ||||
17800 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), | ||||
17801 | DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); | ||||
17802 | } | ||||
17803 | |||||
17804 | case Expr::FunctionParmPackExprClass: { | ||||
17805 | auto *FPPE = cast<FunctionParmPackExpr>(E); | ||||
17806 | // If any of the declarations in the pack is odr-used, then the expression | ||||
17807 | // as a whole constitutes an odr-use. | ||||
17808 | for (VarDecl *D : *FPPE) | ||||
17809 | if (IsPotentialResultOdrUsed(D)) | ||||
17810 | return ExprEmpty(); | ||||
17811 | |||||
17812 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, | ||||
17813 | // nothing cares about whether we marked this as an odr-use, but it might | ||||
17814 | // be useful for non-compiler tools. | ||||
17815 | MarkNotOdrUsed(); | ||||
17816 | break; | ||||
17817 | } | ||||
17818 | |||||
17819 | // -- If e is a subscripting operation with an array operand... | ||||
17820 | case Expr::ArraySubscriptExprClass: { | ||||
17821 | auto *ASE = cast<ArraySubscriptExpr>(E); | ||||
17822 | Expr *OldBase = ASE->getBase()->IgnoreImplicit(); | ||||
17823 | if (!OldBase->getType()->isArrayType()) | ||||
17824 | break; | ||||
17825 | ExprResult Base = Rebuild(OldBase); | ||||
17826 | if (!Base.isUsable()) | ||||
17827 | return Base; | ||||
17828 | Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); | ||||
17829 | Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); | ||||
17830 | SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. | ||||
17831 | return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, | ||||
17832 | ASE->getRBracketLoc()); | ||||
17833 | } | ||||
17834 | |||||
17835 | case Expr::MemberExprClass: { | ||||
17836 | auto *ME = cast<MemberExpr>(E); | ||||
17837 | // -- If e is a class member access expression [...] naming a non-static | ||||
17838 | // data member... | ||||
17839 | if (isa<FieldDecl>(ME->getMemberDecl())) { | ||||
17840 | ExprResult Base = Rebuild(ME->getBase()); | ||||
17841 | if (!Base.isUsable()) | ||||
17842 | return Base; | ||||
17843 | return MemberExpr::Create( | ||||
17844 | S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), | ||||
17845 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), | ||||
17846 | ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), | ||||
17847 | CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), | ||||
17848 | ME->getObjectKind(), ME->isNonOdrUse()); | ||||
17849 | } | ||||
17850 | |||||
17851 | if (ME->getMemberDecl()->isCXXInstanceMember()) | ||||
17852 | break; | ||||
17853 | |||||
17854 | // -- If e is a class member access expression naming a static data member, | ||||
17855 | // ... | ||||
17856 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) | ||||
17857 | break; | ||||
17858 | |||||
17859 | // Rebuild as a non-odr-use MemberExpr. | ||||
17860 | MarkNotOdrUsed(); | ||||
17861 | return MemberExpr::Create( | ||||
17862 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), | ||||
17863 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), | ||||
17864 | ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), | ||||
17865 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); | ||||
17866 | return ExprEmpty(); | ||||
17867 | } | ||||
17868 | |||||
17869 | case Expr::BinaryOperatorClass: { | ||||
17870 | auto *BO = cast<BinaryOperator>(E); | ||||
17871 | Expr *LHS = BO->getLHS(); | ||||
17872 | Expr *RHS = BO->getRHS(); | ||||
17873 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... | ||||
17874 | if (BO->getOpcode() == BO_PtrMemD) { | ||||
17875 | ExprResult Sub = Rebuild(LHS); | ||||
17876 | if (!Sub.isUsable()) | ||||
17877 | return Sub; | ||||
17878 | LHS = Sub.get(); | ||||
17879 | // -- If e is a comma expression, ... | ||||
17880 | } else if (BO->getOpcode() == BO_Comma) { | ||||
17881 | ExprResult Sub = Rebuild(RHS); | ||||
17882 | if (!Sub.isUsable()) | ||||
17883 | return Sub; | ||||
17884 | RHS = Sub.get(); | ||||
17885 | } else { | ||||
17886 | break; | ||||
17887 | } | ||||
17888 | return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), | ||||
17889 | LHS, RHS); | ||||
17890 | } | ||||
17891 | |||||
17892 | // -- If e has the form (e1)... | ||||
17893 | case Expr::ParenExprClass: { | ||||
17894 | auto *PE = cast<ParenExpr>(E); | ||||
17895 | ExprResult Sub = Rebuild(PE->getSubExpr()); | ||||
17896 | if (!Sub.isUsable()) | ||||
17897 | return Sub; | ||||
17898 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); | ||||
17899 | } | ||||
17900 | |||||
17901 | // -- If e is a glvalue conditional expression, ... | ||||
17902 | // We don't apply this to a binary conditional operator. FIXME: Should we? | ||||
17903 | case Expr::ConditionalOperatorClass: { | ||||
17904 | auto *CO = cast<ConditionalOperator>(E); | ||||
17905 | ExprResult LHS = Rebuild(CO->getLHS()); | ||||
17906 | if (LHS.isInvalid()) | ||||
17907 | return ExprError(); | ||||
17908 | ExprResult RHS = Rebuild(CO->getRHS()); | ||||
17909 | if (RHS.isInvalid()) | ||||
17910 | return ExprError(); | ||||
17911 | if (!LHS.isUsable() && !RHS.isUsable()) | ||||
17912 | return ExprEmpty(); | ||||
17913 | if (!LHS.isUsable()) | ||||
17914 | LHS = CO->getLHS(); | ||||
17915 | if (!RHS.isUsable()) | ||||
17916 | RHS = CO->getRHS(); | ||||
17917 | return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), | ||||
17918 | CO->getCond(), LHS.get(), RHS.get()); | ||||
17919 | } | ||||
17920 | |||||
17921 | // [Clang extension] | ||||
17922 | // -- If e has the form __extension__ e1... | ||||
17923 | case Expr::UnaryOperatorClass: { | ||||
17924 | auto *UO = cast<UnaryOperator>(E); | ||||
17925 | if (UO->getOpcode() != UO_Extension) | ||||
17926 | break; | ||||
17927 | ExprResult Sub = Rebuild(UO->getSubExpr()); | ||||
17928 | if (!Sub.isUsable()) | ||||
17929 | return Sub; | ||||
17930 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, | ||||
17931 | Sub.get()); | ||||
17932 | } | ||||
17933 | |||||
17934 | // [Clang extension] | ||||
17935 | // -- If e has the form _Generic(...), the set of potential results is the | ||||
17936 | // union of the sets of potential results of the associated expressions. | ||||
17937 | case Expr::GenericSelectionExprClass: { | ||||
17938 | auto *GSE = cast<GenericSelectionExpr>(E); | ||||
17939 | |||||
17940 | SmallVector<Expr *, 4> AssocExprs; | ||||
17941 | bool AnyChanged = false; | ||||
17942 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { | ||||
17943 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); | ||||
17944 | if (AssocExpr.isInvalid()) | ||||
17945 | return ExprError(); | ||||
17946 | if (AssocExpr.isUsable()) { | ||||
17947 | AssocExprs.push_back(AssocExpr.get()); | ||||
17948 | AnyChanged = true; | ||||
17949 | } else { | ||||
17950 | AssocExprs.push_back(OrigAssocExpr); | ||||
17951 | } | ||||
17952 | } | ||||
17953 | |||||
17954 | return AnyChanged ? S.CreateGenericSelectionExpr( | ||||
17955 | GSE->getGenericLoc(), GSE->getDefaultLoc(), | ||||
17956 | GSE->getRParenLoc(), GSE->getControllingExpr(), | ||||
17957 | GSE->getAssocTypeSourceInfos(), AssocExprs) | ||||
17958 | : ExprEmpty(); | ||||
17959 | } | ||||
17960 | |||||
17961 | // [Clang extension] | ||||
17962 | // -- If e has the form __builtin_choose_expr(...), the set of potential | ||||
17963 | // results is the union of the sets of potential results of the | ||||
17964 | // second and third subexpressions. | ||||
17965 | case Expr::ChooseExprClass: { | ||||
17966 | auto *CE = cast<ChooseExpr>(E); | ||||
17967 | |||||
17968 | ExprResult LHS = Rebuild(CE->getLHS()); | ||||
17969 | if (LHS.isInvalid()) | ||||
17970 | return ExprError(); | ||||
17971 | |||||
17972 | ExprResult RHS = Rebuild(CE->getLHS()); | ||||
17973 | if (RHS.isInvalid()) | ||||
17974 | return ExprError(); | ||||
17975 | |||||
17976 | if (!LHS.get() && !RHS.get()) | ||||
17977 | return ExprEmpty(); | ||||
17978 | if (!LHS.isUsable()) | ||||
17979 | LHS = CE->getLHS(); | ||||
17980 | if (!RHS.isUsable()) | ||||
17981 | RHS = CE->getRHS(); | ||||
17982 | |||||
17983 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), | ||||
17984 | RHS.get(), CE->getRParenLoc()); | ||||
17985 | } | ||||
17986 | |||||
17987 | // Step through non-syntactic nodes. | ||||
17988 | case Expr::ConstantExprClass: { | ||||
17989 | auto *CE = cast<ConstantExpr>(E); | ||||
17990 | ExprResult Sub = Rebuild(CE->getSubExpr()); | ||||
17991 | if (!Sub.isUsable()) | ||||
17992 | return Sub; | ||||
17993 | return ConstantExpr::Create(S.Context, Sub.get()); | ||||
17994 | } | ||||
17995 | |||||
17996 | // We could mostly rely on the recursive rebuilding to rebuild implicit | ||||
17997 | // casts, but not at the top level, so rebuild them here. | ||||
17998 | case Expr::ImplicitCastExprClass: { | ||||
17999 | auto *ICE = cast<ImplicitCastExpr>(E); | ||||
18000 | // Only step through the narrow set of cast kinds we expect to encounter. | ||||
18001 | // Anything else suggests we've left the region in which potential results | ||||
18002 | // can be found. | ||||
18003 | switch (ICE->getCastKind()) { | ||||
18004 | case CK_NoOp: | ||||
18005 | case CK_DerivedToBase: | ||||
18006 | case CK_UncheckedDerivedToBase: { | ||||
18007 | ExprResult Sub = Rebuild(ICE->getSubExpr()); | ||||
18008 | if (!Sub.isUsable()) | ||||
18009 | return Sub; | ||||
18010 | CXXCastPath Path(ICE->path()); | ||||
18011 | return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), | ||||
18012 | ICE->getValueKind(), &Path); | ||||
18013 | } | ||||
18014 | |||||
18015 | default: | ||||
18016 | break; | ||||
18017 | } | ||||
18018 | break; | ||||
18019 | } | ||||
18020 | |||||
18021 | default: | ||||
18022 | break; | ||||
18023 | } | ||||
18024 | |||||
18025 | // Can't traverse through this node. Nothing to do. | ||||
18026 | return ExprEmpty(); | ||||
18027 | } | ||||
18028 | |||||
18029 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { | ||||
18030 | // Check whether the operand is or contains an object of non-trivial C union | ||||
18031 | // type. | ||||
18032 | if (E->getType().isVolatileQualified() && | ||||
18033 | (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
18034 | E->getType().hasNonTrivialToPrimitiveCopyCUnion())) | ||||
18035 | checkNonTrivialCUnion(E->getType(), E->getExprLoc(), | ||||
18036 | Sema::NTCUC_LValueToRValueVolatile, | ||||
18037 | NTCUK_Destruct|NTCUK_Copy); | ||||
18038 | |||||
18039 | // C++2a [basic.def.odr]p4: | ||||
18040 | // [...] an expression of non-volatile-qualified non-class type to which | ||||
18041 | // the lvalue-to-rvalue conversion is applied [...] | ||||
18042 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) | ||||
18043 | return E; | ||||
18044 | |||||
18045 | ExprResult Result = | ||||
18046 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); | ||||
18047 | if (Result.isInvalid()) | ||||
18048 | return ExprError(); | ||||
18049 | return Result.get() ? Result : E; | ||||
18050 | } | ||||
18051 | |||||
18052 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { | ||||
18053 | Res = CorrectDelayedTyposInExpr(Res); | ||||
18054 | |||||
18055 | if (!Res.isUsable()) | ||||
18056 | return Res; | ||||
18057 | |||||
18058 | // If a constant-expression is a reference to a variable where we delay | ||||
18059 | // deciding whether it is an odr-use, just assume we will apply the | ||||
18060 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen | ||||
18061 | // (a non-type template argument), we have special handling anyway. | ||||
18062 | return CheckLValueToRValueConversionOperand(Res.get()); | ||||
18063 | } | ||||
18064 | |||||
18065 | void Sema::CleanupVarDeclMarking() { | ||||
18066 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive | ||||
18067 | // call. | ||||
18068 | MaybeODRUseExprSet LocalMaybeODRUseExprs; | ||||
18069 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); | ||||
18070 | |||||
18071 | for (Expr *E : LocalMaybeODRUseExprs) { | ||||
18072 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
18073 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), | ||||
18074 | DRE->getLocation(), *this); | ||||
18075 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
18076 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), | ||||
18077 | *this); | ||||
18078 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { | ||||
18079 | for (VarDecl *VD : *FP) | ||||
18080 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); | ||||
18081 | } else { | ||||
18082 | llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18082); | ||||
18083 | } | ||||
18084 | } | ||||
18085 | |||||
18086 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18087, __PRETTY_FUNCTION__)) | ||||
18087 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18087, __PRETTY_FUNCTION__)); | ||||
18088 | } | ||||
18089 | |||||
18090 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
18091 | VarDecl *Var, Expr *E) { | ||||
18092 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18094, __PRETTY_FUNCTION__)) | ||||
18093 | isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18094, __PRETTY_FUNCTION__)) | ||||
18094 | "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E ) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18094, __PRETTY_FUNCTION__)); | ||||
18095 | Var->setReferenced(); | ||||
18096 | |||||
18097 | if (Var->isInvalidDecl()) | ||||
18098 | return; | ||||
18099 | |||||
18100 | // Record a CUDA/HIP static device/constant variable if it is referenced | ||||
18101 | // by host code. This is done conservatively, when the variable is referenced | ||||
18102 | // in any of the following contexts: | ||||
18103 | // - a non-function context | ||||
18104 | // - a host function | ||||
18105 | // - a host device function | ||||
18106 | // This also requires the reference of the static device/constant variable by | ||||
18107 | // host code to be visible in the device compilation for the compiler to be | ||||
18108 | // able to externalize the static device/constant variable. | ||||
18109 | if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { | ||||
18110 | auto *CurContext = SemaRef.CurContext; | ||||
18111 | if (!CurContext || !isa<FunctionDecl>(CurContext) || | ||||
18112 | cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || | ||||
18113 | (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && | ||||
18114 | !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) | ||||
18115 | SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); | ||||
18116 | } | ||||
18117 | |||||
18118 | auto *MSI = Var->getMemberSpecializationInfo(); | ||||
18119 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() | ||||
18120 | : Var->getTemplateSpecializationKind(); | ||||
18121 | |||||
18122 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); | ||||
18123 | bool UsableInConstantExpr = | ||||
18124 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); | ||||
18125 | |||||
18126 | // C++20 [expr.const]p12: | ||||
18127 | // A variable [...] is needed for constant evaluation if it is [...] a | ||||
18128 | // variable whose name appears as a potentially constant evaluated | ||||
18129 | // expression that is either a contexpr variable or is of non-volatile | ||||
18130 | // const-qualified integral type or of reference type | ||||
18131 | bool NeededForConstantEvaluation = | ||||
18132 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; | ||||
18133 | |||||
18134 | bool NeedDefinition = | ||||
18135 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; | ||||
18136 | |||||
18137 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18138, __PRETTY_FUNCTION__)) | ||||
18138 | "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) && "Can't instantiate a partial template specialization.") ? static_cast <void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18138, __PRETTY_FUNCTION__)); | ||||
18139 | |||||
18140 | // If this might be a member specialization of a static data member, check | ||||
18141 | // the specialization is visible. We already did the checks for variable | ||||
18142 | // template specializations when we created them. | ||||
18143 | if (NeedDefinition && TSK != TSK_Undeclared && | ||||
18144 | !isa<VarTemplateSpecializationDecl>(Var)) | ||||
18145 | SemaRef.checkSpecializationVisibility(Loc, Var); | ||||
18146 | |||||
18147 | // Perform implicit instantiation of static data members, static data member | ||||
18148 | // templates of class templates, and variable template specializations. Delay | ||||
18149 | // instantiations of variable templates, except for those that could be used | ||||
18150 | // in a constant expression. | ||||
18151 | if (NeedDefinition && isTemplateInstantiation(TSK)) { | ||||
18152 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit | ||||
18153 | // instantiation declaration if a variable is usable in a constant | ||||
18154 | // expression (among other cases). | ||||
18155 | bool TryInstantiating = | ||||
18156 | TSK == TSK_ImplicitInstantiation || | ||||
18157 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); | ||||
18158 | |||||
18159 | if (TryInstantiating) { | ||||
18160 | SourceLocation PointOfInstantiation = | ||||
18161 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); | ||||
18162 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); | ||||
18163 | if (FirstInstantiation) { | ||||
18164 | PointOfInstantiation = Loc; | ||||
18165 | if (MSI) | ||||
18166 | MSI->setPointOfInstantiation(PointOfInstantiation); | ||||
18167 | // FIXME: Notify listener. | ||||
18168 | else | ||||
18169 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); | ||||
18170 | } | ||||
18171 | |||||
18172 | if (UsableInConstantExpr) { | ||||
18173 | // Do not defer instantiations of variables that could be used in a | ||||
18174 | // constant expression. | ||||
18175 | SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
18176 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
18177 | }); | ||||
18178 | |||||
18179 | // Re-set the member to trigger a recomputation of the dependence bits | ||||
18180 | // for the expression. | ||||
18181 | if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18182 | DRE->setDecl(DRE->getDecl()); | ||||
18183 | else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18184 | ME->setMemberDecl(ME->getMemberDecl()); | ||||
18185 | } else if (FirstInstantiation || | ||||
18186 | isa<VarTemplateSpecializationDecl>(Var)) { | ||||
18187 | // FIXME: For a specialization of a variable template, we don't | ||||
18188 | // distinguish between "declaration and type implicitly instantiated" | ||||
18189 | // and "implicit instantiation of definition requested", so we have | ||||
18190 | // no direct way to avoid enqueueing the pending instantiation | ||||
18191 | // multiple times. | ||||
18192 | SemaRef.PendingInstantiations | ||||
18193 | .push_back(std::make_pair(Var, PointOfInstantiation)); | ||||
18194 | } | ||||
18195 | } | ||||
18196 | } | ||||
18197 | |||||
18198 | // C++2a [basic.def.odr]p4: | ||||
18199 | // A variable x whose name appears as a potentially-evaluated expression e | ||||
18200 | // is odr-used by e unless | ||||
18201 | // -- x is a reference that is usable in constant expressions | ||||
18202 | // -- x is a variable of non-reference type that is usable in constant | ||||
18203 | // expressions and has no mutable subobjects [FIXME], and e is an | ||||
18204 | // element of the set of potential results of an expression of | ||||
18205 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue | ||||
18206 | // conversion is applied | ||||
18207 | // -- x is a variable of non-reference type, and e is an element of the set | ||||
18208 | // of potential results of a discarded-value expression to which the | ||||
18209 | // lvalue-to-rvalue conversion is not applied [FIXME] | ||||
18210 | // | ||||
18211 | // We check the first part of the second bullet here, and | ||||
18212 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. | ||||
18213 | // FIXME: To get the third bullet right, we need to delay this even for | ||||
18214 | // variables that are not usable in constant expressions. | ||||
18215 | |||||
18216 | // If we already know this isn't an odr-use, there's nothing more to do. | ||||
18217 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) | ||||
18218 | if (DRE->isNonOdrUse()) | ||||
18219 | return; | ||||
18220 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) | ||||
18221 | if (ME->isNonOdrUse()) | ||||
18222 | return; | ||||
18223 | |||||
18224 | switch (OdrUse) { | ||||
18225 | case OdrUseContext::None: | ||||
18226 | assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18227, __PRETTY_FUNCTION__)) | ||||
18227 | "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref" ) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18227, __PRETTY_FUNCTION__)); | ||||
18228 | break; | ||||
18229 | |||||
18230 | case OdrUseContext::FormallyOdrUsed: | ||||
18231 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture | ||||
18232 | // behavior. | ||||
18233 | break; | ||||
18234 | |||||
18235 | case OdrUseContext::Used: | ||||
18236 | // If we might later find that this expression isn't actually an odr-use, | ||||
18237 | // delay the marking. | ||||
18238 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18239 | SemaRef.MaybeODRUseExprs.insert(E); | ||||
18240 | else | ||||
18241 | MarkVarDeclODRUsed(Var, Loc, SemaRef); | ||||
18242 | break; | ||||
18243 | |||||
18244 | case OdrUseContext::Dependent: | ||||
18245 | // If this is a dependent context, we don't need to mark variables as | ||||
18246 | // odr-used, but we may still need to track them for lambda capture. | ||||
18247 | // FIXME: Do we also need to do this inside dependent typeid expressions | ||||
18248 | // (which are modeled as unevaluated at this point)? | ||||
18249 | const bool RefersToEnclosingScope = | ||||
18250 | (SemaRef.CurContext != Var->getDeclContext() && | ||||
18251 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); | ||||
18252 | if (RefersToEnclosingScope) { | ||||
18253 | LambdaScopeInfo *const LSI = | ||||
18254 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); | ||||
18255 | if (LSI && (!LSI->CallOperator || | ||||
18256 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { | ||||
18257 | // If a variable could potentially be odr-used, defer marking it so | ||||
18258 | // until we finish analyzing the full expression for any | ||||
18259 | // lvalue-to-rvalue | ||||
18260 | // or discarded value conversions that would obviate odr-use. | ||||
18261 | // Add it to the list of potential captures that will be analyzed | ||||
18262 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking | ||||
18263 | // unless the variable is a reference that was initialized by a constant | ||||
18264 | // expression (this will never need to be captured or odr-used). | ||||
18265 | // | ||||
18266 | // FIXME: We can simplify this a lot after implementing P0588R1. | ||||
18267 | assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression." ) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18267, __PRETTY_FUNCTION__)); | ||||
18268 | if (!Var->getType()->isReferenceType() || | ||||
18269 | !Var->isUsableInConstantExpressions(SemaRef.Context)) | ||||
18270 | LSI->addPotentialCapture(E->IgnoreParens()); | ||||
18271 | } | ||||
18272 | } | ||||
18273 | break; | ||||
18274 | } | ||||
18275 | } | ||||
18276 | |||||
18277 | /// Mark a variable referenced, and check whether it is odr-used | ||||
18278 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be | ||||
18279 | /// used directly for normal expressions referring to VarDecl. | ||||
18280 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { | ||||
18281 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); | ||||
18282 | } | ||||
18283 | |||||
18284 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, | ||||
18285 | Decl *D, Expr *E, bool MightBeOdrUse) { | ||||
18286 | if (SemaRef.isInOpenMPDeclareTargetContext()) | ||||
18287 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); | ||||
18288 | |||||
18289 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { | ||||
18290 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); | ||||
18291 | return; | ||||
18292 | } | ||||
18293 | |||||
18294 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); | ||||
18295 | |||||
18296 | // If this is a call to a method via a cast, also mark the method in the | ||||
18297 | // derived class used in case codegen can devirtualize the call. | ||||
18298 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); | ||||
18299 | if (!ME) | ||||
18300 | return; | ||||
18301 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
18302 | if (!MD) | ||||
18303 | return; | ||||
18304 | // Only attempt to devirtualize if this is truly a virtual call. | ||||
18305 | bool IsVirtualCall = MD->isVirtual() && | ||||
18306 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); | ||||
18307 | if (!IsVirtualCall) | ||||
18308 | return; | ||||
18309 | |||||
18310 | // If it's possible to devirtualize the call, mark the called function | ||||
18311 | // referenced. | ||||
18312 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( | ||||
18313 | ME->getBase(), SemaRef.getLangOpts().AppleKext); | ||||
18314 | if (DM) | ||||
18315 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); | ||||
18316 | } | ||||
18317 | |||||
18318 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. | ||||
18319 | /// | ||||
18320 | /// Note, this may change the dependence of the DeclRefExpr, and so needs to be | ||||
18321 | /// handled with care if the DeclRefExpr is not newly-created. | ||||
18322 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { | ||||
18323 | // TODO: update this with DR# once a defect report is filed. | ||||
18324 | // C++11 defect. The address of a pure member should not be an ODR use, even | ||||
18325 | // if it's a qualified reference. | ||||
18326 | bool OdrUse = true; | ||||
18327 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) | ||||
18328 | if (Method->isVirtual() && | ||||
18329 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) | ||||
18330 | OdrUse = false; | ||||
18331 | |||||
18332 | if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
18333 | if (!isConstantEvaluated() && FD->isConsteval() && | ||||
18334 | !RebuildingImmediateInvocation) | ||||
18335 | ExprEvalContexts.back().ReferenceToConsteval.insert(E); | ||||
18336 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); | ||||
18337 | } | ||||
18338 | |||||
18339 | /// Perform reference-marking and odr-use handling for a MemberExpr. | ||||
18340 | void Sema::MarkMemberReferenced(MemberExpr *E) { | ||||
18341 | // C++11 [basic.def.odr]p2: | ||||
18342 | // A non-overloaded function whose name appears as a potentially-evaluated | ||||
18343 | // expression or a member of a set of candidate functions, if selected by | ||||
18344 | // overload resolution when referred to from a potentially-evaluated | ||||
18345 | // expression, is odr-used, unless it is a pure virtual function and its | ||||
18346 | // name is not explicitly qualified. | ||||
18347 | bool MightBeOdrUse = true; | ||||
18348 | if (E->performsVirtualDispatch(getLangOpts())) { | ||||
18349 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) | ||||
18350 | if (Method->isPure()) | ||||
18351 | MightBeOdrUse = false; | ||||
18352 | } | ||||
18353 | SourceLocation Loc = | ||||
18354 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); | ||||
18355 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); | ||||
18356 | } | ||||
18357 | |||||
18358 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. | ||||
18359 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { | ||||
18360 | for (VarDecl *VD : *E) | ||||
18361 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); | ||||
18362 | } | ||||
18363 | |||||
18364 | /// Perform marking for a reference to an arbitrary declaration. It | ||||
18365 | /// marks the declaration referenced, and performs odr-use checking for | ||||
18366 | /// functions and variables. This method should not be used when building a | ||||
18367 | /// normal expression which refers to a variable. | ||||
18368 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, | ||||
18369 | bool MightBeOdrUse) { | ||||
18370 | if (MightBeOdrUse) { | ||||
18371 | if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
18372 | MarkVariableReferenced(Loc, VD); | ||||
18373 | return; | ||||
18374 | } | ||||
18375 | } | ||||
18376 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
18377 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); | ||||
18378 | return; | ||||
18379 | } | ||||
18380 | D->setReferenced(); | ||||
18381 | } | ||||
18382 | |||||
18383 | namespace { | ||||
18384 | // Mark all of the declarations used by a type as referenced. | ||||
18385 | // FIXME: Not fully implemented yet! We need to have a better understanding | ||||
18386 | // of when we're entering a context we should not recurse into. | ||||
18387 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to | ||||
18388 | // TreeTransforms rebuilding the type in a new context. Rather than | ||||
18389 | // duplicating the TreeTransform logic, we should consider reusing it here. | ||||
18390 | // Currently that causes problems when rebuilding LambdaExprs. | ||||
18391 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { | ||||
18392 | Sema &S; | ||||
18393 | SourceLocation Loc; | ||||
18394 | |||||
18395 | public: | ||||
18396 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; | ||||
18397 | |||||
18398 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } | ||||
18399 | |||||
18400 | bool TraverseTemplateArgument(const TemplateArgument &Arg); | ||||
18401 | }; | ||||
18402 | } | ||||
18403 | |||||
18404 | bool MarkReferencedDecls::TraverseTemplateArgument( | ||||
18405 | const TemplateArgument &Arg) { | ||||
18406 | { | ||||
18407 | // A non-type template argument is a constant-evaluated context. | ||||
18408 | EnterExpressionEvaluationContext Evaluated( | ||||
18409 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
18410 | if (Arg.getKind() == TemplateArgument::Declaration) { | ||||
18411 | if (Decl *D = Arg.getAsDecl()) | ||||
18412 | S.MarkAnyDeclReferenced(Loc, D, true); | ||||
18413 | } else if (Arg.getKind() == TemplateArgument::Expression) { | ||||
18414 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); | ||||
18415 | } | ||||
18416 | } | ||||
18417 | |||||
18418 | return Inherited::TraverseTemplateArgument(Arg); | ||||
18419 | } | ||||
18420 | |||||
18421 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { | ||||
18422 | MarkReferencedDecls Marker(*this, Loc); | ||||
18423 | Marker.TraverseType(T); | ||||
18424 | } | ||||
18425 | |||||
18426 | namespace { | ||||
18427 | /// Helper class that marks all of the declarations referenced by | ||||
18428 | /// potentially-evaluated subexpressions as "referenced". | ||||
18429 | class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { | ||||
18430 | public: | ||||
18431 | typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; | ||||
18432 | bool SkipLocalVariables; | ||||
18433 | |||||
18434 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) | ||||
18435 | : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} | ||||
18436 | |||||
18437 | void visitUsedDecl(SourceLocation Loc, Decl *D) { | ||||
18438 | S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); | ||||
18439 | } | ||||
18440 | |||||
18441 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18442 | // If we were asked not to visit local variables, don't. | ||||
18443 | if (SkipLocalVariables) { | ||||
18444 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
18445 | if (VD->hasLocalStorage()) | ||||
18446 | return; | ||||
18447 | } | ||||
18448 | |||||
18449 | // FIXME: This can trigger the instantiation of the initializer of a | ||||
18450 | // variable, which can cause the expression to become value-dependent | ||||
18451 | // or error-dependent. Do we need to propagate the new dependence bits? | ||||
18452 | S.MarkDeclRefReferenced(E); | ||||
18453 | } | ||||
18454 | |||||
18455 | void VisitMemberExpr(MemberExpr *E) { | ||||
18456 | S.MarkMemberReferenced(E); | ||||
18457 | Visit(E->getBase()); | ||||
18458 | } | ||||
18459 | }; | ||||
18460 | } // namespace | ||||
18461 | |||||
18462 | /// Mark any declarations that appear within this expression or any | ||||
18463 | /// potentially-evaluated subexpressions as "referenced". | ||||
18464 | /// | ||||
18465 | /// \param SkipLocalVariables If true, don't mark local variables as | ||||
18466 | /// 'referenced'. | ||||
18467 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, | ||||
18468 | bool SkipLocalVariables) { | ||||
18469 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); | ||||
18470 | } | ||||
18471 | |||||
18472 | /// Emit a diagnostic that describes an effect on the run-time behavior | ||||
18473 | /// of the program being compiled. | ||||
18474 | /// | ||||
18475 | /// This routine emits the given diagnostic when the code currently being | ||||
18476 | /// type-checked is "potentially evaluated", meaning that there is a | ||||
18477 | /// possibility that the code will actually be executable. Code in sizeof() | ||||
18478 | /// expressions, code used only during overload resolution, etc., are not | ||||
18479 | /// potentially evaluated. This routine will suppress such diagnostics or, | ||||
18480 | /// in the absolutely nutty case of potentially potentially evaluated | ||||
18481 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it | ||||
18482 | /// later. | ||||
18483 | /// | ||||
18484 | /// This routine should be used for all diagnostics that describe the run-time | ||||
18485 | /// behavior of a program, such as passing a non-POD value through an ellipsis. | ||||
18486 | /// Failure to do so will likely result in spurious diagnostics or failures | ||||
18487 | /// during overload resolution or within sizeof/alignof/typeof/typeid. | ||||
18488 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | ||||
18489 | const PartialDiagnostic &PD) { | ||||
18490 | switch (ExprEvalContexts.back().Context) { | ||||
18491 | case ExpressionEvaluationContext::Unevaluated: | ||||
18492 | case ExpressionEvaluationContext::UnevaluatedList: | ||||
18493 | case ExpressionEvaluationContext::UnevaluatedAbstract: | ||||
18494 | case ExpressionEvaluationContext::DiscardedStatement: | ||||
18495 | // The argument will never be evaluated, so don't complain. | ||||
18496 | break; | ||||
18497 | |||||
18498 | case ExpressionEvaluationContext::ConstantEvaluated: | ||||
18499 | // Relevant diagnostics should be produced by constant evaluation. | ||||
18500 | break; | ||||
18501 | |||||
18502 | case ExpressionEvaluationContext::PotentiallyEvaluated: | ||||
18503 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: | ||||
18504 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { | ||||
18505 | FunctionScopes.back()->PossiblyUnreachableDiags. | ||||
18506 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); | ||||
18507 | return true; | ||||
18508 | } | ||||
18509 | |||||
18510 | // The initializer of a constexpr variable or of the first declaration of a | ||||
18511 | // static data member is not syntactically a constant evaluated constant, | ||||
18512 | // but nonetheless is always required to be a constant expression, so we | ||||
18513 | // can skip diagnosing. | ||||
18514 | // FIXME: Using the mangling context here is a hack. | ||||
18515 | if (auto *VD = dyn_cast_or_null<VarDecl>( | ||||
18516 | ExprEvalContexts.back().ManglingContextDecl)) { | ||||
18517 | if (VD->isConstexpr() || | ||||
18518 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) | ||||
18519 | break; | ||||
18520 | // FIXME: For any other kind of variable, we should build a CFG for its | ||||
18521 | // initializer and check whether the context in question is reachable. | ||||
18522 | } | ||||
18523 | |||||
18524 | Diag(Loc, PD); | ||||
18525 | return true; | ||||
18526 | } | ||||
18527 | |||||
18528 | return false; | ||||
18529 | } | ||||
18530 | |||||
18531 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | ||||
18532 | const PartialDiagnostic &PD) { | ||||
18533 | return DiagRuntimeBehavior( | ||||
18534 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); | ||||
18535 | } | ||||
18536 | |||||
18537 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | ||||
18538 | CallExpr *CE, FunctionDecl *FD) { | ||||
18539 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) | ||||
18540 | return false; | ||||
18541 | |||||
18542 | // If we're inside a decltype's expression, don't check for a valid return | ||||
18543 | // type or construct temporaries until we know whether this is the last call. | ||||
18544 | if (ExprEvalContexts.back().ExprContext == | ||||
18545 | ExpressionEvaluationContextRecord::EK_Decltype) { | ||||
18546 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); | ||||
18547 | return false; | ||||
18548 | } | ||||
18549 | |||||
18550 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { | ||||
18551 | FunctionDecl *FD; | ||||
18552 | CallExpr *CE; | ||||
18553 | |||||
18554 | public: | ||||
18555 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) | ||||
18556 | : FD(FD), CE(CE) { } | ||||
18557 | |||||
18558 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | ||||
18559 | if (!FD) { | ||||
18560 | S.Diag(Loc, diag::err_call_incomplete_return) | ||||
18561 | << T << CE->getSourceRange(); | ||||
18562 | return; | ||||
18563 | } | ||||
18564 | |||||
18565 | S.Diag(Loc, diag::err_call_function_incomplete_return) | ||||
18566 | << CE->getSourceRange() << FD << T; | ||||
18567 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) | ||||
18568 | << FD->getDeclName(); | ||||
18569 | } | ||||
18570 | } Diagnoser(FD, CE); | ||||
18571 | |||||
18572 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) | ||||
18573 | return true; | ||||
18574 | |||||
18575 | return false; | ||||
18576 | } | ||||
18577 | |||||
18578 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses | ||||
18579 | // will prevent this condition from triggering, which is what we want. | ||||
18580 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { | ||||
18581 | SourceLocation Loc; | ||||
18582 | |||||
18583 | unsigned diagnostic = diag::warn_condition_is_assignment; | ||||
18584 | bool IsOrAssign = false; | ||||
18585 | |||||
18586 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { | ||||
18587 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) | ||||
18588 | return; | ||||
18589 | |||||
18590 | IsOrAssign = Op->getOpcode() == BO_OrAssign; | ||||
18591 | |||||
18592 | // Greylist some idioms by putting them into a warning subcategory. | ||||
18593 | if (ObjCMessageExpr *ME | ||||
18594 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { | ||||
18595 | Selector Sel = ME->getSelector(); | ||||
18596 | |||||
18597 | // self = [<foo> init...] | ||||
18598 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) | ||||
18599 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
18600 | |||||
18601 | // <foo> = [<bar> nextObject] | ||||
18602 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") | ||||
18603 | diagnostic = diag::warn_condition_is_idiomatic_assignment; | ||||
18604 | } | ||||
18605 | |||||
18606 | Loc = Op->getOperatorLoc(); | ||||
18607 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { | ||||
18608 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) | ||||
18609 | return; | ||||
18610 | |||||
18611 | IsOrAssign = Op->getOperator() == OO_PipeEqual; | ||||
18612 | Loc = Op->getOperatorLoc(); | ||||
18613 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) | ||||
18614 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); | ||||
18615 | else { | ||||
18616 | // Not an assignment. | ||||
18617 | return; | ||||
18618 | } | ||||
18619 | |||||
18620 | Diag(Loc, diagnostic) << E->getSourceRange(); | ||||
18621 | |||||
18622 | SourceLocation Open = E->getBeginLoc(); | ||||
18623 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); | ||||
18624 | Diag(Loc, diag::note_condition_assign_silence) | ||||
18625 | << FixItHint::CreateInsertion(Open, "(") | ||||
18626 | << FixItHint::CreateInsertion(Close, ")"); | ||||
18627 | |||||
18628 | if (IsOrAssign) | ||||
18629 | Diag(Loc, diag::note_condition_or_assign_to_comparison) | ||||
18630 | << FixItHint::CreateReplacement(Loc, "!="); | ||||
18631 | else | ||||
18632 | Diag(Loc, diag::note_condition_assign_to_comparison) | ||||
18633 | << FixItHint::CreateReplacement(Loc, "=="); | ||||
18634 | } | ||||
18635 | |||||
18636 | /// Redundant parentheses over an equality comparison can indicate | ||||
18637 | /// that the user intended an assignment used as condition. | ||||
18638 | void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { | ||||
18639 | // Don't warn if the parens came from a macro. | ||||
18640 | SourceLocation parenLoc = ParenE->getBeginLoc(); | ||||
18641 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) | ||||
18642 | return; | ||||
18643 | // Don't warn for dependent expressions. | ||||
18644 | if (ParenE->isTypeDependent()) | ||||
18645 | return; | ||||
18646 | |||||
18647 | Expr *E = ParenE->IgnoreParens(); | ||||
18648 | |||||
18649 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) | ||||
18650 | if (opE->getOpcode() == BO_EQ && | ||||
18651 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) | ||||
18652 | == Expr::MLV_Valid) { | ||||
18653 | SourceLocation Loc = opE->getOperatorLoc(); | ||||
18654 | |||||
18655 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); | ||||
18656 | SourceRange ParenERange = ParenE->getSourceRange(); | ||||
18657 | Diag(Loc, diag::note_equality_comparison_silence) | ||||
18658 | << FixItHint::CreateRemoval(ParenERange.getBegin()) | ||||
18659 | << FixItHint::CreateRemoval(ParenERange.getEnd()); | ||||
18660 | Diag(Loc, diag::note_equality_comparison_to_assign) | ||||
18661 | << FixItHint::CreateReplacement(Loc, "="); | ||||
18662 | } | ||||
18663 | } | ||||
18664 | |||||
18665 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, | ||||
18666 | bool IsConstexpr) { | ||||
18667 | DiagnoseAssignmentAsCondition(E); | ||||
18668 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) | ||||
18669 | DiagnoseEqualityWithExtraParens(parenE); | ||||
18670 | |||||
18671 | ExprResult result = CheckPlaceholderExpr(E); | ||||
18672 | if (result.isInvalid()) return ExprError(); | ||||
18673 | E = result.get(); | ||||
18674 | |||||
18675 | if (!E->isTypeDependent()) { | ||||
18676 | if (getLangOpts().CPlusPlus) | ||||
18677 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 | ||||
18678 | |||||
18679 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); | ||||
18680 | if (ERes.isInvalid()) | ||||
18681 | return ExprError(); | ||||
18682 | E = ERes.get(); | ||||
18683 | |||||
18684 | QualType T = E->getType(); | ||||
18685 | if (!T->isScalarType()) { // C99 6.8.4.1p1 | ||||
18686 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) | ||||
18687 | << T << E->getSourceRange(); | ||||
18688 | return ExprError(); | ||||
18689 | } | ||||
18690 | CheckBoolLikeConversion(E, Loc); | ||||
18691 | } | ||||
18692 | |||||
18693 | return E; | ||||
18694 | } | ||||
18695 | |||||
18696 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, | ||||
18697 | Expr *SubExpr, ConditionKind CK) { | ||||
18698 | // Empty conditions are valid in for-statements. | ||||
18699 | if (!SubExpr) | ||||
18700 | return ConditionResult(); | ||||
18701 | |||||
18702 | ExprResult Cond; | ||||
18703 | switch (CK) { | ||||
18704 | case ConditionKind::Boolean: | ||||
18705 | Cond = CheckBooleanCondition(Loc, SubExpr); | ||||
18706 | break; | ||||
18707 | |||||
18708 | case ConditionKind::ConstexprIf: | ||||
18709 | Cond = CheckBooleanCondition(Loc, SubExpr, true); | ||||
18710 | break; | ||||
18711 | |||||
18712 | case ConditionKind::Switch: | ||||
18713 | Cond = CheckSwitchCondition(Loc, SubExpr); | ||||
18714 | break; | ||||
18715 | } | ||||
18716 | if (Cond.isInvalid()) { | ||||
18717 | Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), | ||||
18718 | {SubExpr}); | ||||
18719 | if (!Cond.get()) | ||||
18720 | return ConditionError(); | ||||
18721 | } | ||||
18722 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. | ||||
18723 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); | ||||
18724 | if (!FullExpr.get()) | ||||
18725 | return ConditionError(); | ||||
18726 | |||||
18727 | return ConditionResult(*this, nullptr, FullExpr, | ||||
18728 | CK == ConditionKind::ConstexprIf); | ||||
18729 | } | ||||
18730 | |||||
18731 | namespace { | ||||
18732 | /// A visitor for rebuilding a call to an __unknown_any expression | ||||
18733 | /// to have an appropriate type. | ||||
18734 | struct RebuildUnknownAnyFunction | ||||
18735 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { | ||||
18736 | |||||
18737 | Sema &S; | ||||
18738 | |||||
18739 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} | ||||
18740 | |||||
18741 | ExprResult VisitStmt(Stmt *S) { | ||||
18742 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18742); | ||||
18743 | } | ||||
18744 | |||||
18745 | ExprResult VisitExpr(Expr *E) { | ||||
18746 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) | ||||
18747 | << E->getSourceRange(); | ||||
18748 | return ExprError(); | ||||
18749 | } | ||||
18750 | |||||
18751 | /// Rebuild an expression which simply semantically wraps another | ||||
18752 | /// expression which it shares the type and value kind of. | ||||
18753 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
18754 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18755 | if (SubResult.isInvalid()) return ExprError(); | ||||
18756 | |||||
18757 | Expr *SubExpr = SubResult.get(); | ||||
18758 | E->setSubExpr(SubExpr); | ||||
18759 | E->setType(SubExpr->getType()); | ||||
18760 | E->setValueKind(SubExpr->getValueKind()); | ||||
18761 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18761, __PRETTY_FUNCTION__)); | ||||
18762 | return E; | ||||
18763 | } | ||||
18764 | |||||
18765 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
18766 | return rebuildSugarExpr(E); | ||||
18767 | } | ||||
18768 | |||||
18769 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
18770 | return rebuildSugarExpr(E); | ||||
18771 | } | ||||
18772 | |||||
18773 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
18774 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18775 | if (SubResult.isInvalid()) return ExprError(); | ||||
18776 | |||||
18777 | Expr *SubExpr = SubResult.get(); | ||||
18778 | E->setSubExpr(SubExpr); | ||||
18779 | E->setType(S.Context.getPointerType(SubExpr->getType())); | ||||
18780 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18780, __PRETTY_FUNCTION__)); | ||||
18781 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18781, __PRETTY_FUNCTION__)); | ||||
18782 | return E; | ||||
18783 | } | ||||
18784 | |||||
18785 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { | ||||
18786 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); | ||||
18787 | |||||
18788 | E->setType(VD->getType()); | ||||
18789 | |||||
18790 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18790, __PRETTY_FUNCTION__)); | ||||
18791 | if (S.getLangOpts().CPlusPlus && | ||||
18792 | !(isa<CXXMethodDecl>(VD) && | ||||
18793 | cast<CXXMethodDecl>(VD)->isInstance())) | ||||
18794 | E->setValueKind(VK_LValue); | ||||
18795 | |||||
18796 | return E; | ||||
18797 | } | ||||
18798 | |||||
18799 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
18800 | return resolveDecl(E, E->getMemberDecl()); | ||||
18801 | } | ||||
18802 | |||||
18803 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18804 | return resolveDecl(E, E->getDecl()); | ||||
18805 | } | ||||
18806 | }; | ||||
18807 | } | ||||
18808 | |||||
18809 | /// Given a function expression of unknown-any type, try to rebuild it | ||||
18810 | /// to have a function type. | ||||
18811 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { | ||||
18812 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); | ||||
18813 | if (Result.isInvalid()) return ExprError(); | ||||
18814 | return S.DefaultFunctionArrayConversion(Result.get()); | ||||
18815 | } | ||||
18816 | |||||
18817 | namespace { | ||||
18818 | /// A visitor for rebuilding an expression of type __unknown_anytype | ||||
18819 | /// into one which resolves the type directly on the referring | ||||
18820 | /// expression. Strict preservation of the original source | ||||
18821 | /// structure is not a goal. | ||||
18822 | struct RebuildUnknownAnyExpr | ||||
18823 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { | ||||
18824 | |||||
18825 | Sema &S; | ||||
18826 | |||||
18827 | /// The current destination type. | ||||
18828 | QualType DestType; | ||||
18829 | |||||
18830 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) | ||||
18831 | : S(S), DestType(CastType) {} | ||||
18832 | |||||
18833 | ExprResult VisitStmt(Stmt *S) { | ||||
18834 | llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18834); | ||||
18835 | } | ||||
18836 | |||||
18837 | ExprResult VisitExpr(Expr *E) { | ||||
18838 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
18839 | << E->getSourceRange(); | ||||
18840 | return ExprError(); | ||||
18841 | } | ||||
18842 | |||||
18843 | ExprResult VisitCallExpr(CallExpr *E); | ||||
18844 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); | ||||
18845 | |||||
18846 | /// Rebuild an expression which simply semantically wraps another | ||||
18847 | /// expression which it shares the type and value kind of. | ||||
18848 | template <class T> ExprResult rebuildSugarExpr(T *E) { | ||||
18849 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18850 | if (SubResult.isInvalid()) return ExprError(); | ||||
18851 | Expr *SubExpr = SubResult.get(); | ||||
18852 | E->setSubExpr(SubExpr); | ||||
18853 | E->setType(SubExpr->getType()); | ||||
18854 | E->setValueKind(SubExpr->getValueKind()); | ||||
18855 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18855, __PRETTY_FUNCTION__)); | ||||
18856 | return E; | ||||
18857 | } | ||||
18858 | |||||
18859 | ExprResult VisitParenExpr(ParenExpr *E) { | ||||
18860 | return rebuildSugarExpr(E); | ||||
18861 | } | ||||
18862 | |||||
18863 | ExprResult VisitUnaryExtension(UnaryOperator *E) { | ||||
18864 | return rebuildSugarExpr(E); | ||||
18865 | } | ||||
18866 | |||||
18867 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { | ||||
18868 | const PointerType *Ptr = DestType->getAs<PointerType>(); | ||||
18869 | if (!Ptr) { | ||||
18870 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) | ||||
18871 | << E->getSourceRange(); | ||||
18872 | return ExprError(); | ||||
18873 | } | ||||
18874 | |||||
18875 | if (isa<CallExpr>(E->getSubExpr())) { | ||||
18876 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) | ||||
18877 | << E->getSourceRange(); | ||||
18878 | return ExprError(); | ||||
18879 | } | ||||
18880 | |||||
18881 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18881, __PRETTY_FUNCTION__)); | ||||
18882 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18882, __PRETTY_FUNCTION__)); | ||||
18883 | E->setType(DestType); | ||||
18884 | |||||
18885 | // Build the sub-expression as if it were an object of the pointee type. | ||||
18886 | DestType = Ptr->getPointeeType(); | ||||
18887 | ExprResult SubResult = Visit(E->getSubExpr()); | ||||
18888 | if (SubResult.isInvalid()) return ExprError(); | ||||
18889 | E->setSubExpr(SubResult.get()); | ||||
18890 | return E; | ||||
18891 | } | ||||
18892 | |||||
18893 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); | ||||
18894 | |||||
18895 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); | ||||
18896 | |||||
18897 | ExprResult VisitMemberExpr(MemberExpr *E) { | ||||
18898 | return resolveDecl(E, E->getMemberDecl()); | ||||
18899 | } | ||||
18900 | |||||
18901 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { | ||||
18902 | return resolveDecl(E, E->getDecl()); | ||||
18903 | } | ||||
18904 | }; | ||||
18905 | } | ||||
18906 | |||||
18907 | /// Rebuilds a call expression which yielded __unknown_anytype. | ||||
18908 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { | ||||
18909 | Expr *CalleeExpr = E->getCallee(); | ||||
18910 | |||||
18911 | enum FnKind { | ||||
18912 | FK_MemberFunction, | ||||
18913 | FK_FunctionPointer, | ||||
18914 | FK_BlockPointer | ||||
18915 | }; | ||||
18916 | |||||
18917 | FnKind Kind; | ||||
18918 | QualType CalleeType = CalleeExpr->getType(); | ||||
18919 | if (CalleeType == S.Context.BoundMemberTy) { | ||||
18920 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr >(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18920, __PRETTY_FUNCTION__)); | ||||
18921 | Kind = FK_MemberFunction; | ||||
18922 | CalleeType = Expr::findBoundMemberType(CalleeExpr); | ||||
18923 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { | ||||
18924 | CalleeType = Ptr->getPointeeType(); | ||||
18925 | Kind = FK_FunctionPointer; | ||||
18926 | } else { | ||||
18927 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); | ||||
18928 | Kind = FK_BlockPointer; | ||||
18929 | } | ||||
18930 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); | ||||
18931 | |||||
18932 | // Verify that this is a legal result type of a function. | ||||
18933 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
18934 | unsigned diagID = diag::err_func_returning_array_function; | ||||
18935 | if (Kind == FK_BlockPointer) | ||||
18936 | diagID = diag::err_block_returning_array_function; | ||||
18937 | |||||
18938 | S.Diag(E->getExprLoc(), diagID) | ||||
18939 | << DestType->isFunctionType() << DestType; | ||||
18940 | return ExprError(); | ||||
18941 | } | ||||
18942 | |||||
18943 | // Otherwise, go ahead and set DestType as the call's result. | ||||
18944 | E->setType(DestType.getNonLValueExprType(S.Context)); | ||||
18945 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
18946 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 18946, __PRETTY_FUNCTION__)); | ||||
18947 | |||||
18948 | // Rebuild the function type, replacing the result type with DestType. | ||||
18949 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); | ||||
18950 | if (Proto) { | ||||
18951 | // __unknown_anytype(...) is a special case used by the debugger when | ||||
18952 | // it has no idea what a function's signature is. | ||||
18953 | // | ||||
18954 | // We want to build this call essentially under the K&R | ||||
18955 | // unprototyped rules, but making a FunctionNoProtoType in C++ | ||||
18956 | // would foul up all sorts of assumptions. However, we cannot | ||||
18957 | // simply pass all arguments as variadic arguments, nor can we | ||||
18958 | // portably just call the function under a non-variadic type; see | ||||
18959 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. | ||||
18960 | // However, it turns out that in practice it is generally safe to | ||||
18961 | // call a function declared as "A foo(B,C,D);" under the prototype | ||||
18962 | // "A foo(B,C,D,...);". The only known exception is with the | ||||
18963 | // Windows ABI, where any variadic function is implicitly cdecl | ||||
18964 | // regardless of its normal CC. Therefore we change the parameter | ||||
18965 | // types to match the types of the arguments. | ||||
18966 | // | ||||
18967 | // This is a hack, but it is far superior to moving the | ||||
18968 | // corresponding target-specific code from IR-gen to Sema/AST. | ||||
18969 | |||||
18970 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); | ||||
18971 | SmallVector<QualType, 8> ArgTypes; | ||||
18972 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case | ||||
18973 | ArgTypes.reserve(E->getNumArgs()); | ||||
18974 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { | ||||
18975 | Expr *Arg = E->getArg(i); | ||||
18976 | QualType ArgType = Arg->getType(); | ||||
18977 | if (E->isLValue()) { | ||||
18978 | ArgType = S.Context.getLValueReferenceType(ArgType); | ||||
18979 | } else if (E->isXValue()) { | ||||
18980 | ArgType = S.Context.getRValueReferenceType(ArgType); | ||||
18981 | } | ||||
18982 | ArgTypes.push_back(ArgType); | ||||
18983 | } | ||||
18984 | ParamTypes = ArgTypes; | ||||
18985 | } | ||||
18986 | DestType = S.Context.getFunctionType(DestType, ParamTypes, | ||||
18987 | Proto->getExtProtoInfo()); | ||||
18988 | } else { | ||||
18989 | DestType = S.Context.getFunctionNoProtoType(DestType, | ||||
18990 | FnType->getExtInfo()); | ||||
18991 | } | ||||
18992 | |||||
18993 | // Rebuild the appropriate pointer-to-function type. | ||||
18994 | switch (Kind) { | ||||
18995 | case FK_MemberFunction: | ||||
18996 | // Nothing to do. | ||||
18997 | break; | ||||
18998 | |||||
18999 | case FK_FunctionPointer: | ||||
19000 | DestType = S.Context.getPointerType(DestType); | ||||
19001 | break; | ||||
19002 | |||||
19003 | case FK_BlockPointer: | ||||
19004 | DestType = S.Context.getBlockPointerType(DestType); | ||||
19005 | break; | ||||
19006 | } | ||||
19007 | |||||
19008 | // Finally, we can recurse. | ||||
19009 | ExprResult CalleeResult = Visit(CalleeExpr); | ||||
19010 | if (!CalleeResult.isUsable()) return ExprError(); | ||||
19011 | E->setCallee(CalleeResult.get()); | ||||
19012 | |||||
19013 | // Bind a temporary if necessary. | ||||
19014 | return S.MaybeBindToTemporary(E); | ||||
19015 | } | ||||
19016 | |||||
19017 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { | ||||
19018 | // Verify that this is a legal result type of a call. | ||||
19019 | if (DestType->isArrayType() || DestType->isFunctionType()) { | ||||
19020 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) | ||||
19021 | << DestType->isFunctionType() << DestType; | ||||
19022 | return ExprError(); | ||||
19023 | } | ||||
19024 | |||||
19025 | // Rewrite the method result type if available. | ||||
19026 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { | ||||
19027 | assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast <void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19027, __PRETTY_FUNCTION__)); | ||||
19028 | Method->setReturnType(DestType); | ||||
19029 | } | ||||
19030 | |||||
19031 | // Change the type of the message. | ||||
19032 | E->setType(DestType.getNonReferenceType()); | ||||
19033 | E->setValueKind(Expr::getValueKindForType(DestType)); | ||||
19034 | |||||
19035 | return S.MaybeBindToTemporary(E); | ||||
19036 | } | ||||
19037 | |||||
19038 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
19039 | // The only case we should ever see here is a function-to-pointer decay. | ||||
19040 | if (E->getCastKind() == CK_FunctionToPointerDecay) { | ||||
19041 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19041, __PRETTY_FUNCTION__)); | ||||
19042 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19042, __PRETTY_FUNCTION__)); | ||||
19043 | |||||
19044 | E->setType(DestType); | ||||
19045 | |||||
19046 | // Rebuild the sub-expression as the pointee (function) type. | ||||
19047 | DestType = DestType->castAs<PointerType>()->getPointeeType(); | ||||
19048 | |||||
19049 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19050 | if (!Result.isUsable()) return ExprError(); | ||||
19051 | |||||
19052 | E->setSubExpr(Result.get()); | ||||
19053 | return E; | ||||
19054 | } else if (E->getCastKind() == CK_LValueToRValue) { | ||||
19055 | assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void> (0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19055, __PRETTY_FUNCTION__)); | ||||
19056 | assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void > (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19056, __PRETTY_FUNCTION__)); | ||||
19057 | |||||
19058 | assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast <void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19058, __PRETTY_FUNCTION__)); | ||||
19059 | |||||
19060 | E->setType(DestType); | ||||
19061 | |||||
19062 | // The sub-expression has to be a lvalue reference, so rebuild it as such. | ||||
19063 | DestType = S.Context.getLValueReferenceType(DestType); | ||||
19064 | |||||
19065 | ExprResult Result = Visit(E->getSubExpr()); | ||||
19066 | if (!Result.isUsable()) return ExprError(); | ||||
19067 | |||||
19068 | E->setSubExpr(Result.get()); | ||||
19069 | return E; | ||||
19070 | } else { | ||||
19071 | llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19071); | ||||
19072 | } | ||||
19073 | } | ||||
19074 | |||||
19075 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { | ||||
19076 | ExprValueKind ValueKind = VK_LValue; | ||||
19077 | QualType Type = DestType; | ||||
19078 | |||||
19079 | // We know how to make this work for certain kinds of decls: | ||||
19080 | |||||
19081 | // - functions | ||||
19082 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { | ||||
19083 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { | ||||
19084 | DestType = Ptr->getPointeeType(); | ||||
19085 | ExprResult Result = resolveDecl(E, VD); | ||||
19086 | if (Result.isInvalid()) return ExprError(); | ||||
19087 | return S.ImpCastExprToType(Result.get(), Type, | ||||
19088 | CK_FunctionToPointerDecay, VK_RValue); | ||||
19089 | } | ||||
19090 | |||||
19091 | if (!Type->isFunctionType()) { | ||||
19092 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) | ||||
19093 | << VD << E->getSourceRange(); | ||||
19094 | return ExprError(); | ||||
19095 | } | ||||
19096 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { | ||||
19097 | // We must match the FunctionDecl's type to the hack introduced in | ||||
19098 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown | ||||
19099 | // type. See the lengthy commentary in that routine. | ||||
19100 | QualType FDT = FD->getType(); | ||||
19101 | const FunctionType *FnType = FDT->castAs<FunctionType>(); | ||||
19102 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); | ||||
19103 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); | ||||
19104 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { | ||||
19105 | SourceLocation Loc = FD->getLocation(); | ||||
19106 | FunctionDecl *NewFD = FunctionDecl::Create( | ||||
19107 | S.Context, FD->getDeclContext(), Loc, Loc, | ||||
19108 | FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), | ||||
19109 | SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), | ||||
19110 | /*ConstexprKind*/ ConstexprSpecKind::Unspecified); | ||||
19111 | |||||
19112 | if (FD->getQualifier()) | ||||
19113 | NewFD->setQualifierInfo(FD->getQualifierLoc()); | ||||
19114 | |||||
19115 | SmallVector<ParmVarDecl*, 16> Params; | ||||
19116 | for (const auto &AI : FT->param_types()) { | ||||
19117 | ParmVarDecl *Param = | ||||
19118 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); | ||||
19119 | Param->setScopeInfo(0, Params.size()); | ||||
19120 | Params.push_back(Param); | ||||
19121 | } | ||||
19122 | NewFD->setParams(Params); | ||||
19123 | DRE->setDecl(NewFD); | ||||
19124 | VD = DRE->getDecl(); | ||||
19125 | } | ||||
19126 | } | ||||
19127 | |||||
19128 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) | ||||
19129 | if (MD->isInstance()) { | ||||
19130 | ValueKind = VK_RValue; | ||||
19131 | Type = S.Context.BoundMemberTy; | ||||
19132 | } | ||||
19133 | |||||
19134 | // Function references aren't l-values in C. | ||||
19135 | if (!S.getLangOpts().CPlusPlus) | ||||
19136 | ValueKind = VK_RValue; | ||||
19137 | |||||
19138 | // - variables | ||||
19139 | } else if (isa<VarDecl>(VD)) { | ||||
19140 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { | ||||
19141 | Type = RefTy->getPointeeType(); | ||||
19142 | } else if (Type->isFunctionType()) { | ||||
19143 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) | ||||
19144 | << VD << E->getSourceRange(); | ||||
19145 | return ExprError(); | ||||
19146 | } | ||||
19147 | |||||
19148 | // - nothing else | ||||
19149 | } else { | ||||
19150 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) | ||||
19151 | << VD << E->getSourceRange(); | ||||
19152 | return ExprError(); | ||||
19153 | } | ||||
19154 | |||||
19155 | // Modifying the declaration like this is friendly to IR-gen but | ||||
19156 | // also really dangerous. | ||||
19157 | VD->setType(DestType); | ||||
19158 | E->setType(Type); | ||||
19159 | E->setValueKind(ValueKind); | ||||
19160 | return E; | ||||
19161 | } | ||||
19162 | |||||
19163 | /// Check a cast of an unknown-any type. We intentionally only | ||||
19164 | /// trigger this for C-style casts. | ||||
19165 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | ||||
19166 | Expr *CastExpr, CastKind &CastKind, | ||||
19167 | ExprValueKind &VK, CXXCastPath &Path) { | ||||
19168 | // The type we're casting to must be either void or complete. | ||||
19169 | if (!CastType->isVoidType() && | ||||
19170 | RequireCompleteType(TypeRange.getBegin(), CastType, | ||||
19171 | diag::err_typecheck_cast_to_incomplete)) | ||||
19172 | return ExprError(); | ||||
19173 | |||||
19174 | // Rewrite the casted expression from scratch. | ||||
19175 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); | ||||
19176 | if (!result.isUsable()) return ExprError(); | ||||
19177 | |||||
19178 | CastExpr = result.get(); | ||||
19179 | VK = CastExpr->getValueKind(); | ||||
19180 | CastKind = CK_NoOp; | ||||
19181 | |||||
19182 | return CastExpr; | ||||
19183 | } | ||||
19184 | |||||
19185 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { | ||||
19186 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); | ||||
19187 | } | ||||
19188 | |||||
19189 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, | ||||
19190 | Expr *arg, QualType ¶mType) { | ||||
19191 | // If the syntactic form of the argument is not an explicit cast of | ||||
19192 | // any sort, just do default argument promotion. | ||||
19193 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); | ||||
19194 | if (!castArg) { | ||||
19195 | ExprResult result = DefaultArgumentPromotion(arg); | ||||
19196 | if (result.isInvalid()) return ExprError(); | ||||
19197 | paramType = result.get()->getType(); | ||||
19198 | return result; | ||||
19199 | } | ||||
19200 | |||||
19201 | // Otherwise, use the type that was written in the explicit cast. | ||||
19202 | assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0 ) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19202, __PRETTY_FUNCTION__)); | ||||
19203 | paramType = castArg->getTypeAsWritten(); | ||||
19204 | |||||
19205 | // Copy-initialize a parameter of that type. | ||||
19206 | InitializedEntity entity = | ||||
19207 | InitializedEntity::InitializeParameter(Context, paramType, | ||||
19208 | /*consumed*/ false); | ||||
19209 | return PerformCopyInitialization(entity, callLoc, arg); | ||||
19210 | } | ||||
19211 | |||||
19212 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { | ||||
19213 | Expr *orig = E; | ||||
19214 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; | ||||
19215 | while (true) { | ||||
19216 | E = E->IgnoreParenImpCasts(); | ||||
19217 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { | ||||
19218 | E = call->getCallee(); | ||||
19219 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19220 | } else { | ||||
19221 | break; | ||||
19222 | } | ||||
19223 | } | ||||
19224 | |||||
19225 | SourceLocation loc; | ||||
19226 | NamedDecl *d; | ||||
19227 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { | ||||
19228 | loc = ref->getLocation(); | ||||
19229 | d = ref->getDecl(); | ||||
19230 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { | ||||
19231 | loc = mem->getMemberLoc(); | ||||
19232 | d = mem->getMemberDecl(); | ||||
19233 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { | ||||
19234 | diagID = diag::err_uncasted_call_of_unknown_any; | ||||
19235 | loc = msg->getSelectorStartLoc(); | ||||
19236 | d = msg->getMethodDecl(); | ||||
19237 | if (!d) { | ||||
19238 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) | ||||
19239 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() | ||||
19240 | << orig->getSourceRange(); | ||||
19241 | return ExprError(); | ||||
19242 | } | ||||
19243 | } else { | ||||
19244 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) | ||||
19245 | << E->getSourceRange(); | ||||
19246 | return ExprError(); | ||||
19247 | } | ||||
19248 | |||||
19249 | S.Diag(loc, diagID) << d << orig->getSourceRange(); | ||||
19250 | |||||
19251 | // Never recoverable. | ||||
19252 | return ExprError(); | ||||
19253 | } | ||||
19254 | |||||
19255 | /// Check for operands with placeholder types and complain if found. | ||||
19256 | /// Returns ExprError() if there was an error and no recovery was possible. | ||||
19257 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { | ||||
19258 | if (!Context.isDependenceAllowed()) { | ||||
19259 | // C cannot handle TypoExpr nodes on either side of a binop because it | ||||
19260 | // doesn't handle dependent types properly, so make sure any TypoExprs have | ||||
19261 | // been dealt with before checking the operands. | ||||
19262 | ExprResult Result = CorrectDelayedTyposInExpr(E); | ||||
19263 | if (!Result.isUsable()) return ExprError(); | ||||
19264 | E = Result.get(); | ||||
19265 | } | ||||
19266 | |||||
19267 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); | ||||
19268 | if (!placeholderType) return E; | ||||
19269 | |||||
19270 | switch (placeholderType->getKind()) { | ||||
19271 | |||||
19272 | // Overloaded expressions. | ||||
19273 | case BuiltinType::Overload: { | ||||
19274 | // Try to resolve a single function template specialization. | ||||
19275 | // This is obligatory. | ||||
19276 | ExprResult Result = E; | ||||
19277 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) | ||||
19278 | return Result; | ||||
19279 | |||||
19280 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
19281 | // leaves Result unchanged on failure. | ||||
19282 | Result = E; | ||||
19283 | if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) | ||||
19284 | return Result; | ||||
19285 | |||||
19286 | // If that failed, try to recover with a call. | ||||
19287 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), | ||||
19288 | /*complain*/ true); | ||||
19289 | return Result; | ||||
19290 | } | ||||
19291 | |||||
19292 | // Bound member functions. | ||||
19293 | case BuiltinType::BoundMember: { | ||||
19294 | ExprResult result = E; | ||||
19295 | const Expr *BME = E->IgnoreParens(); | ||||
19296 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); | ||||
19297 | // Try to give a nicer diagnostic if it is a bound member that we recognize. | ||||
19298 | if (isa<CXXPseudoDestructorExpr>(BME)) { | ||||
19299 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; | ||||
19300 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { | ||||
19301 | if (ME->getMemberNameInfo().getName().getNameKind() == | ||||
19302 | DeclarationName::CXXDestructorName) | ||||
19303 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; | ||||
19304 | } | ||||
19305 | tryToRecoverWithCall(result, PD, | ||||
19306 | /*complain*/ true); | ||||
19307 | return result; | ||||
19308 | } | ||||
19309 | |||||
19310 | // ARC unbridged casts. | ||||
19311 | case BuiltinType::ARCUnbridgedCast: { | ||||
19312 | Expr *realCast = stripARCUnbridgedCast(E); | ||||
19313 | diagnoseARCUnbridgedCast(realCast); | ||||
19314 | return realCast; | ||||
19315 | } | ||||
19316 | |||||
19317 | // Expressions of unknown type. | ||||
19318 | case BuiltinType::UnknownAny: | ||||
19319 | return diagnoseUnknownAnyExpr(*this, E); | ||||
19320 | |||||
19321 | // Pseudo-objects. | ||||
19322 | case BuiltinType::PseudoObject: | ||||
19323 | return checkPseudoObjectRValue(E); | ||||
19324 | |||||
19325 | case BuiltinType::BuiltinFn: { | ||||
19326 | // Accept __noop without parens by implicitly converting it to a call expr. | ||||
19327 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); | ||||
19328 | if (DRE) { | ||||
19329 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); | ||||
19330 | if (FD->getBuiltinID() == Builtin::BI__noop) { | ||||
19331 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), | ||||
19332 | CK_BuiltinFnToFnPtr) | ||||
19333 | .get(); | ||||
19334 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, | ||||
19335 | VK_RValue, SourceLocation(), | ||||
19336 | FPOptionsOverride()); | ||||
19337 | } | ||||
19338 | } | ||||
19339 | |||||
19340 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); | ||||
19341 | return ExprError(); | ||||
19342 | } | ||||
19343 | |||||
19344 | case BuiltinType::IncompleteMatrixIdx: | ||||
19345 | Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) | ||||
19346 | ->getRowIdx() | ||||
19347 | ->getBeginLoc(), | ||||
19348 | diag::err_matrix_incomplete_index); | ||||
19349 | return ExprError(); | ||||
19350 | |||||
19351 | // Expressions of unknown type. | ||||
19352 | case BuiltinType::OMPArraySection: | ||||
19353 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); | ||||
19354 | return ExprError(); | ||||
19355 | |||||
19356 | // Expressions of unknown type. | ||||
19357 | case BuiltinType::OMPArrayShaping: | ||||
19358 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); | ||||
19359 | |||||
19360 | case BuiltinType::OMPIterator: | ||||
19361 | return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); | ||||
19362 | |||||
19363 | // Everything else should be impossible. | ||||
19364 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
19365 | case BuiltinType::Id: | ||||
19366 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
19367 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
19368 | case BuiltinType::Id: | ||||
19369 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
19370 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
19371 | case BuiltinType::Id: | ||||
19372 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
19373 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
19374 | case BuiltinType::Id: | ||||
19375 | #include "clang/Basic/PPCTypes.def" | ||||
19376 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
19377 | #include "clang/Basic/RISCVVTypes.def" | ||||
19378 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: | ||||
19379 | #define PLACEHOLDER_TYPE(Id, SingletonId) | ||||
19380 | #include "clang/AST/BuiltinTypes.def" | ||||
19381 | break; | ||||
19382 | } | ||||
19383 | |||||
19384 | llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19384); | ||||
19385 | } | ||||
19386 | |||||
19387 | bool Sema::CheckCaseExpression(Expr *E) { | ||||
19388 | if (E->isTypeDependent()) | ||||
19389 | return true; | ||||
19390 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) | ||||
19391 | return E->getType()->isIntegralOrEnumerationType(); | ||||
19392 | return false; | ||||
19393 | } | ||||
19394 | |||||
19395 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | ||||
19396 | ExprResult | ||||
19397 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | ||||
19398 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19399, __PRETTY_FUNCTION__)) | ||||
19399 | "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && "Unknown Objective-C Boolean value!") ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/lib/Sema/SemaExpr.cpp" , 19399, __PRETTY_FUNCTION__)); | ||||
19400 | QualType BoolT = Context.ObjCBuiltinBoolTy; | ||||
19401 | if (!Context.getBOOLDecl()) { | ||||
19402 | LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, | ||||
19403 | Sema::LookupOrdinaryName); | ||||
19404 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { | ||||
19405 | NamedDecl *ND = Result.getFoundDecl(); | ||||
19406 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) | ||||
19407 | Context.setBOOLDecl(TD); | ||||
19408 | } | ||||
19409 | } | ||||
19410 | if (Context.getBOOLDecl()) | ||||
19411 | BoolT = Context.getBOOLType(); | ||||
19412 | return new (Context) | ||||
19413 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); | ||||
19414 | } | ||||
19415 | |||||
19416 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( | ||||
19417 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, | ||||
19418 | SourceLocation RParen) { | ||||
19419 | |||||
19420 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); | ||||
19421 | |||||
19422 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { | ||||
19423 | return Spec.getPlatform() == Platform; | ||||
19424 | }); | ||||
19425 | |||||
19426 | VersionTuple Version; | ||||
19427 | if (Spec != AvailSpecs.end()) | ||||
19428 | Version = Spec->getVersion(); | ||||
19429 | |||||
19430 | // The use of `@available` in the enclosing function should be analyzed to | ||||
19431 | // warn when it's used inappropriately (i.e. not if(@available)). | ||||
19432 | if (getCurFunctionOrMethodDecl()) | ||||
19433 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; | ||||
19434 | else if (getCurBlock() || getCurLambda()) | ||||
19435 | getCurFunction()->HasPotentialAvailabilityViolations = true; | ||||
19436 | |||||
19437 | return new (Context) | ||||
19438 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); | ||||
19439 | } | ||||
19440 | |||||
19441 | ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, | ||||
19442 | ArrayRef<Expr *> SubExprs, QualType T) { | ||||
19443 | if (!Context.getLangOpts().RecoveryAST) | ||||
19444 | return ExprError(); | ||||
19445 | |||||
19446 | if (isSFINAEContext()) | ||||
19447 | return ExprError(); | ||||
19448 | |||||
19449 | if (T.isNull() || !Context.getLangOpts().RecoveryASTType) | ||||
19450 | // We don't know the concrete type, fallback to dependent type. | ||||
19451 | T = Context.DependentTy; | ||||
19452 | return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); | ||||
19453 | } |
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/XRayLists.h" |
44 | #include "llvm/ADT/APSInt.h" |
45 | #include "llvm/ADT/ArrayRef.h" |
46 | #include "llvm/ADT/DenseMap.h" |
47 | #include "llvm/ADT/DenseSet.h" |
48 | #include "llvm/ADT/FoldingSet.h" |
49 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
50 | #include "llvm/ADT/MapVector.h" |
51 | #include "llvm/ADT/None.h" |
52 | #include "llvm/ADT/Optional.h" |
53 | #include "llvm/ADT/PointerIntPair.h" |
54 | #include "llvm/ADT/PointerUnion.h" |
55 | #include "llvm/ADT/SmallVector.h" |
56 | #include "llvm/ADT/StringMap.h" |
57 | #include "llvm/ADT/StringRef.h" |
58 | #include "llvm/ADT/TinyPtrVector.h" |
59 | #include "llvm/ADT/Triple.h" |
60 | #include "llvm/ADT/iterator_range.h" |
61 | #include "llvm/Support/AlignOf.h" |
62 | #include "llvm/Support/Allocator.h" |
63 | #include "llvm/Support/Casting.h" |
64 | #include "llvm/Support/Compiler.h" |
65 | #include "llvm/Support/TypeSize.h" |
66 | #include <cassert> |
67 | #include <cstddef> |
68 | #include <cstdint> |
69 | #include <iterator> |
70 | #include <memory> |
71 | #include <string> |
72 | #include <type_traits> |
73 | #include <utility> |
74 | #include <vector> |
75 | |
76 | namespace llvm { |
77 | |
78 | class APFixedPoint; |
79 | class FixedPointSemantics; |
80 | struct fltSemantics; |
81 | template <typename T, unsigned N> class SmallPtrSet; |
82 | |
83 | } // namespace llvm |
84 | |
85 | namespace clang { |
86 | |
87 | class APValue; |
88 | class ASTMutationListener; |
89 | class ASTRecordLayout; |
90 | class AtomicExpr; |
91 | class BlockExpr; |
92 | class BuiltinTemplateDecl; |
93 | class CharUnits; |
94 | class ConceptDecl; |
95 | class CXXABI; |
96 | class CXXConstructorDecl; |
97 | class CXXMethodDecl; |
98 | class CXXRecordDecl; |
99 | class DiagnosticsEngine; |
100 | class ParentMapContext; |
101 | class DynTypedNode; |
102 | class DynTypedNodeList; |
103 | class Expr; |
104 | class GlobalDecl; |
105 | class MangleContext; |
106 | class MangleNumberingContext; |
107 | class MaterializeTemporaryExpr; |
108 | class MemberSpecializationInfo; |
109 | class Module; |
110 | struct MSGuidDeclParts; |
111 | class ObjCCategoryDecl; |
112 | class ObjCCategoryImplDecl; |
113 | class ObjCContainerDecl; |
114 | class ObjCImplDecl; |
115 | class ObjCImplementationDecl; |
116 | class ObjCInterfaceDecl; |
117 | class ObjCIvarDecl; |
118 | class ObjCMethodDecl; |
119 | class ObjCPropertyDecl; |
120 | class ObjCPropertyImplDecl; |
121 | class ObjCProtocolDecl; |
122 | class ObjCTypeParamDecl; |
123 | class OMPTraitInfo; |
124 | struct ParsedTargetAttr; |
125 | class Preprocessor; |
126 | class Stmt; |
127 | class StoredDeclsMap; |
128 | class TargetAttr; |
129 | class TargetInfo; |
130 | class TemplateDecl; |
131 | class TemplateParameterList; |
132 | class TemplateTemplateParmDecl; |
133 | class TemplateTypeParmDecl; |
134 | class UnresolvedSetIterator; |
135 | class UsingShadowDecl; |
136 | class VarTemplateDecl; |
137 | class VTableContextBase; |
138 | struct BlockVarCopyInit; |
139 | |
140 | namespace Builtin { |
141 | |
142 | class Context; |
143 | |
144 | } // namespace Builtin |
145 | |
146 | enum BuiltinTemplateKind : int; |
147 | enum OpenCLTypeKind : uint8_t; |
148 | |
149 | namespace comments { |
150 | |
151 | class FullComment; |
152 | |
153 | } // namespace comments |
154 | |
155 | namespace interp { |
156 | |
157 | class Context; |
158 | |
159 | } // namespace interp |
160 | |
161 | namespace serialization { |
162 | template <class> class AbstractTypeReader; |
163 | } // namespace serialization |
164 | |
165 | struct TypeInfo { |
166 | uint64_t Width = 0; |
167 | unsigned Align = 0; |
168 | bool AlignIsRequired : 1; |
169 | |
170 | TypeInfo() : AlignIsRequired(false) {} |
171 | TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired) |
172 | : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {} |
173 | }; |
174 | |
175 | struct TypeInfoChars { |
176 | CharUnits Width; |
177 | CharUnits Align; |
178 | bool AlignIsRequired : 1; |
179 | |
180 | TypeInfoChars() : AlignIsRequired(false) {} |
181 | TypeInfoChars(CharUnits Width, CharUnits Align, bool AlignIsRequired) |
182 | : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {} |
183 | }; |
184 | |
185 | /// Holds long-lived AST nodes (such as types and decls) that can be |
186 | /// referred to throughout the semantic analysis of a file. |
187 | class ASTContext : public RefCountedBase<ASTContext> { |
188 | friend class NestedNameSpecifier; |
189 | |
190 | mutable SmallVector<Type *, 0> Types; |
191 | mutable llvm::FoldingSet<ExtQuals> ExtQualNodes; |
192 | mutable llvm::FoldingSet<ComplexType> ComplexTypes; |
193 | mutable llvm::FoldingSet<PointerType> PointerTypes; |
194 | mutable llvm::FoldingSet<AdjustedType> AdjustedTypes; |
195 | mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes; |
196 | mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes; |
197 | mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes; |
198 | mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes; |
199 | mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &> |
200 | ConstantArrayTypes; |
201 | mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes; |
202 | mutable std::vector<VariableArrayType*> VariableArrayTypes; |
203 | mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes; |
204 | mutable llvm::FoldingSet<DependentSizedExtVectorType> |
205 | DependentSizedExtVectorTypes; |
206 | mutable llvm::FoldingSet<DependentAddressSpaceType> |
207 | DependentAddressSpaceTypes; |
208 | mutable llvm::FoldingSet<VectorType> VectorTypes; |
209 | mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes; |
210 | mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes; |
211 | mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes; |
212 | mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes; |
213 | mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&> |
214 | FunctionProtoTypes; |
215 | mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes; |
216 | mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes; |
217 | mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes; |
218 | mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes; |
219 | mutable llvm::FoldingSet<SubstTemplateTypeParmType> |
220 | SubstTemplateTypeParmTypes; |
221 | mutable llvm::FoldingSet<SubstTemplateTypeParmPackType> |
222 | SubstTemplateTypeParmPackTypes; |
223 | mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&> |
224 | TemplateSpecializationTypes; |
225 | mutable llvm::FoldingSet<ParenType> ParenTypes; |
226 | mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes; |
227 | mutable llvm::FoldingSet<DependentNameType> DependentNameTypes; |
228 | mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType, |
229 | ASTContext&> |
230 | DependentTemplateSpecializationTypes; |
231 | llvm::FoldingSet<PackExpansionType> PackExpansionTypes; |
232 | mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes; |
233 | mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes; |
234 | mutable llvm::FoldingSet<DependentUnaryTransformType> |
235 | DependentUnaryTransformTypes; |
236 | mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes; |
237 | mutable llvm::FoldingSet<DeducedTemplateSpecializationType> |
238 | DeducedTemplateSpecializationTypes; |
239 | mutable llvm::FoldingSet<AtomicType> AtomicTypes; |
240 | llvm::FoldingSet<AttributedType> AttributedTypes; |
241 | mutable llvm::FoldingSet<PipeType> PipeTypes; |
242 | mutable llvm::FoldingSet<ExtIntType> ExtIntTypes; |
243 | mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes; |
244 | |
245 | mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames; |
246 | mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames; |
247 | mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> |
248 | SubstTemplateTemplateParms; |
249 | mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage, |
250 | ASTContext&> |
251 | SubstTemplateTemplateParmPacks; |
252 | |
253 | /// The set of nested name specifiers. |
254 | /// |
255 | /// This set is managed by the NestedNameSpecifier class. |
256 | mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers; |
257 | mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr; |
258 | |
259 | /// A cache mapping from RecordDecls to ASTRecordLayouts. |
260 | /// |
261 | /// This is lazily created. This is intentionally not serialized. |
262 | mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> |
263 | ASTRecordLayouts; |
264 | mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> |
265 | ObjCLayouts; |
266 | |
267 | /// A cache from types to size and alignment information. |
268 | using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; |
269 | mutable TypeInfoMap MemoizedTypeInfo; |
270 | |
271 | /// A cache from types to unadjusted alignment information. Only ARM and |
272 | /// AArch64 targets need this information, keeping it separate prevents |
273 | /// imposing overhead on TypeInfo size. |
274 | using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>; |
275 | mutable UnadjustedAlignMap MemoizedUnadjustedAlign; |
276 | |
277 | /// A cache mapping from CXXRecordDecls to key functions. |
278 | llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; |
279 | |
280 | /// Mapping from ObjCContainers to their ObjCImplementations. |
281 | llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls; |
282 | |
283 | /// Mapping from ObjCMethod to its duplicate declaration in the same |
284 | /// interface. |
285 | llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls; |
286 | |
287 | /// Mapping from __block VarDecls to BlockVarCopyInit. |
288 | llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits; |
289 | |
290 | /// Mapping from GUIDs to the corresponding MSGuidDecl. |
291 | mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls; |
292 | |
293 | /// Mapping from APValues to the corresponding TemplateParamObjects. |
294 | mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls; |
295 | |
296 | /// A cache mapping a string value to a StringLiteral object with the same |
297 | /// value. |
298 | /// |
299 | /// This is lazily created. This is intentionally not serialized. |
300 | mutable llvm::StringMap<StringLiteral *> StringLiteralCache; |
301 | |
302 | /// MD5 hash of CUID. It is calculated when first used and cached by this |
303 | /// data member. |
304 | mutable std::string CUIDHash; |
305 | |
306 | /// Representation of a "canonical" template template parameter that |
307 | /// is used in canonical template names. |
308 | class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { |
309 | TemplateTemplateParmDecl *Parm; |
310 | |
311 | public: |
312 | CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) |
313 | : Parm(Parm) {} |
314 | |
315 | TemplateTemplateParmDecl *getParam() const { return Parm; } |
316 | |
317 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) { |
318 | Profile(ID, C, Parm); |
319 | } |
320 | |
321 | static void Profile(llvm::FoldingSetNodeID &ID, |
322 | const ASTContext &C, |
323 | TemplateTemplateParmDecl *Parm); |
324 | }; |
325 | mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm, |
326 | const ASTContext&> |
327 | CanonTemplateTemplateParms; |
328 | |
329 | TemplateTemplateParmDecl * |
330 | getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; |
331 | |
332 | /// The typedef for the __int128_t type. |
333 | mutable TypedefDecl *Int128Decl = nullptr; |
334 | |
335 | /// The typedef for the __uint128_t type. |
336 | mutable TypedefDecl *UInt128Decl = nullptr; |
337 | |
338 | /// The typedef for the target specific predefined |
339 | /// __builtin_va_list type. |
340 | mutable TypedefDecl *BuiltinVaListDecl = nullptr; |
341 | |
342 | /// The typedef for the predefined \c __builtin_ms_va_list type. |
343 | mutable TypedefDecl *BuiltinMSVaListDecl = nullptr; |
344 | |
345 | /// The typedef for the predefined \c id type. |
346 | mutable TypedefDecl *ObjCIdDecl = nullptr; |
347 | |
348 | /// The typedef for the predefined \c SEL type. |
349 | mutable TypedefDecl *ObjCSelDecl = nullptr; |
350 | |
351 | /// The typedef for the predefined \c Class type. |
352 | mutable TypedefDecl *ObjCClassDecl = nullptr; |
353 | |
354 | /// The typedef for the predefined \c Protocol class in Objective-C. |
355 | mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr; |
356 | |
357 | /// The typedef for the predefined 'BOOL' type. |
358 | mutable TypedefDecl *BOOLDecl = nullptr; |
359 | |
360 | // Typedefs which may be provided defining the structure of Objective-C |
361 | // pseudo-builtins |
362 | QualType ObjCIdRedefinitionType; |
363 | QualType ObjCClassRedefinitionType; |
364 | QualType ObjCSelRedefinitionType; |
365 | |
366 | /// The identifier 'bool'. |
367 | mutable IdentifierInfo *BoolName = nullptr; |
368 | |
369 | /// The identifier 'NSObject'. |
370 | mutable IdentifierInfo *NSObjectName = nullptr; |
371 | |
372 | /// The identifier 'NSCopying'. |
373 | IdentifierInfo *NSCopyingName = nullptr; |
374 | |
375 | /// The identifier '__make_integer_seq'. |
376 | mutable IdentifierInfo *MakeIntegerSeqName = nullptr; |
377 | |
378 | /// The identifier '__type_pack_element'. |
379 | mutable IdentifierInfo *TypePackElementName = nullptr; |
380 | |
381 | QualType ObjCConstantStringType; |
382 | mutable RecordDecl *CFConstantStringTagDecl = nullptr; |
383 | mutable TypedefDecl *CFConstantStringTypeDecl = nullptr; |
384 | |
385 | mutable QualType ObjCSuperType; |
386 | |
387 | QualType ObjCNSStringType; |
388 | |
389 | /// The typedef declaration for the Objective-C "instancetype" type. |
390 | TypedefDecl *ObjCInstanceTypeDecl = nullptr; |
391 | |
392 | /// The type for the C FILE type. |
393 | TypeDecl *FILEDecl = nullptr; |
394 | |
395 | /// The type for the C jmp_buf type. |
396 | TypeDecl *jmp_bufDecl = nullptr; |
397 | |
398 | /// The type for the C sigjmp_buf type. |
399 | TypeDecl *sigjmp_bufDecl = nullptr; |
400 | |
401 | /// The type for the C ucontext_t type. |
402 | TypeDecl *ucontext_tDecl = nullptr; |
403 | |
404 | /// Type for the Block descriptor for Blocks CodeGen. |
405 | /// |
406 | /// Since this is only used for generation of debug info, it is not |
407 | /// serialized. |
408 | mutable RecordDecl *BlockDescriptorType = nullptr; |
409 | |
410 | /// Type for the Block descriptor for Blocks CodeGen. |
411 | /// |
412 | /// Since this is only used for generation of debug info, it is not |
413 | /// serialized. |
414 | mutable RecordDecl *BlockDescriptorExtendedType = nullptr; |
415 | |
416 | /// Declaration for the CUDA cudaConfigureCall function. |
417 | FunctionDecl *cudaConfigureCallDecl = nullptr; |
418 | |
419 | /// Keeps track of all declaration attributes. |
420 | /// |
421 | /// Since so few decls have attrs, we keep them in a hash map instead of |
422 | /// wasting space in the Decl class. |
423 | llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs; |
424 | |
425 | /// A mapping from non-redeclarable declarations in modules that were |
426 | /// merged with other declarations to the canonical declaration that they were |
427 | /// merged into. |
428 | llvm::DenseMap<Decl*, Decl*> MergedDecls; |
429 | |
430 | /// A mapping from a defining declaration to a list of modules (other |
431 | /// than the owning module of the declaration) that contain merged |
432 | /// definitions of that entity. |
433 | llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules; |
434 | |
435 | /// Initializers for a module, in order. Each Decl will be either |
436 | /// something that has a semantic effect on startup (such as a variable with |
437 | /// a non-constant initializer), or an ImportDecl (which recursively triggers |
438 | /// initialization of another module). |
439 | struct PerModuleInitializers { |
440 | llvm::SmallVector<Decl*, 4> Initializers; |
441 | llvm::SmallVector<uint32_t, 4> LazyInitializers; |
442 | |
443 | void resolve(ASTContext &Ctx); |
444 | }; |
445 | llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers; |
446 | |
447 | ASTContext &this_() { return *this; } |
448 | |
449 | public: |
450 | /// A type synonym for the TemplateOrInstantiation mapping. |
451 | using TemplateOrSpecializationInfo = |
452 | llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>; |
453 | |
454 | private: |
455 | friend class ASTDeclReader; |
456 | friend class ASTReader; |
457 | friend class ASTWriter; |
458 | template <class> friend class serialization::AbstractTypeReader; |
459 | friend class CXXRecordDecl; |
460 | |
461 | /// A mapping to contain the template or declaration that |
462 | /// a variable declaration describes or was instantiated from, |
463 | /// respectively. |
464 | /// |
465 | /// For non-templates, this value will be NULL. For variable |
466 | /// declarations that describe a variable template, this will be a |
467 | /// pointer to a VarTemplateDecl. For static data members |
468 | /// of class template specializations, this will be the |
469 | /// MemberSpecializationInfo referring to the member variable that was |
470 | /// instantiated or specialized. Thus, the mapping will keep track of |
471 | /// the static data member templates from which static data members of |
472 | /// class template specializations were instantiated. |
473 | /// |
474 | /// Given the following example: |
475 | /// |
476 | /// \code |
477 | /// template<typename T> |
478 | /// struct X { |
479 | /// static T value; |
480 | /// }; |
481 | /// |
482 | /// template<typename T> |
483 | /// T X<T>::value = T(17); |
484 | /// |
485 | /// int *x = &X<int>::value; |
486 | /// \endcode |
487 | /// |
488 | /// This mapping will contain an entry that maps from the VarDecl for |
489 | /// X<int>::value to the corresponding VarDecl for X<T>::value (within the |
490 | /// class template X) and will be marked TSK_ImplicitInstantiation. |
491 | llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo> |
492 | TemplateOrInstantiation; |
493 | |
494 | /// Keeps track of the declaration from which a using declaration was |
495 | /// created during instantiation. |
496 | /// |
497 | /// The source and target declarations are always a UsingDecl, an |
498 | /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl. |
499 | /// |
500 | /// For example: |
501 | /// \code |
502 | /// template<typename T> |
503 | /// struct A { |
504 | /// void f(); |
505 | /// }; |
506 | /// |
507 | /// template<typename T> |
508 | /// struct B : A<T> { |
509 | /// using A<T>::f; |
510 | /// }; |
511 | /// |
512 | /// template struct B<int>; |
513 | /// \endcode |
514 | /// |
515 | /// This mapping will contain an entry that maps from the UsingDecl in |
516 | /// B<int> to the UnresolvedUsingDecl in B<T>. |
517 | llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl; |
518 | |
519 | llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*> |
520 | InstantiatedFromUsingShadowDecl; |
521 | |
522 | llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl; |
523 | |
524 | /// Mapping that stores the methods overridden by a given C++ |
525 | /// member function. |
526 | /// |
527 | /// Since most C++ member functions aren't virtual and therefore |
528 | /// don't override anything, we store the overridden functions in |
529 | /// this map on the side rather than within the CXXMethodDecl structure. |
530 | using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>; |
531 | llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods; |
532 | |
533 | /// Mapping from each declaration context to its corresponding |
534 | /// mangling numbering context (used for constructs like lambdas which |
535 | /// need to be consistently numbered for the mangler). |
536 | llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>> |
537 | MangleNumberingContexts; |
538 | llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>> |
539 | ExtraMangleNumberingContexts; |
540 | |
541 | /// Side-table of mangling numbers for declarations which rarely |
542 | /// need them (like static local vars). |
543 | llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers; |
544 | llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers; |
545 | /// Mapping the associated device lambda mangling number if present. |
546 | mutable llvm::DenseMap<const CXXRecordDecl *, unsigned> |
547 | DeviceLambdaManglingNumbers; |
548 | |
549 | /// Mapping that stores parameterIndex values for ParmVarDecls when |
550 | /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex. |
551 | using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>; |
552 | ParameterIndexTable ParamIndices; |
553 | |
554 | ImportDecl *FirstLocalImport = nullptr; |
555 | ImportDecl *LastLocalImport = nullptr; |
556 | |
557 | TranslationUnitDecl *TUDecl; |
558 | mutable ExternCContextDecl *ExternCContext = nullptr; |
559 | mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr; |
560 | mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr; |
561 | |
562 | /// The associated SourceManager object. |
563 | SourceManager &SourceMgr; |
564 | |
565 | /// The language options used to create the AST associated with |
566 | /// this ASTContext object. |
567 | LangOptions &LangOpts; |
568 | |
569 | /// NoSanitizeList object that is used by sanitizers to decide which |
570 | /// entities should not be instrumented. |
571 | std::unique_ptr<NoSanitizeList> NoSanitizeL; |
572 | |
573 | /// Function filtering mechanism to determine whether a given function |
574 | /// should be imbued with the XRay "always" or "never" attributes. |
575 | std::unique_ptr<XRayFunctionFilter> XRayFilter; |
576 | |
577 | /// ProfileList object that is used by the profile instrumentation |
578 | /// to decide which entities should be instrumented. |
579 | std::unique_ptr<ProfileList> ProfList; |
580 | |
581 | /// The allocator used to create AST objects. |
582 | /// |
583 | /// AST objects are never destructed; rather, all memory associated with the |
584 | /// AST objects will be released when the ASTContext itself is destroyed. |
585 | mutable llvm::BumpPtrAllocator BumpAlloc; |
586 | |
587 | /// Allocator for partial diagnostics. |
588 | PartialDiagnostic::DiagStorageAllocator DiagAllocator; |
589 | |
590 | /// The current C++ ABI. |
591 | std::unique_ptr<CXXABI> ABI; |
592 | CXXABI *createCXXABI(const TargetInfo &T); |
593 | |
594 | /// The logical -> physical address space map. |
595 | const LangASMap *AddrSpaceMap = nullptr; |
596 | |
597 | /// Address space map mangling must be used with language specific |
598 | /// address spaces (e.g. OpenCL/CUDA) |
599 | bool AddrSpaceMapMangling; |
600 | |
601 | const TargetInfo *Target = nullptr; |
602 | const TargetInfo *AuxTarget = nullptr; |
603 | clang::PrintingPolicy PrintingPolicy; |
604 | std::unique_ptr<interp::Context> InterpContext; |
605 | std::unique_ptr<ParentMapContext> ParentMapCtx; |
606 | |
607 | public: |
608 | IdentifierTable &Idents; |
609 | SelectorTable &Selectors; |
610 | Builtin::Context &BuiltinInfo; |
611 | mutable DeclarationNameTable DeclarationNames; |
612 | IntrusiveRefCntPtr<ExternalASTSource> ExternalSource; |
613 | ASTMutationListener *Listener = nullptr; |
614 | |
615 | /// Returns the clang bytecode interpreter context. |
616 | interp::Context &getInterpContext(); |
617 | |
618 | /// Returns the dynamic AST node parent map context. |
619 | ParentMapContext &getParentMapContext(); |
620 | |
621 | // A traversal scope limits the parts of the AST visible to certain analyses. |
622 | // RecursiveASTVisitor::TraverseAST will only visit reachable nodes, and |
623 | // getParents() will only observe reachable parent edges. |
624 | // |
625 | // The scope is defined by a set of "top-level" declarations. |
626 | // Initially, it is the entire TU: {getTranslationUnitDecl()}. |
627 | // Changing the scope clears the parent cache, which is expensive to rebuild. |
628 | std::vector<Decl *> getTraversalScope() const { return TraversalScope; } |
629 | void setTraversalScope(const std::vector<Decl *> &); |
630 | |
631 | /// Forwards to get node parents from the ParentMapContext. New callers should |
632 | /// use ParentMapContext::getParents() directly. |
633 | template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node); |
634 | |
635 | const clang::PrintingPolicy &getPrintingPolicy() const { |
636 | return PrintingPolicy; |
637 | } |
638 | |
639 | void setPrintingPolicy(const clang::PrintingPolicy &Policy) { |
640 | PrintingPolicy = Policy; |
641 | } |
642 | |
643 | SourceManager& getSourceManager() { return SourceMgr; } |
644 | const SourceManager& getSourceManager() const { return SourceMgr; } |
645 | |
646 | llvm::BumpPtrAllocator &getAllocator() const { |
647 | return BumpAlloc; |
648 | } |
649 | |
650 | void *Allocate(size_t Size, unsigned Align = 8) const { |
651 | return BumpAlloc.Allocate(Size, Align); |
652 | } |
653 | template <typename T> T *Allocate(size_t Num = 1) const { |
654 | return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T))); |
655 | } |
656 | void Deallocate(void *Ptr) const {} |
657 | |
658 | /// Return the total amount of physical memory allocated for representing |
659 | /// AST nodes and type information. |
660 | size_t getASTAllocatedMemory() const { |
661 | return BumpAlloc.getTotalMemory(); |
662 | } |
663 | |
664 | /// Return the total memory used for various side tables. |
665 | size_t getSideTableAllocatedMemory() const; |
666 | |
667 | PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() { |
668 | return DiagAllocator; |
669 | } |
670 | |
671 | const TargetInfo &getTargetInfo() const { return *Target; } |
672 | const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } |
673 | |
674 | /// getIntTypeForBitwidth - |
675 | /// sets integer QualTy according to specified details: |
676 | /// bitwidth, signed/unsigned. |
677 | /// Returns empty type if there is no appropriate target types. |
678 | QualType getIntTypeForBitwidth(unsigned DestWidth, |
679 | unsigned Signed) const; |
680 | |
681 | /// getRealTypeForBitwidth - |
682 | /// sets floating point QualTy according to specified bitwidth. |
683 | /// Returns empty type if there is no appropriate target types. |
684 | QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const; |
685 | |
686 | bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const; |
687 | |
688 | const LangOptions& getLangOpts() const { return LangOpts; } |
689 | |
690 | // If this condition is false, typo correction must be performed eagerly |
691 | // rather than delayed in many places, as it makes use of dependent types. |
692 | // the condition is false for clang's C-only codepath, as it doesn't support |
693 | // dependent types yet. |
694 | bool isDependenceAllowed() const { |
695 | return LangOpts.CPlusPlus || LangOpts.RecoveryAST; |
696 | } |
697 | |
698 | const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; } |
699 | |
700 | const XRayFunctionFilter &getXRayFilter() const { |
701 | return *XRayFilter; |
702 | } |
703 | |
704 | const ProfileList &getProfileList() const { return *ProfList; } |
705 | |
706 | DiagnosticsEngine &getDiagnostics() const; |
707 | |
708 | FullSourceLoc getFullLoc(SourceLocation Loc) const { |
709 | return FullSourceLoc(Loc,SourceMgr); |
710 | } |
711 | |
712 | /// All comments in this translation unit. |
713 | RawCommentList Comments; |
714 | |
715 | /// True if comments are already loaded from ExternalASTSource. |
716 | mutable bool CommentsLoaded = false; |
717 | |
718 | /// Mapping from declaration to directly attached comment. |
719 | /// |
720 | /// Raw comments are owned by Comments list. This mapping is populated |
721 | /// lazily. |
722 | mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments; |
723 | |
724 | /// Mapping from canonical declaration to the first redeclaration in chain |
725 | /// that has a comment attached. |
726 | /// |
727 | /// Raw comments are owned by Comments list. This mapping is populated |
728 | /// lazily. |
729 | mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments; |
730 | |
731 | /// Keeps track of redeclaration chains that don't have any comment attached. |
732 | /// Mapping from canonical declaration to redeclaration chain that has no |
733 | /// comments attached to any redeclaration. Specifically it's mapping to |
734 | /// the last redeclaration we've checked. |
735 | /// |
736 | /// Shall not contain declarations that have comments attached to any |
737 | /// redeclaration in their chain. |
738 | mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains; |
739 | |
740 | /// Mapping from declarations to parsed comments attached to any |
741 | /// redeclaration. |
742 | mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments; |
743 | |
744 | /// Attaches \p Comment to \p OriginalD and to its redeclaration chain |
745 | /// and removes the redeclaration chain from the set of commentless chains. |
746 | /// |
747 | /// Don't do anything if a comment has already been attached to \p OriginalD |
748 | /// or its redeclaration chain. |
749 | void cacheRawCommentForDecl(const Decl &OriginalD, |
750 | const RawComment &Comment) const; |
751 | |
752 | /// \returns searches \p CommentsInFile for doc comment for \p D. |
753 | /// |
754 | /// \p RepresentativeLocForDecl is used as a location for searching doc |
755 | /// comments. \p CommentsInFile is a mapping offset -> comment of files in the |
756 | /// same file where \p RepresentativeLocForDecl is. |
757 | RawComment *getRawCommentForDeclNoCacheImpl( |
758 | const Decl *D, const SourceLocation RepresentativeLocForDecl, |
759 | const std::map<unsigned, RawComment *> &CommentsInFile) const; |
760 | |
761 | /// Return the documentation comment attached to a given declaration, |
762 | /// without looking into cache. |
763 | RawComment *getRawCommentForDeclNoCache(const Decl *D) const; |
764 | |
765 | public: |
766 | void addComment(const RawComment &RC); |
767 | |
768 | /// Return the documentation comment attached to a given declaration. |
769 | /// Returns nullptr if no comment is attached. |
770 | /// |
771 | /// \param OriginalDecl if not nullptr, is set to declaration AST node that |
772 | /// had the comment, if the comment we found comes from a redeclaration. |
773 | const RawComment * |
774 | getRawCommentForAnyRedecl(const Decl *D, |
775 | const Decl **OriginalDecl = nullptr) const; |
776 | |
777 | /// Searches existing comments for doc comments that should be attached to \p |
778 | /// Decls. If any doc comment is found, it is parsed. |
779 | /// |
780 | /// Requirement: All \p Decls are in the same file. |
781 | /// |
782 | /// If the last comment in the file is already attached we assume |
783 | /// there are not comments left to be attached to \p Decls. |
784 | void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls, |
785 | const Preprocessor *PP); |
786 | |
787 | /// Return parsed documentation comment attached to a given declaration. |
788 | /// Returns nullptr if no comment is attached. |
789 | /// |
790 | /// \param PP the Preprocessor used with this TU. Could be nullptr if |
791 | /// preprocessor is not available. |
792 | comments::FullComment *getCommentForDecl(const Decl *D, |
793 | const Preprocessor *PP) const; |
794 | |
795 | /// Return parsed documentation comment attached to a given declaration. |
796 | /// Returns nullptr if no comment is attached. Does not look at any |
797 | /// redeclarations of the declaration. |
798 | comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const; |
799 | |
800 | comments::FullComment *cloneFullComment(comments::FullComment *FC, |
801 | const Decl *D) const; |
802 | |
803 | private: |
804 | mutable comments::CommandTraits CommentCommandTraits; |
805 | |
806 | /// Iterator that visits import declarations. |
807 | class import_iterator { |
808 | ImportDecl *Import = nullptr; |
809 | |
810 | public: |
811 | using value_type = ImportDecl *; |
812 | using reference = ImportDecl *; |
813 | using pointer = ImportDecl *; |
814 | using difference_type = int; |
815 | using iterator_category = std::forward_iterator_tag; |
816 | |
817 | import_iterator() = default; |
818 | explicit import_iterator(ImportDecl *Import) : Import(Import) {} |
819 | |
820 | reference operator*() const { return Import; } |
821 | pointer operator->() const { return Import; } |
822 | |
823 | import_iterator &operator++() { |
824 | Import = ASTContext::getNextLocalImport(Import); |
825 | return *this; |
826 | } |
827 | |
828 | import_iterator operator++(int) { |
829 | import_iterator Other(*this); |
830 | ++(*this); |
831 | return Other; |
832 | } |
833 | |
834 | friend bool operator==(import_iterator X, import_iterator Y) { |
835 | return X.Import == Y.Import; |
836 | } |
837 | |
838 | friend bool operator!=(import_iterator X, import_iterator Y) { |
839 | return X.Import != Y.Import; |
840 | } |
841 | }; |
842 | |
843 | public: |
844 | comments::CommandTraits &getCommentCommandTraits() const { |
845 | return CommentCommandTraits; |
846 | } |
847 | |
848 | /// Retrieve the attributes for the given declaration. |
849 | AttrVec& getDeclAttrs(const Decl *D); |
850 | |
851 | /// Erase the attributes corresponding to the given declaration. |
852 | void eraseDeclAttrs(const Decl *D); |
853 | |
854 | /// If this variable is an instantiated static data member of a |
855 | /// class template specialization, returns the templated static data member |
856 | /// from which it was instantiated. |
857 | // FIXME: Remove ? |
858 | MemberSpecializationInfo *getInstantiatedFromStaticDataMember( |
859 | const VarDecl *Var); |
860 | |
861 | TemplateOrSpecializationInfo |
862 | getTemplateOrSpecializationInfo(const VarDecl *Var); |
863 | |
864 | /// Note that the static data member \p Inst is an instantiation of |
865 | /// the static data member template \p Tmpl of a class template. |
866 | void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, |
867 | TemplateSpecializationKind TSK, |
868 | SourceLocation PointOfInstantiation = SourceLocation()); |
869 | |
870 | void setTemplateOrSpecializationInfo(VarDecl *Inst, |
871 | TemplateOrSpecializationInfo TSI); |
872 | |
873 | /// If the given using decl \p Inst is an instantiation of a |
874 | /// (possibly unresolved) using decl from a template instantiation, |
875 | /// return it. |
876 | NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst); |
877 | |
878 | /// Remember that the using decl \p Inst is an instantiation |
879 | /// of the using decl \p Pattern of a class template. |
880 | void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern); |
881 | |
882 | void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, |
883 | UsingShadowDecl *Pattern); |
884 | UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); |
885 | |
886 | FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); |
887 | |
888 | void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); |
889 | |
890 | // Access to the set of methods overridden by the given C++ method. |
891 | using overridden_cxx_method_iterator = CXXMethodVector::const_iterator; |
892 | overridden_cxx_method_iterator |
893 | overridden_methods_begin(const CXXMethodDecl *Method) const; |
894 | |
895 | overridden_cxx_method_iterator |
896 | overridden_methods_end(const CXXMethodDecl *Method) const; |
897 | |
898 | unsigned overridden_methods_size(const CXXMethodDecl *Method) const; |
899 | |
900 | using overridden_method_range = |
901 | llvm::iterator_range<overridden_cxx_method_iterator>; |
902 | |
903 | overridden_method_range overridden_methods(const CXXMethodDecl *Method) const; |
904 | |
905 | /// Note that the given C++ \p Method overrides the given \p |
906 | /// Overridden method. |
907 | void addOverriddenMethod(const CXXMethodDecl *Method, |
908 | const CXXMethodDecl *Overridden); |
909 | |
910 | /// Return C++ or ObjC overridden methods for the given \p Method. |
911 | /// |
912 | /// An ObjC method is considered to override any method in the class's |
913 | /// base classes, its protocols, or its categories' protocols, that has |
914 | /// the same selector and is of the same kind (class or instance). |
915 | /// A method in an implementation is not considered as overriding the same |
916 | /// method in the interface or its categories. |
917 | void getOverriddenMethods( |
918 | const NamedDecl *Method, |
919 | SmallVectorImpl<const NamedDecl *> &Overridden) const; |
920 | |
921 | /// Notify the AST context that a new import declaration has been |
922 | /// parsed or implicitly created within this translation unit. |
923 | void addedLocalImportDecl(ImportDecl *Import); |
924 | |
925 | static ImportDecl *getNextLocalImport(ImportDecl *Import) { |
926 | return Import->getNextLocalImport(); |
927 | } |
928 | |
929 | using import_range = llvm::iterator_range<import_iterator>; |
930 | |
931 | import_range local_imports() const { |
932 | return import_range(import_iterator(FirstLocalImport), import_iterator()); |
933 | } |
934 | |
935 | Decl *getPrimaryMergedDecl(Decl *D) { |
936 | Decl *Result = MergedDecls.lookup(D); |
937 | return Result ? Result : D; |
938 | } |
939 | void setPrimaryMergedDecl(Decl *D, Decl *Primary) { |
940 | MergedDecls[D] = Primary; |
941 | } |
942 | |
943 | /// Note that the definition \p ND has been merged into module \p M, |
944 | /// and should be visible whenever \p M is visible. |
945 | void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, |
946 | bool NotifyListeners = true); |
947 | |
948 | /// Clean up the merged definition list. Call this if you might have |
949 | /// added duplicates into the list. |
950 | void deduplicateMergedDefinitonsFor(NamedDecl *ND); |
951 | |
952 | /// Get the additional modules in which the definition \p Def has |
953 | /// been merged. |
954 | ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def); |
955 | |
956 | /// Add a declaration to the list of declarations that are initialized |
957 | /// for a module. This will typically be a global variable (with internal |
958 | /// linkage) that runs module initializers, such as the iostream initializer, |
959 | /// or an ImportDecl nominating another module that has initializers. |
960 | void addModuleInitializer(Module *M, Decl *Init); |
961 | |
962 | void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs); |
963 | |
964 | /// Get the initializations to perform when importing a module, if any. |
965 | ArrayRef<Decl*> getModuleInitializers(Module *M); |
966 | |
967 | TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; } |
968 | |
969 | ExternCContextDecl *getExternCContextDecl() const; |
970 | BuiltinTemplateDecl *getMakeIntegerSeqDecl() const; |
971 | BuiltinTemplateDecl *getTypePackElementDecl() const; |
972 | |
973 | // Builtin Types. |
974 | CanQualType VoidTy; |
975 | CanQualType BoolTy; |
976 | CanQualType CharTy; |
977 | CanQualType WCharTy; // [C++ 3.9.1p5]. |
978 | CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99. |
979 | CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. |
980 | CanQualType Char8Ty; // [C++20 proposal] |
981 | CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. |
982 | CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. |
983 | CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; |
984 | CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; |
985 | CanQualType UnsignedLongLongTy, UnsignedInt128Ty; |
986 | CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty; |
987 | CanQualType ShortAccumTy, AccumTy, |
988 | LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension |
989 | CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy; |
990 | CanQualType ShortFractTy, FractTy, LongFractTy; |
991 | CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy; |
992 | CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy; |
993 | CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy, |
994 | SatUnsignedLongAccumTy; |
995 | CanQualType SatShortFractTy, SatFractTy, SatLongFractTy; |
996 | CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy, |
997 | SatUnsignedLongFractTy; |
998 | CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON |
999 | CanQualType BFloat16Ty; |
1000 | CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 |
1001 | CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy; |
1002 | CanQualType Float128ComplexTy; |
1003 | CanQualType VoidPtrTy, NullPtrTy; |
1004 | CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; |
1005 | CanQualType BuiltinFnTy; |
1006 | CanQualType PseudoObjectTy, ARCUnbridgedCastTy; |
1007 | CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; |
1008 | CanQualType ObjCBuiltinBoolTy; |
1009 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
1010 | CanQualType SingletonId; |
1011 | #include "clang/Basic/OpenCLImageTypes.def" |
1012 | CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy; |
1013 | CanQualType OCLQueueTy, OCLReserveIDTy; |
1014 | CanQualType IncompleteMatrixIdxTy; |
1015 | CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy; |
1016 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
1017 | CanQualType Id##Ty; |
1018 | #include "clang/Basic/OpenCLExtensionTypes.def" |
1019 | #define SVE_TYPE(Name, Id, SingletonId) \ |
1020 | CanQualType SingletonId; |
1021 | #include "clang/Basic/AArch64SVEACLETypes.def" |
1022 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ |
1023 | CanQualType Id##Ty; |
1024 | #include "clang/Basic/PPCTypes.def" |
1025 | #define RVV_TYPE(Name, Id, SingletonId) \ |
1026 | CanQualType SingletonId; |
1027 | #include "clang/Basic/RISCVVTypes.def" |
1028 | |
1029 | // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. |
1030 | mutable QualType AutoDeductTy; // Deduction against 'auto'. |
1031 | mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. |
1032 | |
1033 | // Decl used to help define __builtin_va_list for some targets. |
1034 | // The decl is built when constructing 'BuiltinVaListDecl'. |
1035 | mutable Decl *VaListTagDecl = nullptr; |
1036 | |
1037 | // Implicitly-declared type 'struct _GUID'. |
1038 | mutable TagDecl *MSGuidTagDecl = nullptr; |
1039 | |
1040 | /// Keep track of CUDA/HIP static device variables referenced by host code. |
1041 | llvm::DenseSet<const VarDecl *> CUDAStaticDeviceVarReferencedByHost; |
1042 | |
1043 | ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, |
1044 | SelectorTable &sels, Builtin::Context &builtins); |
1045 | ASTContext(const ASTContext &) = delete; |
1046 | ASTContext &operator=(const ASTContext &) = delete; |
1047 | ~ASTContext(); |
1048 | |
1049 | /// Attach an external AST source to the AST context. |
1050 | /// |
1051 | /// The external AST source provides the ability to load parts of |
1052 | /// the abstract syntax tree as needed from some external storage, |
1053 | /// e.g., a precompiled header. |
1054 | void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source); |
1055 | |
1056 | /// Retrieve a pointer to the external AST source associated |
1057 | /// with this AST context, if any. |
1058 | ExternalASTSource *getExternalSource() const { |
1059 | return ExternalSource.get(); |
1060 | } |
1061 | |
1062 | /// Attach an AST mutation listener to the AST context. |
1063 | /// |
1064 | /// The AST mutation listener provides the ability to track modifications to |
1065 | /// the abstract syntax tree entities committed after they were initially |
1066 | /// created. |
1067 | void setASTMutationListener(ASTMutationListener *Listener) { |
1068 | this->Listener = Listener; |
1069 | } |
1070 | |
1071 | /// Retrieve a pointer to the AST mutation listener associated |
1072 | /// with this AST context, if any. |
1073 | ASTMutationListener *getASTMutationListener() const { return Listener; } |
1074 | |
1075 | void PrintStats() const; |
1076 | const SmallVectorImpl<Type *>& getTypes() const { return Types; } |
1077 | |
1078 | BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, |
1079 | const IdentifierInfo *II) const; |
1080 | |
1081 | /// Create a new implicit TU-level CXXRecordDecl or RecordDecl |
1082 | /// declaration. |
1083 | RecordDecl *buildImplicitRecord(StringRef Name, |
1084 | RecordDecl::TagKind TK = TTK_Struct) const; |
1085 | |
1086 | /// Create a new implicit TU-level typedef declaration. |
1087 | TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const; |
1088 | |
1089 | /// Retrieve the declaration for the 128-bit signed integer type. |
1090 | TypedefDecl *getInt128Decl() const; |
1091 | |
1092 | /// Retrieve the declaration for the 128-bit unsigned integer type. |
1093 | TypedefDecl *getUInt128Decl() const; |
1094 | |
1095 | //===--------------------------------------------------------------------===// |
1096 | // Type Constructors |
1097 | //===--------------------------------------------------------------------===// |
1098 | |
1099 | private: |
1100 | /// Return a type with extended qualifiers. |
1101 | QualType getExtQualType(const Type *Base, Qualifiers Quals) const; |
1102 | |
1103 | QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; |
1104 | |
1105 | QualType getPipeType(QualType T, bool ReadOnly) const; |
1106 | |
1107 | public: |
1108 | /// Return the uniqued reference to the type for an address space |
1109 | /// qualified type with the specified type and address space. |
1110 | /// |
1111 | /// The resulting type has a union of the qualifiers from T and the address |
1112 | /// space. If T already has an address space specifier, it is silently |
1113 | /// replaced. |
1114 | QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const; |
1115 | |
1116 | /// Remove any existing address space on the type and returns the type |
1117 | /// with qualifiers intact (or that's the idea anyway) |
1118 | /// |
1119 | /// The return type should be T with all prior qualifiers minus the address |
1120 | /// space. |
1121 | QualType removeAddrSpaceQualType(QualType T) const; |
1122 | |
1123 | /// Apply Objective-C protocol qualifiers to the given type. |
1124 | /// \param allowOnPointerType specifies if we can apply protocol |
1125 | /// qualifiers on ObjCObjectPointerType. It can be set to true when |
1126 | /// constructing the canonical type of a Objective-C type parameter. |
1127 | QualType applyObjCProtocolQualifiers(QualType type, |
1128 | ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, |
1129 | bool allowOnPointerType = false) const; |
1130 | |
1131 | /// Return the uniqued reference to the type for an Objective-C |
1132 | /// gc-qualified type. |
1133 | /// |
1134 | /// The resulting type has a union of the qualifiers from T and the gc |
1135 | /// attribute. |
1136 | QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; |
1137 | |
1138 | /// Remove the existing address space on the type if it is a pointer size |
1139 | /// address space and return the type with qualifiers intact. |
1140 | QualType removePtrSizeAddrSpace(QualType T) const; |
1141 | |
1142 | /// Return the uniqued reference to the type for a \c restrict |
1143 | /// qualified type. |
1144 | /// |
1145 | /// The resulting type has a union of the qualifiers from \p T and |
1146 | /// \c restrict. |
1147 | QualType getRestrictType(QualType T) const { |
1148 | return T.withFastQualifiers(Qualifiers::Restrict); |
1149 | } |
1150 | |
1151 | /// Return the uniqued reference to the type for a \c volatile |
1152 | /// qualified type. |
1153 | /// |
1154 | /// The resulting type has a union of the qualifiers from \p T and |
1155 | /// \c volatile. |
1156 | QualType getVolatileType(QualType T) const { |
1157 | return T.withFastQualifiers(Qualifiers::Volatile); |
1158 | } |
1159 | |
1160 | /// Return the uniqued reference to the type for a \c const |
1161 | /// qualified type. |
1162 | /// |
1163 | /// The resulting type has a union of the qualifiers from \p T and \c const. |
1164 | /// |
1165 | /// It can be reasonably expected that this will always be equivalent to |
1166 | /// calling T.withConst(). |
1167 | QualType getConstType(QualType T) const { return T.withConst(); } |
1168 | |
1169 | /// Change the ExtInfo on a function type. |
1170 | const FunctionType *adjustFunctionType(const FunctionType *Fn, |
1171 | FunctionType::ExtInfo EInfo); |
1172 | |
1173 | /// Adjust the given function result type. |
1174 | CanQualType getCanonicalFunctionResultType(QualType ResultType) const; |
1175 | |
1176 | /// Change the result type of a function type once it is deduced. |
1177 | void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType); |
1178 | |
1179 | /// Get a function type and produce the equivalent function type with the |
1180 | /// specified exception specification. Type sugar that can be present on a |
1181 | /// declaration of a function with an exception specification is permitted |
1182 | /// and preserved. Other type sugar (for instance, typedefs) is not. |
1183 | QualType getFunctionTypeWithExceptionSpec( |
1184 | QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI); |
1185 | |
1186 | /// Determine whether two function types are the same, ignoring |
1187 | /// exception specifications in cases where they're part of the type. |
1188 | bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U); |
1189 | |
1190 | /// Change the exception specification on a function once it is |
1191 | /// delay-parsed, instantiated, or computed. |
1192 | void adjustExceptionSpec(FunctionDecl *FD, |
1193 | const FunctionProtoType::ExceptionSpecInfo &ESI, |
1194 | bool AsWritten = false); |
1195 | |
1196 | /// Get a function type and produce the equivalent function type where |
1197 | /// pointer size address spaces in the return type and parameter tyeps are |
1198 | /// replaced with the default address space. |
1199 | QualType getFunctionTypeWithoutPtrSizes(QualType T); |
1200 | |
1201 | /// Determine whether two function types are the same, ignoring pointer sizes |
1202 | /// in the return type and parameter types. |
1203 | bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U); |
1204 | |
1205 | /// Return the uniqued reference to the type for a complex |
1206 | /// number with the specified element type. |
1207 | QualType getComplexType(QualType T) const; |
1208 | CanQualType getComplexType(CanQualType T) const { |
1209 | return CanQualType::CreateUnsafe(getComplexType((QualType) T)); |
1210 | } |
1211 | |
1212 | /// Return the uniqued reference to the type for a pointer to |
1213 | /// the specified type. |
1214 | QualType getPointerType(QualType T) const; |
1215 | CanQualType getPointerType(CanQualType T) const { |
1216 | return CanQualType::CreateUnsafe(getPointerType((QualType) T)); |
1217 | } |
1218 | |
1219 | /// Return the uniqued reference to a type adjusted from the original |
1220 | /// type to a new type. |
1221 | QualType getAdjustedType(QualType Orig, QualType New) const; |
1222 | CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const { |
1223 | return CanQualType::CreateUnsafe( |
1224 | getAdjustedType((QualType)Orig, (QualType)New)); |
1225 | } |
1226 | |
1227 | /// Return the uniqued reference to the decayed version of the given |
1228 | /// type. Can only be called on array and function types which decay to |
1229 | /// pointer types. |
1230 | QualType getDecayedType(QualType T) const; |
1231 | CanQualType getDecayedType(CanQualType T) const { |
1232 | return CanQualType::CreateUnsafe(getDecayedType((QualType) T)); |
1233 | } |
1234 | |
1235 | /// Return the uniqued reference to the atomic type for the specified |
1236 | /// type. |
1237 | QualType getAtomicType(QualType T) const; |
1238 | |
1239 | /// Return the uniqued reference to the type for a block of the |
1240 | /// specified type. |
1241 | QualType getBlockPointerType(QualType T) const; |
1242 | |
1243 | /// Gets the struct used to keep track of the descriptor for pointer to |
1244 | /// blocks. |
1245 | QualType getBlockDescriptorType() const; |
1246 | |
1247 | /// Return a read_only pipe type for the specified type. |
1248 | QualType getReadPipeType(QualType T) const; |
1249 | |
1250 | /// Return a write_only pipe type for the specified type. |
1251 | QualType getWritePipeType(QualType T) const; |
1252 | |
1253 | /// Return an extended integer type with the specified signedness and bit |
1254 | /// count. |
1255 | QualType getExtIntType(bool Unsigned, unsigned NumBits) const; |
1256 | |
1257 | /// Return a dependent extended integer type with the specified signedness and |
1258 | /// bit count. |
1259 | QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const; |
1260 | |
1261 | /// Gets the struct used to keep track of the extended descriptor for |
1262 | /// pointer to blocks. |
1263 | QualType getBlockDescriptorExtendedType() const; |
1264 | |
1265 | /// Map an AST Type to an OpenCLTypeKind enum value. |
1266 | OpenCLTypeKind getOpenCLTypeKind(const Type *T) const; |
1267 | |
1268 | /// Get address space for OpenCL type. |
1269 | LangAS getOpenCLTypeAddrSpace(const Type *T) const; |
1270 | |
1271 | void setcudaConfigureCallDecl(FunctionDecl *FD) { |
1272 | cudaConfigureCallDecl = FD; |
1273 | } |
1274 | |
1275 | FunctionDecl *getcudaConfigureCallDecl() { |
1276 | return cudaConfigureCallDecl; |
1277 | } |
1278 | |
1279 | /// Returns true iff we need copy/dispose helpers for the given type. |
1280 | bool BlockRequiresCopying(QualType Ty, const VarDecl *D); |
1281 | |
1282 | /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout |
1283 | /// is set to false in this case. If HasByrefExtendedLayout returns true, |
1284 | /// byref variable has extended lifetime. |
1285 | bool getByrefLifetime(QualType Ty, |
1286 | Qualifiers::ObjCLifetime &Lifetime, |
1287 | bool &HasByrefExtendedLayout) const; |
1288 | |
1289 | /// Return the uniqued reference to the type for an lvalue reference |
1290 | /// to the specified type. |
1291 | QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) |
1292 | const; |
1293 | |
1294 | /// Return the uniqued reference to the type for an rvalue reference |
1295 | /// to the specified type. |
1296 | QualType getRValueReferenceType(QualType T) const; |
1297 | |
1298 | /// Return the uniqued reference to the type for a member pointer to |
1299 | /// the specified type in the specified class. |
1300 | /// |
1301 | /// The class \p Cls is a \c Type because it could be a dependent name. |
1302 | QualType getMemberPointerType(QualType T, const Type *Cls) const; |
1303 | |
1304 | /// Return a non-unique reference to the type for a variable array of |
1305 | /// the specified element type. |
1306 | QualType getVariableArrayType(QualType EltTy, Expr *NumElts, |
1307 | ArrayType::ArraySizeModifier ASM, |
1308 | unsigned IndexTypeQuals, |
1309 | SourceRange Brackets) const; |
1310 | |
1311 | /// Return a non-unique reference to the type for a dependently-sized |
1312 | /// array of the specified element type. |
1313 | /// |
1314 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1315 | /// point. |
1316 | QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, |
1317 | ArrayType::ArraySizeModifier ASM, |
1318 | unsigned IndexTypeQuals, |
1319 | SourceRange Brackets) const; |
1320 | |
1321 | /// Return a unique reference to the type for an incomplete array of |
1322 | /// the specified element type. |
1323 | QualType getIncompleteArrayType(QualType EltTy, |
1324 | ArrayType::ArraySizeModifier ASM, |
1325 | unsigned IndexTypeQuals) const; |
1326 | |
1327 | /// Return the unique reference to the type for a constant array of |
1328 | /// the specified element type. |
1329 | QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, |
1330 | const Expr *SizeExpr, |
1331 | ArrayType::ArraySizeModifier ASM, |
1332 | unsigned IndexTypeQuals) const; |
1333 | |
1334 | /// Return a type for a constant array for a string literal of the |
1335 | /// specified element type and length. |
1336 | QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const; |
1337 | |
1338 | /// Returns a vla type where known sizes are replaced with [*]. |
1339 | QualType getVariableArrayDecayedType(QualType Ty) const; |
1340 | |
1341 | // Convenience struct to return information about a builtin vector type. |
1342 | struct BuiltinVectorTypeInfo { |
1343 | QualType ElementType; |
1344 | llvm::ElementCount EC; |
1345 | unsigned NumVectors; |
1346 | BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC, |
1347 | unsigned NumVectors) |
1348 | : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {} |
1349 | }; |
1350 | |
1351 | /// Returns the element type, element count and number of vectors |
1352 | /// (in case of tuple) for a builtin vector type. |
1353 | BuiltinVectorTypeInfo |
1354 | getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const; |
1355 | |
1356 | /// Return the unique reference to a scalable vector type of the specified |
1357 | /// element type and scalable number of elements. |
1358 | /// |
1359 | /// \pre \p EltTy must be a built-in type. |
1360 | QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const; |
1361 | |
1362 | /// Return the unique reference to a vector type of the specified |
1363 | /// element type and size. |
1364 | /// |
1365 | /// \pre \p VectorType must be a built-in type. |
1366 | QualType getVectorType(QualType VectorType, unsigned NumElts, |
1367 | VectorType::VectorKind VecKind) const; |
1368 | /// Return the unique reference to the type for a dependently sized vector of |
1369 | /// the specified element type. |
1370 | QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, |
1371 | SourceLocation AttrLoc, |
1372 | VectorType::VectorKind VecKind) const; |
1373 | |
1374 | /// Return the unique reference to an extended vector type |
1375 | /// of the specified element type and size. |
1376 | /// |
1377 | /// \pre \p VectorType must be a built-in type. |
1378 | QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; |
1379 | |
1380 | /// \pre Return a non-unique reference to the type for a dependently-sized |
1381 | /// vector of the specified element type. |
1382 | /// |
1383 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1384 | /// point. |
1385 | QualType getDependentSizedExtVectorType(QualType VectorType, |
1386 | Expr *SizeExpr, |
1387 | SourceLocation AttrLoc) const; |
1388 | |
1389 | /// Return the unique reference to the matrix type of the specified element |
1390 | /// type and size |
1391 | /// |
1392 | /// \pre \p ElementType must be a valid matrix element type (see |
1393 | /// MatrixType::isValidElementType). |
1394 | QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, |
1395 | unsigned NumColumns) const; |
1396 | |
1397 | /// Return the unique reference to the matrix type of the specified element |
1398 | /// type and size |
1399 | QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, |
1400 | Expr *ColumnExpr, |
1401 | SourceLocation AttrLoc) const; |
1402 | |
1403 | QualType getDependentAddressSpaceType(QualType PointeeType, |
1404 | Expr *AddrSpaceExpr, |
1405 | SourceLocation AttrLoc) const; |
1406 | |
1407 | /// Return a K&R style C function type like 'int()'. |
1408 | QualType getFunctionNoProtoType(QualType ResultTy, |
1409 | const FunctionType::ExtInfo &Info) const; |
1410 | |
1411 | QualType getFunctionNoProtoType(QualType ResultTy) const { |
1412 | return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); |
1413 | } |
1414 | |
1415 | /// Return a normal function type with a typed argument list. |
1416 | QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args, |
1417 | const FunctionProtoType::ExtProtoInfo &EPI) const { |
1418 | return getFunctionTypeInternal(ResultTy, Args, EPI, false); |
1419 | } |
1420 | |
1421 | QualType adjustStringLiteralBaseType(QualType StrLTy) const; |
1422 | |
1423 | private: |
1424 | /// Return a normal function type with a typed argument list. |
1425 | QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args, |
1426 | const FunctionProtoType::ExtProtoInfo &EPI, |
1427 | bool OnlyWantCanonical) const; |
1428 | |
1429 | public: |
1430 | /// Return the unique reference to the type for the specified type |
1431 | /// declaration. |
1432 | QualType getTypeDeclType(const TypeDecl *Decl, |
1433 | const TypeDecl *PrevDecl = nullptr) const { |
1434 | assert(Decl && "Passed null for Decl param")((Decl && "Passed null for Decl param") ? static_cast <void> (0) : __assert_fail ("Decl && \"Passed null for Decl param\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/include/clang/AST/ASTContext.h" , 1434, __PRETTY_FUNCTION__)); |
1435 | if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); |
1436 | |
1437 | if (PrevDecl) { |
1438 | assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")((PrevDecl->TypeForDecl && "previous decl has no TypeForDecl" ) ? static_cast<void> (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/include/clang/AST/ASTContext.h" , 1438, __PRETTY_FUNCTION__)); |
1439 | Decl->TypeForDecl = PrevDecl->TypeForDecl; |
1440 | return QualType(PrevDecl->TypeForDecl, 0); |
1441 | } |
1442 | |
1443 | return getTypeDeclTypeSlow(Decl); |
1444 | } |
1445 | |
1446 | /// Return the unique reference to the type for the specified |
1447 | /// typedef-name decl. |
1448 | QualType getTypedefType(const TypedefNameDecl *Decl, |
1449 | QualType Underlying = QualType()) const; |
1450 | |
1451 | QualType getRecordType(const RecordDecl *Decl) const; |
1452 | |
1453 | QualType getEnumType(const EnumDecl *Decl) const; |
1454 | |
1455 | QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; |
1456 | |
1457 | QualType getAttributedType(attr::Kind attrKind, |
1458 | QualType modifiedType, |
1459 | QualType equivalentType); |
1460 | |
1461 | QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, |
1462 | QualType Replacement) const; |
1463 | QualType getSubstTemplateTypeParmPackType( |
1464 | const TemplateTypeParmType *Replaced, |
1465 | const TemplateArgument &ArgPack); |
1466 | |
1467 | QualType |
1468 | getTemplateTypeParmType(unsigned Depth, unsigned Index, |
1469 | bool ParameterPack, |
1470 | TemplateTypeParmDecl *ParmDecl = nullptr) const; |
1471 | |
1472 | QualType getTemplateSpecializationType(TemplateName T, |
1473 | ArrayRef<TemplateArgument> Args, |
1474 | QualType Canon = QualType()) const; |
1475 | |
1476 | QualType |
1477 | getCanonicalTemplateSpecializationType(TemplateName T, |
1478 | ArrayRef<TemplateArgument> Args) const; |
1479 | |
1480 | QualType getTemplateSpecializationType(TemplateName T, |
1481 | const TemplateArgumentListInfo &Args, |
1482 | QualType Canon = QualType()) const; |
1483 | |
1484 | TypeSourceInfo * |
1485 | getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, |
1486 | const TemplateArgumentListInfo &Args, |
1487 | QualType Canon = QualType()) const; |
1488 | |
1489 | QualType getParenType(QualType NamedType) const; |
1490 | |
1491 | QualType getMacroQualifiedType(QualType UnderlyingTy, |
1492 | const IdentifierInfo *MacroII) const; |
1493 | |
1494 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
1495 | NestedNameSpecifier *NNS, QualType NamedType, |
1496 | TagDecl *OwnedTagDecl = nullptr) const; |
1497 | QualType getDependentNameType(ElaboratedTypeKeyword Keyword, |
1498 | NestedNameSpecifier *NNS, |
1499 | const IdentifierInfo *Name, |
1500 | QualType Canon = QualType()) const; |
1501 | |
1502 | QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
1503 | NestedNameSpecifier *NNS, |
1504 | const IdentifierInfo *Name, |
1505 | const TemplateArgumentListInfo &Args) const; |
1506 | QualType getDependentTemplateSpecializationType( |
1507 | ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
1508 | const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const; |
1509 | |
1510 | TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl); |
1511 | |
1512 | /// Get a template argument list with one argument per template parameter |
1513 | /// in a template parameter list, such as for the injected class name of |
1514 | /// a class template. |
1515 | void getInjectedTemplateArgs(const TemplateParameterList *Params, |
1516 | SmallVectorImpl<TemplateArgument> &Args); |
1517 | |
1518 | /// Form a pack expansion type with the given pattern. |
1519 | /// \param NumExpansions The number of expansions for the pack, if known. |
1520 | /// \param ExpectPackInType If \c false, we should not expect \p Pattern to |
1521 | /// contain an unexpanded pack. This only makes sense if the pack |
1522 | /// expansion is used in a context where the arity is inferred from |
1523 | /// elsewhere, such as if the pattern contains a placeholder type or |
1524 | /// if this is the canonical type of another pack expansion type. |
1525 | QualType getPackExpansionType(QualType Pattern, |
1526 | Optional<unsigned> NumExpansions, |
1527 | bool ExpectPackInType = true); |
1528 | |
1529 | QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, |
1530 | ObjCInterfaceDecl *PrevDecl = nullptr) const; |
1531 | |
1532 | /// Legacy interface: cannot provide type arguments or __kindof. |
1533 | QualType getObjCObjectType(QualType Base, |
1534 | ObjCProtocolDecl * const *Protocols, |
1535 | unsigned NumProtocols) const; |
1536 | |
1537 | QualType getObjCObjectType(QualType Base, |
1538 | ArrayRef<QualType> typeArgs, |
1539 | ArrayRef<ObjCProtocolDecl *> protocols, |
1540 | bool isKindOf) const; |
1541 | |
1542 | QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
1543 | ArrayRef<ObjCProtocolDecl *> protocols) const; |
1544 | void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, |
1545 | ObjCTypeParamDecl *New) const; |
1546 | |
1547 | bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl); |
1548 | |
1549 | /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in |
1550 | /// QT's qualified-id protocol list adopt all protocols in IDecl's list |
1551 | /// of protocols. |
1552 | bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, |
1553 | ObjCInterfaceDecl *IDecl); |
1554 | |
1555 | /// Return a ObjCObjectPointerType type for the given ObjCObjectType. |
1556 | QualType getObjCObjectPointerType(QualType OIT) const; |
1557 | |
1558 | /// GCC extension. |
1559 | QualType getTypeOfExprType(Expr *e) const; |
1560 | QualType getTypeOfType(QualType t) const; |
1561 | |
1562 | /// C++11 decltype. |
1563 | QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; |
1564 | |
1565 | /// Unary type transforms |
1566 | QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, |
1567 | UnaryTransformType::UTTKind UKind) const; |
1568 | |
1569 | /// C++11 deduced auto type. |
1570 | QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, |
1571 | bool IsDependent, bool IsPack = false, |
1572 | ConceptDecl *TypeConstraintConcept = nullptr, |
1573 | ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const; |
1574 | |
1575 | /// C++11 deduction pattern for 'auto' type. |
1576 | QualType getAutoDeductType() const; |
1577 | |
1578 | /// C++11 deduction pattern for 'auto &&' type. |
1579 | QualType getAutoRRefDeductType() const; |
1580 | |
1581 | /// C++17 deduced class template specialization type. |
1582 | QualType getDeducedTemplateSpecializationType(TemplateName Template, |
1583 | QualType DeducedType, |
1584 | bool IsDependent) const; |
1585 | |
1586 | /// Return the unique reference to the type for the specified TagDecl |
1587 | /// (struct/union/class/enum) decl. |
1588 | QualType getTagDeclType(const TagDecl *Decl) const; |
1589 | |
1590 | /// Return the unique type for "size_t" (C99 7.17), defined in |
1591 | /// <stddef.h>. |
1592 | /// |
1593 | /// The sizeof operator requires this (C99 6.5.3.4p4). |
1594 | CanQualType getSizeType() const; |
1595 | |
1596 | /// Return the unique signed counterpart of |
1597 | /// the integer type corresponding to size_t. |
1598 | CanQualType getSignedSizeType() const; |
1599 | |
1600 | /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in |
1601 | /// <stdint.h>. |
1602 | CanQualType getIntMaxType() const; |
1603 | |
1604 | /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in |
1605 | /// <stdint.h>. |
1606 | CanQualType getUIntMaxType() const; |
1607 | |
1608 | /// Return the unique wchar_t type available in C++ (and available as |
1609 | /// __wchar_t as a Microsoft extension). |
1610 | QualType getWCharType() const { return WCharTy; } |
1611 | |
1612 | /// Return the type of wide characters. In C++, this returns the |
1613 | /// unique wchar_t type. In C99, this returns a type compatible with the type |
1614 | /// defined in <stddef.h> as defined by the target. |
1615 | QualType getWideCharType() const { return WideCharTy; } |
1616 | |
1617 | /// Return the type of "signed wchar_t". |
1618 | /// |
1619 | /// Used when in C++, as a GCC extension. |
1620 | QualType getSignedWCharType() const; |
1621 | |
1622 | /// Return the type of "unsigned wchar_t". |
1623 | /// |
1624 | /// Used when in C++, as a GCC extension. |
1625 | QualType getUnsignedWCharType() const; |
1626 | |
1627 | /// In C99, this returns a type compatible with the type |
1628 | /// defined in <stddef.h> as defined by the target. |
1629 | QualType getWIntType() const { return WIntTy; } |
1630 | |
1631 | /// Return a type compatible with "intptr_t" (C99 7.18.1.4), |
1632 | /// as defined by the target. |
1633 | QualType getIntPtrType() const; |
1634 | |
1635 | /// Return a type compatible with "uintptr_t" (C99 7.18.1.4), |
1636 | /// as defined by the target. |
1637 | QualType getUIntPtrType() const; |
1638 | |
1639 | /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in |
1640 | /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). |
1641 | QualType getPointerDiffType() const; |
1642 | |
1643 | /// Return the unique unsigned counterpart of "ptrdiff_t" |
1644 | /// integer type. The standard (C11 7.21.6.1p7) refers to this type |
1645 | /// in the definition of %tu format specifier. |
1646 | QualType getUnsignedPointerDiffType() const; |
1647 | |
1648 | /// Return the unique type for "pid_t" defined in |
1649 | /// <sys/types.h>. We need this to compute the correct type for vfork(). |
1650 | QualType getProcessIDType() const; |
1651 | |
1652 | /// Return the C structure type used to represent constant CFStrings. |
1653 | QualType getCFConstantStringType() const; |
1654 | |
1655 | /// Returns the C struct type for objc_super |
1656 | QualType getObjCSuperType() const; |
1657 | void setObjCSuperType(QualType ST) { ObjCSuperType = ST; } |
1658 | |
1659 | /// Get the structure type used to representation CFStrings, or NULL |
1660 | /// if it hasn't yet been built. |
1661 | QualType getRawCFConstantStringType() const { |
1662 | if (CFConstantStringTypeDecl) |
1663 | return getTypedefType(CFConstantStringTypeDecl); |
1664 | return QualType(); |
1665 | } |
1666 | void setCFConstantStringType(QualType T); |
1667 | TypedefDecl *getCFConstantStringDecl() const; |
1668 | RecordDecl *getCFConstantStringTagDecl() const; |
1669 | |
1670 | // This setter/getter represents the ObjC type for an NSConstantString. |
1671 | void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); |
1672 | QualType getObjCConstantStringInterface() const { |
1673 | return ObjCConstantStringType; |
1674 | } |
1675 | |
1676 | QualType getObjCNSStringType() const { |
1677 | return ObjCNSStringType; |
1678 | } |
1679 | |
1680 | void setObjCNSStringType(QualType T) { |
1681 | ObjCNSStringType = T; |
1682 | } |
1683 | |
1684 | /// Retrieve the type that \c id has been defined to, which may be |
1685 | /// different from the built-in \c id if \c id has been typedef'd. |
1686 | QualType getObjCIdRedefinitionType() const { |
1687 | if (ObjCIdRedefinitionType.isNull()) |
1688 | return getObjCIdType(); |
1689 | return ObjCIdRedefinitionType; |
1690 | } |
1691 | |
1692 | /// Set the user-written type that redefines \c id. |
1693 | void setObjCIdRedefinitionType(QualType RedefType) { |
1694 | ObjCIdRedefinitionType = RedefType; |
1695 | } |
1696 | |
1697 | /// Retrieve the type that \c Class has been defined to, which may be |
1698 | /// different from the built-in \c Class if \c Class has been typedef'd. |
1699 | QualType getObjCClassRedefinitionType() const { |
1700 | if (ObjCClassRedefinitionType.isNull()) |
1701 | return getObjCClassType(); |
1702 | return ObjCClassRedefinitionType; |
1703 | } |
1704 | |
1705 | /// Set the user-written type that redefines 'SEL'. |
1706 | void setObjCClassRedefinitionType(QualType RedefType) { |
1707 | ObjCClassRedefinitionType = RedefType; |
1708 | } |
1709 | |
1710 | /// Retrieve the type that 'SEL' has been defined to, which may be |
1711 | /// different from the built-in 'SEL' if 'SEL' has been typedef'd. |
1712 | QualType getObjCSelRedefinitionType() const { |
1713 | if (ObjCSelRedefinitionType.isNull()) |
1714 | return getObjCSelType(); |
1715 | return ObjCSelRedefinitionType; |
1716 | } |
1717 | |
1718 | /// Set the user-written type that redefines 'SEL'. |
1719 | void setObjCSelRedefinitionType(QualType RedefType) { |
1720 | ObjCSelRedefinitionType = RedefType; |
1721 | } |
1722 | |
1723 | /// Retrieve the identifier 'NSObject'. |
1724 | IdentifierInfo *getNSObjectName() const { |
1725 | if (!NSObjectName) { |
1726 | NSObjectName = &Idents.get("NSObject"); |
1727 | } |
1728 | |
1729 | return NSObjectName; |
1730 | } |
1731 | |
1732 | /// Retrieve the identifier 'NSCopying'. |
1733 | IdentifierInfo *getNSCopyingName() { |
1734 | if (!NSCopyingName) { |
1735 | NSCopyingName = &Idents.get("NSCopying"); |
1736 | } |
1737 | |
1738 | return NSCopyingName; |
1739 | } |
1740 | |
1741 | CanQualType getNSUIntegerType() const; |
1742 | |
1743 | CanQualType getNSIntegerType() const; |
1744 | |
1745 | /// Retrieve the identifier 'bool'. |
1746 | IdentifierInfo *getBoolName() const { |
1747 | if (!BoolName) |
1748 | BoolName = &Idents.get("bool"); |
1749 | return BoolName; |
1750 | } |
1751 | |
1752 | IdentifierInfo *getMakeIntegerSeqName() const { |
1753 | if (!MakeIntegerSeqName) |
1754 | MakeIntegerSeqName = &Idents.get("__make_integer_seq"); |
1755 | return MakeIntegerSeqName; |
1756 | } |
1757 | |
1758 | IdentifierInfo *getTypePackElementName() const { |
1759 | if (!TypePackElementName) |
1760 | TypePackElementName = &Idents.get("__type_pack_element"); |
1761 | return TypePackElementName; |
1762 | } |
1763 | |
1764 | /// Retrieve the Objective-C "instancetype" type, if already known; |
1765 | /// otherwise, returns a NULL type; |
1766 | QualType getObjCInstanceType() { |
1767 | return getTypeDeclType(getObjCInstanceTypeDecl()); |
1768 | } |
1769 | |
1770 | /// Retrieve the typedef declaration corresponding to the Objective-C |
1771 | /// "instancetype" type. |
1772 | TypedefDecl *getObjCInstanceTypeDecl(); |
1773 | |
1774 | /// Set the type for the C FILE type. |
1775 | void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } |
1776 | |
1777 | /// Retrieve the C FILE type. |
1778 | QualType getFILEType() const { |
1779 | if (FILEDecl) |
1780 | return getTypeDeclType(FILEDecl); |
1781 | return QualType(); |
1782 | } |
1783 | |
1784 | /// Set the type for the C jmp_buf type. |
1785 | void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { |
1786 | this->jmp_bufDecl = jmp_bufDecl; |
1787 | } |
1788 | |
1789 | /// Retrieve the C jmp_buf type. |
1790 | QualType getjmp_bufType() const { |
1791 | if (jmp_bufDecl) |
1792 | return getTypeDeclType(jmp_bufDecl); |
1793 | return QualType(); |
1794 | } |
1795 | |
1796 | /// Set the type for the C sigjmp_buf type. |
1797 | void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { |
1798 | this->sigjmp_bufDecl = sigjmp_bufDecl; |
1799 | } |
1800 | |
1801 | /// Retrieve the C sigjmp_buf type. |
1802 | QualType getsigjmp_bufType() const { |
1803 | if (sigjmp_bufDecl) |
1804 | return getTypeDeclType(sigjmp_bufDecl); |
1805 | return QualType(); |
1806 | } |
1807 | |
1808 | /// Set the type for the C ucontext_t type. |
1809 | void setucontext_tDecl(TypeDecl *ucontext_tDecl) { |
1810 | this->ucontext_tDecl = ucontext_tDecl; |
1811 | } |
1812 | |
1813 | /// Retrieve the C ucontext_t type. |
1814 | QualType getucontext_tType() const { |
1815 | if (ucontext_tDecl) |
1816 | return getTypeDeclType(ucontext_tDecl); |
1817 | return QualType(); |
1818 | } |
1819 | |
1820 | /// The result type of logical operations, '<', '>', '!=', etc. |
1821 | QualType getLogicalOperationType() const { |
1822 | return getLangOpts().CPlusPlus ? BoolTy : IntTy; |
1823 | } |
1824 | |
1825 | /// Emit the Objective-CC type encoding for the given type \p T into |
1826 | /// \p S. |
1827 | /// |
1828 | /// If \p Field is specified then record field names are also encoded. |
1829 | void getObjCEncodingForType(QualType T, std::string &S, |
1830 | const FieldDecl *Field=nullptr, |
1831 | QualType *NotEncodedT=nullptr) const; |
1832 | |
1833 | /// Emit the Objective-C property type encoding for the given |
1834 | /// type \p T into \p S. |
1835 | void getObjCEncodingForPropertyType(QualType T, std::string &S) const; |
1836 | |
1837 | void getLegacyIntegralTypeEncoding(QualType &t) const; |
1838 | |
1839 | /// Put the string version of the type qualifiers \p QT into \p S. |
1840 | void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, |
1841 | std::string &S) const; |
1842 | |
1843 | /// Emit the encoded type for the function \p Decl into \p S. |
1844 | /// |
1845 | /// This is in the same format as Objective-C method encodings. |
1846 | /// |
1847 | /// \returns true if an error occurred (e.g., because one of the parameter |
1848 | /// types is incomplete), false otherwise. |
1849 | std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const; |
1850 | |
1851 | /// Emit the encoded type for the method declaration \p Decl into |
1852 | /// \p S. |
1853 | std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, |
1854 | bool Extended = false) const; |
1855 | |
1856 | /// Return the encoded type for this block declaration. |
1857 | std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const; |
1858 | |
1859 | /// getObjCEncodingForPropertyDecl - Return the encoded type for |
1860 | /// this method declaration. If non-NULL, Container must be either |
1861 | /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should |
1862 | /// only be NULL when getting encodings for protocol properties. |
1863 | std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, |
1864 | const Decl *Container) const; |
1865 | |
1866 | bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, |
1867 | ObjCProtocolDecl *rProto) const; |
1868 | |
1869 | ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl( |
1870 | const ObjCPropertyDecl *PD, |
1871 | const Decl *Container) const; |
1872 | |
1873 | /// Return the size of type \p T for Objective-C encoding purpose, |
1874 | /// in characters. |
1875 | CharUnits getObjCEncodingTypeSize(QualType T) const; |
1876 | |
1877 | /// Retrieve the typedef corresponding to the predefined \c id type |
1878 | /// in Objective-C. |
1879 | TypedefDecl *getObjCIdDecl() const; |
1880 | |
1881 | /// Represents the Objective-CC \c id type. |
1882 | /// |
1883 | /// This is set up lazily, by Sema. \c id is always a (typedef for a) |
1884 | /// pointer type, a pointer to a struct. |
1885 | QualType getObjCIdType() const { |
1886 | return getTypeDeclType(getObjCIdDecl()); |
1887 | } |
1888 | |
1889 | /// Retrieve the typedef corresponding to the predefined 'SEL' type |
1890 | /// in Objective-C. |
1891 | TypedefDecl *getObjCSelDecl() const; |
1892 | |
1893 | /// Retrieve the type that corresponds to the predefined Objective-C |
1894 | /// 'SEL' type. |
1895 | QualType getObjCSelType() const { |
1896 | return getTypeDeclType(getObjCSelDecl()); |
1897 | } |
1898 | |
1899 | /// Retrieve the typedef declaration corresponding to the predefined |
1900 | /// Objective-C 'Class' type. |
1901 | TypedefDecl *getObjCClassDecl() const; |
1902 | |
1903 | /// Represents the Objective-C \c Class type. |
1904 | /// |
1905 | /// This is set up lazily, by Sema. \c Class is always a (typedef for a) |
1906 | /// pointer type, a pointer to a struct. |
1907 | QualType getObjCClassType() const { |
1908 | return getTypeDeclType(getObjCClassDecl()); |
1909 | } |
1910 | |
1911 | /// Retrieve the Objective-C class declaration corresponding to |
1912 | /// the predefined \c Protocol class. |
1913 | ObjCInterfaceDecl *getObjCProtocolDecl() const; |
1914 | |
1915 | /// Retrieve declaration of 'BOOL' typedef |
1916 | TypedefDecl *getBOOLDecl() const { |
1917 | return BOOLDecl; |
1918 | } |
1919 | |
1920 | /// Save declaration of 'BOOL' typedef |
1921 | void setBOOLDecl(TypedefDecl *TD) { |
1922 | BOOLDecl = TD; |
1923 | } |
1924 | |
1925 | /// type of 'BOOL' type. |
1926 | QualType getBOOLType() const { |
1927 | return getTypeDeclType(getBOOLDecl()); |
1928 | } |
1929 | |
1930 | /// Retrieve the type of the Objective-C \c Protocol class. |
1931 | QualType getObjCProtoType() const { |
1932 | return getObjCInterfaceType(getObjCProtocolDecl()); |
1933 | } |
1934 | |
1935 | /// Retrieve the C type declaration corresponding to the predefined |
1936 | /// \c __builtin_va_list type. |
1937 | TypedefDecl *getBuiltinVaListDecl() const; |
1938 | |
1939 | /// Retrieve the type of the \c __builtin_va_list type. |
1940 | QualType getBuiltinVaListType() const { |
1941 | return getTypeDeclType(getBuiltinVaListDecl()); |
1942 | } |
1943 | |
1944 | /// Retrieve the C type declaration corresponding to the predefined |
1945 | /// \c __va_list_tag type used to help define the \c __builtin_va_list type |
1946 | /// for some targets. |
1947 | Decl *getVaListTagDecl() const; |
1948 | |
1949 | /// Retrieve the C type declaration corresponding to the predefined |
1950 | /// \c __builtin_ms_va_list type. |
1951 | TypedefDecl *getBuiltinMSVaListDecl() const; |
1952 | |
1953 | /// Retrieve the type of the \c __builtin_ms_va_list type. |
1954 | QualType getBuiltinMSVaListType() const { |
1955 | return getTypeDeclType(getBuiltinMSVaListDecl()); |
1956 | } |
1957 | |
1958 | /// Retrieve the implicitly-predeclared 'struct _GUID' declaration. |
1959 | TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; } |
1960 | |
1961 | /// Retrieve the implicitly-predeclared 'struct _GUID' type. |
1962 | QualType getMSGuidType() const { |
1963 | assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled")((MSGuidTagDecl && "asked for GUID type but MS extensions disabled" ) ? static_cast<void> (0) : __assert_fail ("MSGuidTagDecl && \"asked for GUID type but MS extensions disabled\"" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/include/clang/AST/ASTContext.h" , 1963, __PRETTY_FUNCTION__)); |
1964 | return getTagDeclType(MSGuidTagDecl); |
1965 | } |
1966 | |
1967 | /// Return whether a declaration to a builtin is allowed to be |
1968 | /// overloaded/redeclared. |
1969 | bool canBuiltinBeRedeclared(const FunctionDecl *) const; |
1970 | |
1971 | /// Return a type with additional \c const, \c volatile, or |
1972 | /// \c restrict qualifiers. |
1973 | QualType getCVRQualifiedType(QualType T, unsigned CVR) const { |
1974 | return getQualifiedType(T, Qualifiers::fromCVRMask(CVR)); |
1975 | } |
1976 | |
1977 | /// Un-split a SplitQualType. |
1978 | QualType getQualifiedType(SplitQualType split) const { |
1979 | return getQualifiedType(split.Ty, split.Quals); |
1980 | } |
1981 | |
1982 | /// Return a type with additional qualifiers. |
1983 | QualType getQualifiedType(QualType T, Qualifiers Qs) const { |
1984 | if (!Qs.hasNonFastQualifiers()) |
1985 | return T.withFastQualifiers(Qs.getFastQualifiers()); |
1986 | QualifierCollector Qc(Qs); |
1987 | const Type *Ptr = Qc.strip(T); |
1988 | return getExtQualType(Ptr, Qc); |
1989 | } |
1990 | |
1991 | /// Return a type with additional qualifiers. |
1992 | QualType getQualifiedType(const Type *T, Qualifiers Qs) const { |
1993 | if (!Qs.hasNonFastQualifiers()) |
1994 | return QualType(T, Qs.getFastQualifiers()); |
1995 | return getExtQualType(T, Qs); |
1996 | } |
1997 | |
1998 | /// Return a type with the given lifetime qualifier. |
1999 | /// |
2000 | /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None. |
2001 | QualType getLifetimeQualifiedType(QualType type, |
2002 | Qualifiers::ObjCLifetime lifetime) { |
2003 | assert(type.getObjCLifetime() == Qualifiers::OCL_None)((type.getObjCLifetime() == Qualifiers::OCL_None) ? static_cast <void> (0) : __assert_fail ("type.getObjCLifetime() == Qualifiers::OCL_None" , "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/include/clang/AST/ASTContext.h" , 2003, __PRETTY_FUNCTION__)); |
2004 | assert(lifetime != Qualifiers::OCL_None)((lifetime != Qualifiers::OCL_None) ? static_cast<void> (0) : __assert_fail ("lifetime != Qualifiers::OCL_None", "/build/llvm-toolchain-snapshot-13~++20210302100634+51cdb780db3b/clang/include/clang/AST/ASTContext.h" , 2004, __PRETTY_FUNCTION__)); |
2005 | |
2006 | Qualifiers qs; |
2007 | qs.addObjCLifetime(lifetime); |
2008 | return getQualifiedType(type, qs); |
2009 | } |
2010 | |
2011 | /// getUnqualifiedObjCPointerType - Returns version of |
2012 | /// Objective-C pointer type with lifetime qualifier removed. |
2013 | QualType getUnqualifiedObjCPointerType(QualType type) const { |
2014 | if (!type.getTypePtr()->isObjCObjectPointerType() || |
2015 | !type.getQualifiers().hasObjCLifetime()) |
2016 | return type; |
2017 | Qualifiers Qs = type.getQualifiers(); |
2018 | Qs.removeObjCLifetime(); |
2019 | return getQualifiedType(type.getUnqualifiedType(), Qs); |
2020 | } |
2021 | |
2022 | unsigned char getFixedPointScale(QualType Ty) const; |
2023 | unsigned char getFixedPointIBits(QualType Ty) const; |
2024 | llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const; |
2025 | llvm::APFixedPoint getFixedPointMax(QualType Ty) const; |
2026 | llvm::APFixedPoint getFixedPointMin(QualType Ty) const; |
2027 | |
2028 | DeclarationNameInfo getNameForTemplate(TemplateName Name, |
2029 | SourceLocation NameLoc) const; |
2030 | |
2031 | TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, |
2032 | UnresolvedSetIterator End) const; |
2033 | TemplateName getAssumedTemplateName(DeclarationName Name) const; |
2034 | |
2035 | TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, |
2036 | bool TemplateKeyword, |
2037 | TemplateDecl *Template) const; |
2038 | |
2039 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
2040 | const IdentifierInfo *Name) const; |
2041 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
2042 | OverloadedOperatorKind Operator) const; |
2043 | TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, |
2044 | TemplateName replacement) const; |
2045 | TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, |
2046 | const TemplateArgument &ArgPack) const; |
2047 | |
2048 | enum GetBuiltinTypeError { |
2049 | /// No error |
2050 | GE_None, |
2051 | |
2052 | /// Missing a type |
2053 | GE_Missing_type, |
2054 | |
2055 | /// Missing a type from <stdio.h> |
2056 | GE_Missing_stdio, |
2057 | |
2058 | /// Missing a type from <setjmp.h> |
2059 | GE_Missing_setjmp, |
2060 | |
2061 | /// Missing a type from <ucontext.h> |
2062 | GE_Missing_ucontext |
2063 | }; |
2064 | |
2065 | QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, |
2066 | ASTContext::GetBuiltinTypeError &Error, |
2067 | bool &RequireICE, bool AllowTypeModifiers) const; |
2068 | |
2069 | /// Return the type for the specified builtin. |
2070 | /// |
2071 | /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of |
2072 | /// arguments to the builtin that are required to be integer constant |
2073 | /// expressions. |
2074 | QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, |
2075 | unsigned *IntegerConstantArgs = nullptr) const; |
2076 | |
2077 | /// Types and expressions required to build C++2a three-way comparisons |
2078 | /// using operator<=>, including the values return by builtin <=> operators. |
2079 | ComparisonCategories CompCategories; |
2080 | |
2081 | private: |
2082 | CanQualType getFromTargetType(unsigned Type) const; |
2083 | TypeInfo getTypeInfoImpl(const Type *T) const; |
2084 | |
2085 | //===--------------------------------------------------------------------===// |
2086 | // Type Predicates. |
2087 | //===--------------------------------------------------------------------===// |
2088 | |
2089 | public: |
2090 | /// Return one of the GCNone, Weak or Strong Objective-C garbage |
2091 | /// collection attributes. |
2092 | Qualifiers::GC getObjCGCAttrKind(QualType Ty) const; |
2093 | |
2094 | /// Return true if the given vector types are of the same unqualified |
2095 | /// type or if they are equivalent to the same GCC vector type. |
2096 | /// |
2097 | /// \note This ignores whether they are target-specific (AltiVec or Neon) |
2098 | /// types. |
2099 | bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); |
2100 | |
2101 | /// Return true if the given types are an SVE builtin and a VectorType that |
2102 | /// is a fixed-length representation of the SVE builtin for a specific |
2103 | /// vector-length. |
2104 | bool areCompatibleSveTypes(QualType FirstType, QualType SecondType); |
2105 | |
2106 | /// Return true if the given vector types are lax-compatible SVE vector types, |
2107 | /// false otherwise. |
2108 | bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType); |
2109 | |
2110 | /// Return true if the type has been explicitly qualified with ObjC ownership. |
2111 | /// A type may be implicitly qualified with ownership under ObjC ARC, and in |
2112 | /// some cases the compiler treats these differently. |
2113 | bool hasDirectOwnershipQualifier(QualType Ty) const; |
2114 | |
2115 | /// Return true if this is an \c NSObject object with its \c NSObject |
2116 | /// attribute set. |
2117 | static bool isObjCNSObjectType(QualType Ty) { |
2118 | return Ty->isObjCNSObjectType(); |
2119 | } |
2120 | |
2121 | //===--------------------------------------------------------------------===// |
2122 | // Type Sizing and Analysis |
2123 | //===--------------------------------------------------------------------===// |
2124 | |
2125 | /// Return the APFloat 'semantics' for the specified scalar floating |
2126 | /// point type. |
2127 | const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; |
2128 | |
2129 | /// Get the size and alignment of the specified complete type in bits. |
2130 | TypeInfo getTypeInfo(const Type *T) const; |
2131 | TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); } |
2132 | |
2133 | /// Get default simd alignment of the specified complete type in bits. |
2134 | unsigned getOpenMPDefaultSimdAlign(QualType T) const; |
2135 | |
2136 | /// Return the size of the specified (complete) type \p T, in bits. |
2137 | uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; } |
2138 | uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; } |
2139 | |
2140 | /// Return the size of the character type, in bits. |
2141 | uint64_t getCharWidth() const { |
2142 | return getTypeSize(CharTy); |
2143 | } |
2144 | |
2145 | /// Convert a size in bits to a size in characters. |
2146 | CharUnits toCharUnitsFromBits(int64_t BitSize) const; |
2147 | |
2148 | /// Convert a size in characters to a size in bits. |
2149 | int64_t toBits(CharUnits CharSize) const; |
2150 | |
2151 | /// Return the size of the specified (complete) type \p T, in |
2152 | /// characters. |
2153 | CharUnits getTypeSizeInChars(QualType T) const; |
2154 | CharUnits getTypeSizeInChars(const Type *T) const; |
2155 | |
2156 | Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { |
2157 | if (Ty->isIncompleteType() || Ty->isDependentType()) |
2158 | return None; |
2159 | return getTypeSizeInChars(Ty); |
2160 | } |
2161 | |
2162 | Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { |
2163 | return getTypeSizeInCharsIfKnown(QualType(Ty, 0)); |
2164 | } |
2165 | |
2166 | /// Return the ABI-specified alignment of a (complete) type \p T, in |
2167 | /// bits. |
2168 | unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; } |
2169 | unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; } |
2170 | |
2171 | /// Return the ABI-specified natural alignment of a (complete) type \p T, |
2172 | /// before alignment adjustments, in bits. |
2173 | /// |
2174 | /// This alignment is curently used only by ARM and AArch64 when passing |
2175 | /// arguments of a composite type. |
2176 | unsigned getTypeUnadjustedAlign(QualType T) const { |
2177 | return getTypeUnadjustedAlign(T.getTypePtr()); |
2178 | } |
2179 | unsigned getTypeUnadjustedAlign(const Type *T) const; |
2180 | |
2181 | /// Return the alignment of a type, in bits, or 0 if |
2182 | /// the type is incomplete and we cannot determine the alignment (for |
2183 | /// example, from alignment attributes). The returned alignment is the |
2184 | /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the |
2185 | /// ABI alignment. |
2186 | unsigned getTypeAlignIfKnown(QualType T, |
2187 | bool NeedsPreferredAlignment = false) const; |
2188 | |
2189 | /// Return the ABI-specified alignment of a (complete) type \p T, in |
2190 | /// characters. |
2191 | CharUnits getTypeAlignInChars(QualType T) const; |
2192 | CharUnits getTypeAlignInChars(const Type *T) const; |
2193 | |
2194 | /// Return the PreferredAlignment of a (complete) type \p T, in |
2195 | /// characters. |
2196 | CharUnits getPreferredTypeAlignInChars(QualType T) const { |
2197 | return toCharUnitsFromBits(getPreferredTypeAlign(T)); |
2198 | } |
2199 | |
2200 | /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, |
2201 | /// in characters, before alignment adjustments. This method does not work on |
2202 | /// incomplete types. |
2203 | CharUnits getTypeUnadjustedAlignInChars(QualType T) const; |
2204 | CharUnits getTypeUnadjustedAlignInChars(const Type *T) const; |
2205 | |
2206 | // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the |
2207 | // type is a record, its data size is returned. |
2208 | TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const; |
2209 | |
2210 | TypeInfoChars getTypeInfoInChars(const Type *T) const; |
2211 | TypeInfoChars getTypeInfoInChars(QualType T) const; |
2212 | |
2213 | /// Determine if the alignment the type has was required using an |
2214 | /// alignment attribute. |
2215 | bool isAlignmentRequired(const Type *T) const; |
2216 | bool isAlignmentRequired(QualType T) const; |
2217 | |
2218 | /// Return the "preferred" alignment of the specified type \p T for |
2219 | /// the current target, in bits. |
2220 | /// |
2221 | /// This can be different than the ABI alignment in cases where it is |
2222 | /// beneficial for performance or backwards compatibility preserving to |
2223 | /// overalign a data type. (Note: despite the name, the preferred alignment |
2224 | /// is ABI-impacting, and not an optimization.) |
2225 | unsigned getPreferredTypeAlign(QualType T) const { |
2226 | return getPreferredTypeAlign(T.getTypePtr()); |
2227 | } |
2228 | unsigned getPreferredTypeAlign(const Type *T) const; |
2229 | |
2230 | /// Return the default alignment for __attribute__((aligned)) on |
2231 | /// this target, to be used if no alignment value is specified. |
2232 | unsigned getTargetDefaultAlignForAttributeAligned() const; |
2233 | |
2234 | /// Return the alignment in bits that should be given to a |
2235 | /// global variable with type \p T. |
2236 | unsigned getAlignOfGlobalVar(QualType T) const; |
2237 | |
2238 | /// Return the alignment in characters that should be given to a |
2239 | /// global variable with type \p T. |
2240 | CharUnits getAlignOfGlobalVarInChars(QualType T) const; |
2241 | |
2242 | /// Return a conservative estimate of the alignment of the specified |
2243 | /// decl \p D. |
2244 | /// |
2245 | /// \pre \p D must not be a bitfield type, as bitfields do not have a valid |
2246 | /// alignment. |
2247 | /// |
2248 | /// If \p ForAlignof, references are treated like their underlying type |
2249 | /// and large arrays don't get any special treatment. If not \p ForAlignof |
2250 | /// it computes the value expected by CodeGen: references are treated like |
2251 | /// pointers and large arrays get extra alignment. |
2252 | CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const; |
2253 | |
2254 | /// Return the alignment (in bytes) of the thrown exception object. This is |
2255 | /// only meaningful for targets that allocate C++ exceptions in a system |
2256 | /// runtime, such as those using the Itanium C++ ABI. |
2257 | CharUnits getExnObjectAlignment() const; |
2258 | |
2259 | /// Get or compute information about the layout of the specified |
2260 | /// record (struct/union/class) \p D, which indicates its size and field |
2261 | /// position information. |
2262 | const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const; |
2263 | |
2264 | /// Get or compute information about the layout of the specified |
2265 | /// Objective-C interface. |
2266 | const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) |
2267 | const; |
2268 | |
2269 | void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, |
2270 | bool Simple = false) const; |
2271 | |
2272 | /// Get or compute information about the layout of the specified |
2273 | /// Objective-C implementation. |
2274 | /// |
2275 | /// This may differ from the interface if synthesized ivars are present. |
2276 | const ASTRecordLayout & |
2277 | getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const; |
2278 | |
2279 | /// Get our current best idea for the key function of the |
2280 | /// given record decl, or nullptr if there isn't one. |
2281 | /// |
2282 | /// The key function is, according to the Itanium C++ ABI section 5.2.3: |
2283 | /// ...the first non-pure virtual function that is not inline at the |
2284 | /// point of class definition. |
2285 | /// |
2286 | /// Other ABIs use the same idea. However, the ARM C++ ABI ignores |
2287 | /// virtual functions that are defined 'inline', which means that |
2288 | /// the result of this computation can change. |
2289 | const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD); |
2290 | |
2291 | /// Observe that the given method cannot be a key function. |
2292 | /// Checks the key-function cache for the method's class and clears it |
2293 | /// if matches the given declaration. |
2294 | /// |
2295 | /// This is used in ABIs where out-of-line definitions marked |
2296 | /// inline are not considered to be key functions. |
2297 | /// |
2298 | /// \param method should be the declaration from the class definition |
2299 | void setNonKeyFunction(const CXXMethodDecl *method); |
2300 | |
2301 | /// Loading virtual member pointers using the virtual inheritance model |
2302 | /// always results in an adjustment using the vbtable even if the index is |
2303 | /// zero. |
2304 | /// |
2305 | /// This is usually OK because the first slot in the vbtable points |
2306 | /// backwards to the top of the MDC. However, the MDC might be reusing a |
2307 | /// vbptr from an nv-base. In this case, the first slot in the vbtable |
2308 | /// points to the start of the nv-base which introduced the vbptr and *not* |
2309 | /// the MDC. Modify the NonVirtualBaseAdjustment to account for this. |
2310 | CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const; |
2311 | |
2312 | /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. |
2313 | uint64_t getFieldOffset(const ValueDecl *FD) const; |
2314 | |
2315 | /// Get the offset of an ObjCIvarDecl in bits. |
2316 | uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, |
2317 | const ObjCImplementationDecl *ID, |
2318 | const ObjCIvarDecl *Ivar) const; |
2319 | |
2320 | /// Find the 'this' offset for the member path in a pointer-to-member |
2321 | /// APValue. |
2322 | CharUnits getMemberPointerPathAdjustment(const APValue &MP) const; |
2323 | |
2324 | bool isNearlyEmpty(const CXXRecordDecl *RD) const; |
2325 | |
2326 | VTableContextBase *getVTableContext(); |
2327 | |
2328 | /// If \p T is null pointer, assume the target in ASTContext. |
2329 | MangleContext *createMangleContext(const TargetInfo *T = nullptr); |
2330 | |
2331 | void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, |
2332 | SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const; |
2333 | |
2334 | unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const; |
2335 | void CollectInheritedProtocols(const Decl *CDecl, |
2336 | llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols); |
2337 | |
2338 | /// Return true if the specified type has unique object representations |
2339 | /// according to (C++17 [meta.unary.prop]p9) |
2340 | bool hasUniqueObjectRepresentations(QualType Ty) const; |
2341 | |
2342 | //===--------------------------------------------------------------------===// |
2343 | // Type Operators |
2344 | //===--------------------------------------------------------------------===// |
2345 | |
2346 | /// Return the canonical (structural) type corresponding to the |
2347 | /// specified potentially non-canonical type \p T. |
2348 | /// |
2349 | /// The non-canonical version of a type may have many "decorated" versions of |
2350 | /// types. Decorators can include typedefs, 'typeof' operators, etc. The |
2351 | /// returned type is guaranteed to be free of any of these, allowing two |
2352 | /// canonical types to be compared for exact equality with a simple pointer |
2353 | /// comparison. |
2354 | CanQualType getCanonicalType(QualType T) const { |
2355 | return CanQualType::CreateUnsafe(T.getCanonicalType()); |
2356 | } |
2357 | |
2358 | const Type *getCanonicalType(const Type *T) const { |
2359 | return T->getCanonicalTypeInternal().getTypePtr(); |
2360 | } |
2361 | |
2362 | /// Return the canonical parameter type corresponding to the specific |
2363 | /// potentially non-canonical one. |
2364 | /// |
2365 | /// Qualifiers are stripped off, functions are turned into function |
2366 | /// pointers, and arrays decay one level into pointers. |
2367 | CanQualType getCanonicalParamType(QualType T) const; |
2368 | |
2369 | /// Determine whether the given types \p T1 and \p T2 are equivalent. |
2370 | bool hasSameType(QualType T1, QualType T2) const { |
2371 | return getCanonicalType(T1) == getCanonicalType(T2); |
2372 | } |
2373 | bool hasSameType(const Type *T1, const Type *T2) const { |
2374 | return getCanonicalType(T1) == getCanonicalType(T2); |
2375 | } |
2376 | |
2377 | /// Return this type as a completely-unqualified array type, |
2378 | /// capturing the qualifiers in \p Quals. |
2379 | /// |
2380 | /// This will remove the minimal amount of sugaring from the types, similar |
2381 | /// to the behavior of QualType::getUnqualifiedType(). |
2382 | /// |
2383 | /// \param T is the qualified type, which may be an ArrayType |
2384 | /// |
2385 | /// \param Quals will receive the full set of qualifiers that were |
2386 | /// applied to the array. |
2387 | /// |
2388 | /// \returns if this is an array type, the completely unqualified array type |
2389 | /// that corresponds to it. Otherwise, returns T.getUnqualifiedType(). |
2390 | QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals); |
2391 | |
2392 | /// Determine whether the given types are equivalent after |
2393 | /// cvr-qualifiers have been removed. |
2394 | bool hasSameUnqualifiedType(QualType T1, QualType T2) const { |
2395 | return getCanonicalType(T1).getTypePtr() == |
2396 | getCanonicalType(T2).getTypePtr(); |
2397 | } |
2398 | |
2399 | bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT, |
2400 | bool IsParam) const { |
2401 | auto SubTnullability = SubT->getNullability(*this); |
2402 | auto SuperTnullability = SuperT->getNullability(*this); |
2403 | if (SubTnullability.hasValue() == SuperTnullability.hasValue()) { |
2404 | // Neither has nullability; return true |
2405 | if (!SubTnullability) |
2406 | return true; |
2407 | // Both have nullability qualifier. |
2408 | if (*SubTnullability == *SuperTnullability || |
2409 | *SubTnullability == NullabilityKind::Unspecified || |
2410 | *SuperTnullability == NullabilityKind::Unspecified) |
2411 | return true; |
2412 | |
2413 | if (IsParam) { |
2414 | // Ok for the superclass method parameter to be "nonnull" and the subclass |
2415 | // method parameter to be "nullable" |
2416 | return (*SuperTnullability == NullabilityKind::NonNull && |
2417 | *SubTnullability == NullabilityKind::Nullable); |
2418 | } |
2419 | // For the return type, it's okay for the superclass method to specify |
2420 | // "nullable" and the subclass method specify "nonnull" |
2421 | return (*SuperTnullability == NullabilityKind::Nullable && |
2422 | *SubTnullability == NullabilityKind::NonNull); |
2423 | } |
2424 | return true; |
2425 | } |
2426 | |
2427 | bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, |
2428 | const ObjCMethodDecl *MethodImp); |
2429 | |
2430 | bool UnwrapSimilarTypes(QualType &T1, QualType &T2); |
2431 | bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2); |
2432 | |
2433 | /// Determine if two types are similar, according to the C++ rules. That is, |
2434 | /// determine if they are the same other than qualifiers on the initial |
2435 | /// sequence of pointer / pointer-to-member / array (and in Clang, object |
2436 | /// pointer) types and their element types. |
2437 | /// |
2438 | /// Clang offers a number of qualifiers in addition to the C++ qualifiers; |
2439 | /// those qualifiers are also ignored in the 'similarity' check. |
2440 | bool hasSimilarType(QualType T1, QualType T2); |
2441 | |
2442 | /// Determine if two types are similar, ignoring only CVR qualifiers. |
2443 | bool hasCvrSimilarType(QualType T1, QualType T2); |
2444 | |
2445 | /// Retrieves the "canonical" nested name specifier for a |
2446 | /// given nested name specifier. |
2447 | /// |
2448 | /// The canonical nested name specifier is a nested name specifier |
2449 | /// that uniquely identifies a type or namespace within the type |
2450 | /// system. For example, given: |
2451 | /// |
2452 | /// \code |
2453 | /// namespace N { |
2454 | /// struct S { |
2455 | /// template<typename T> struct X { typename T* type; }; |
2456 | /// }; |
2457 | /// } |
2458 | /// |
2459 | /// template<typename T> struct Y { |
2460 | /// typename N::S::X<T>::type member; |
2461 | /// }; |
2462 | /// \endcode |
2463 | /// |
2464 | /// Here, the nested-name-specifier for N::S::X<T>:: will be |
2465 | /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined |
2466 | /// by declarations in the type system and the canonical type for |
2467 | /// the template type parameter 'T' is template-param-0-0. |
2468 | NestedNameSpecifier * |
2469 | getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const; |
2470 | |
2471 | /// Retrieves the default calling convention for the current target. |
2472 | CallingConv getDefaultCallingConvention(bool IsVariadic, |
2473 | bool IsCXXMethod, |
2474 | bool IsBuiltin = false) const; |
2475 | |
2476 | /// Retrieves the "canonical" template name that refers to a |
2477 | /// given template. |
2478 | /// |
2479 | /// The canonical template name is the simplest expression that can |
2480 | /// be used to refer to a given template. For most templates, this |
2481 | /// expression is just the template declaration itself. For example, |
2482 | /// the template std::vector can be referred to via a variety of |
2483 | /// names---std::vector, \::std::vector, vector (if vector is in |
2484 | /// scope), etc.---but all of these names map down to the same |
2485 | /// TemplateDecl, which is used to form the canonical template name. |
2486 | /// |
2487 | /// Dependent template names are more interesting. Here, the |
2488 | /// template name could be something like T::template apply or |
2489 | /// std::allocator<T>::template rebind, where the nested name |
2490 | /// specifier itself is dependent. In this case, the canonical |
2491 | /// template name uses the shortest form of the dependent |
2492 | /// nested-name-specifier, which itself contains all canonical |
2493 | /// types, values, and templates. |
2494 | TemplateName getCanonicalTemplateName(TemplateName Name) const; |
2495 | |
2496 | /// Determine whether the given template names refer to the same |
2497 | /// template. |
2498 | bool hasSameTemplateName(TemplateName X, TemplateName Y); |
2499 | |
2500 | /// Retrieve the "canonical" template argument. |
2501 | /// |
2502 | /// The canonical template argument is the simplest template argument |
2503 | /// (which may be a type, value, expression, or declaration) that |
2504 | /// expresses the value of the argument. |
2505 | TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) |
2506 | const; |
2507 | |
2508 | /// Type Query functions. If the type is an instance of the specified class, |
2509 | /// return the Type pointer for the underlying maximally pretty type. This |
2510 | /// is a member of ASTContext because this may need to do some amount of |
2511 | /// canonicalization, e.g. to move type qualifiers into the element type. |
2512 | const ArrayType *getAsArrayType(QualType T) const; |
2513 | const ConstantArrayType *getAsConstantArrayType(QualType T) const { |
2514 | return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T)); |
2515 | } |
2516 | const VariableArrayType *getAsVariableArrayType(QualType T) const { |
2517 | return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T)); |
2518 | } |
2519 | const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { |
2520 | return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T)); |
2521 | } |
2522 | const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) |
2523 | const { |
2524 | return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T)); |
2525 | } |
2526 | |
2527 | /// Return the innermost element type of an array type. |
2528 | /// |
2529 | /// For example, will return "int" for int[m][n] |
2530 | QualType getBaseElementType(const ArrayType *VAT) const; |
2531 | |
2532 | /// Return the innermost element type of a type (which needn't |
2533 | /// actually be an array type). |
2534 | QualType getBaseElementType(QualType QT) const; |
2535 | |
2536 | /// Return number of constant array elements. |
2537 | uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; |
2538 | |
2539 | /// Perform adjustment on the parameter type of a function. |
2540 | /// |
2541 | /// This routine adjusts the given parameter type @p T to the actual |
2542 | /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], |
2543 | /// C++ [dcl.fct]p3). The adjusted parameter type is returned. |
2544 | QualType getAdjustedParameterType(QualType T) const; |
2545 | |
2546 | /// Retrieve the parameter type as adjusted for use in the signature |
2547 | /// of a function, decaying array and function types and removing top-level |
2548 | /// cv-qualifiers. |
2549 | QualType getSignatureParameterType(QualType T) const; |
2550 | |
2551 | QualType getExceptionObjectType(QualType T) const; |
2552 | |
2553 | /// Return the properly qualified result of decaying the specified |
2554 | /// array type to a pointer. |
2555 | /// |
2556 | /// This operation is non-trivial when handling typedefs etc. The canonical |
2557 | /// type of \p T must be an array type, this returns a pointer to a properly |
2558 | /// qualified element of the array. |
2559 | /// |
2560 | /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. |
2561 | QualType getArrayDecayedType(QualType T) const; |
2562 | |
2563 | /// Return the type that \p PromotableType will promote to: C99 |
2564 | /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type. |
2565 | QualType getPromotedIntegerType(QualType PromotableType) const; |
2566 | |
2567 | /// Recurses in pointer/array types until it finds an Objective-C |
2568 | /// retainable type and returns its ownership. |
2569 | Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; |
2570 | |
2571 | /// Whether this is a promotable bitfield reference according |
2572 | /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). |
2573 | /// |
2574 | /// \returns the type this bit-field will promote to, or NULL if no |
2575 | /// promotion occurs. |
2576 | QualType isPromotableBitField(Expr *E) const; |
2577 | |
2578 | /// Return the highest ranked integer type, see C99 6.3.1.8p1. |
2579 | /// |
2580 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2581 | /// \p LHS < \p RHS, return -1. |
2582 | int getIntegerTypeOrder(QualType LHS, QualType RHS) const; |
2583 | |
2584 | /// Compare the rank of the two specified floating point types, |
2585 | /// ignoring the domain of the type (i.e. 'double' == '_Complex double'). |
2586 | /// |
2587 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2588 | /// \p LHS < \p RHS, return -1. |
2589 | int getFloatingTypeOrder(QualType LHS, QualType RHS) const; |
2590 | |
2591 | /// Compare the rank of two floating point types as above, but compare equal |
2592 | /// if both types have the same floating-point semantics on the target (i.e. |
2593 | /// long double and double on AArch64 will return 0). |
2594 | int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const; |
2595 | |
2596 | /// Return a real floating point or a complex type (based on |
2597 | /// \p typeDomain/\p typeSize). |
2598 | /// |
2599 | /// \param typeDomain a real floating point or complex type. |
2600 | /// \param typeSize a real floating point or complex type. |
2601 | QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, |
2602 | QualType typeDomain) const; |
2603 | |
2604 | unsigned getTargetAddressSpace(QualType T) const { |
2605 | return getTargetAddressSpace(T.getQualifiers()); |
2606 | } |
2607 | |
2608 | unsigned getTargetAddressSpace(Qualifiers Q) const { |
2609 | return getTargetAddressSpace(Q.getAddressSpace()); |
2610 | } |
2611 | |
2612 | unsigned getTargetAddressSpace(LangAS AS) const; |
2613 | |
2614 | LangAS getLangASForBuiltinAddressSpace(unsigned AS) const; |
2615 | |
2616 | /// Get target-dependent integer value for null pointer which is used for |
2617 | /// constant folding. |
2618 | uint64_t getTargetNullPointerValue(QualType QT) const; |
2619 | |
2620 | bool addressSpaceMapManglingFor(LangAS AS) const { |
2621 | return AddrSpaceMapMangling || isTargetAddressSpace(AS); |
2622 | } |
2623 | |
2624 | private: |
2625 | // Helper for integer ordering |
2626 | unsigned getIntegerRank(const Type *T) const; |
2627 | |
2628 | public: |
2629 | //===--------------------------------------------------------------------===// |
2630 | // Type Compatibility Predicates |
2631 | //===--------------------------------------------------------------------===// |
2632 | |
2633 | /// Compatibility predicates used to check assignment expressions. |
2634 | bool typesAreCompatible(QualType T1, QualType T2, |
2635 | bool CompareUnqualified = false); // C99 6.2.7p1 |
2636 | |
2637 | bool propertyTypesAreCompatible(QualType, QualType); |
2638 | bool typesAreBlockPointerCompatible(QualType, QualType); |
2639 | |
2640 | bool isObjCIdType(QualType T) const { |
2641 | return T == getObjCIdType(); |
2642 | } |
2643 | |
2644 | bool isObjCClassType(QualType T) const { |
2645 | return T == getObjCClassType(); |
2646 | } |
2647 | |
2648 | bool isObjCSelType(QualType T) const { |
2649 | return T == getObjCSelType(); |
2650 | } |
2651 | |
2652 | bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, |
2653 | const ObjCObjectPointerType *RHS, |
2654 | bool ForCompare); |
2655 | |
2656 | bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, |
2657 | const ObjCObjectPointerType *RHS); |
2658 | |
2659 | // Check the safety of assignment from LHS to RHS |
2660 | bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, |
2661 | const ObjCObjectPointerType *RHSOPT); |
2662 | bool canAssignObjCInterfaces(const ObjCObjectType *LHS, |
2663 | const ObjCObjectType *RHS); |
2664 | bool canAssignObjCInterfacesInBlockPointer( |
2665 | const ObjCObjectPointerType *LHSOPT, |
2666 | const ObjCObjectPointerType *RHSOPT, |
2667 | bool BlockReturnType); |
2668 | bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); |
2669 | QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, |
2670 | const ObjCObjectPointerType *RHSOPT); |
2671 | bool canBindObjCObjectType(QualType To, QualType From); |
2672 | |
2673 | // Functions for calculating composite types |
2674 | QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, |
2675 | bool Unqualified = false, bool BlockReturnType = false); |
2676 | QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, |
2677 | bool Unqualified = false, bool AllowCXX = false); |
2678 | QualType mergeFunctionParameterTypes(QualType, QualType, |
2679 | bool OfBlockPointer = false, |
2680 | bool Unqualified = false); |
2681 | QualType mergeTransparentUnionType(QualType, QualType, |
2682 | bool OfBlockPointer=false, |
2683 | bool Unqualified = false); |
2684 | |
2685 | QualType mergeObjCGCQualifiers(QualType, QualType); |
2686 | |
2687 | /// This function merges the ExtParameterInfo lists of two functions. It |
2688 | /// returns true if the lists are compatible. The merged list is returned in |
2689 | /// NewParamInfos. |
2690 | /// |
2691 | /// \param FirstFnType The type of the first function. |
2692 | /// |
2693 | /// \param SecondFnType The type of the second function. |
2694 | /// |
2695 | /// \param CanUseFirst This flag is set to true if the first function's |
2696 | /// ExtParameterInfo list can be used as the composite list of |
2697 | /// ExtParameterInfo. |
2698 | /// |
2699 | /// \param CanUseSecond This flag is set to true if the second function's |
2700 | /// ExtParameterInfo list can be used as the composite list of |
2701 | /// ExtParameterInfo. |
2702 | /// |
2703 | /// \param NewParamInfos The composite list of ExtParameterInfo. The list is |
2704 | /// empty if none of the flags are set. |
2705 | /// |
2706 | bool mergeExtParameterInfo( |
2707 | const FunctionProtoType *FirstFnType, |
2708 | const FunctionProtoType *SecondFnType, |
2709 | bool &CanUseFirst, bool &CanUseSecond, |
2710 | SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos); |
2711 | |
2712 | void ResetObjCLayout(const ObjCContainerDecl *CD); |
2713 | |
2714 | //===--------------------------------------------------------------------===// |
2715 | // Integer Predicates |
2716 | //===--------------------------------------------------------------------===// |
2717 | |
2718 | // The width of an integer, as defined in C99 6.2.6.2. This is the number |
2719 | // of bits in an integer type excluding any padding bits. |
2720 | unsigned getIntWidth(QualType T) const; |
2721 | |
2722 | // Per C99 6.2.5p6, for every signed integer type, there is a corresponding |
2723 | // unsigned integer type. This method takes a signed type, and returns the |
2724 | // corresponding unsigned integer type. |
2725 | // With the introduction of fixed point types in ISO N1169, this method also |
2726 | // accepts fixed point types and returns the corresponding unsigned type for |
2727 | // a given fixed point type. |
2728 | QualType getCorrespondingUnsignedType(QualType T) const; |
2729 | |
2730 | // Per ISO N1169, this method accepts fixed point types and returns the |
2731 | // corresponding saturated type for a given fixed point type. |
2732 | QualType getCorrespondingSaturatedType(QualType Ty) const; |
2733 | |
2734 | // This method accepts fixed point types and returns the corresponding signed |
2735 | // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned |
2736 | // fixed point types because there are unsigned integer types like bool and |
2737 | // char8_t that don't have signed equivalents. |
2738 | QualType getCorrespondingSignedFixedPointType(QualType Ty) const; |
2739 | |
2740 | //===--------------------------------------------------------------------===// |
2741 | // Integer Values |
2742 | //===--------------------------------------------------------------------===// |
2743 | |
2744 | /// Make an APSInt of the appropriate width and signedness for the |
2745 | /// given \p Value and integer \p Type. |
2746 | llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { |
2747 | // If Type is a signed integer type larger than 64 bits, we need to be sure |
2748 | // to sign extend Res appropriately. |
2749 | llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType()); |
2750 | Res = Value; |
2751 | unsigned Width = getIntWidth(Type); |
2752 | if (Width != Res.getBitWidth()) |
2753 | return Res.extOrTrunc(Width); |
2754 | return Res; |
2755 | } |
2756 | |
2757 | bool isSentinelNullExpr(const Expr *E); |
2758 | |
2759 | /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if |
2760 | /// none exists. |
2761 | ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); |
2762 | |
2763 | /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if |
2764 | /// none exists. |
2765 | ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); |
2766 | |
2767 | /// Return true if there is at least one \@implementation in the TU. |
2768 | bool AnyObjCImplementation() { |
2769 | return !ObjCImpls.empty(); |
2770 | } |
2771 | |
2772 | /// Set the implementation of ObjCInterfaceDecl. |
2773 | void setObjCImplementation(ObjCInterfaceDecl *IFaceD, |
2774 | ObjCImplementationDecl *ImplD); |
2775 | |
2776 | /// Set the implementation of ObjCCategoryDecl. |
2777 | void setObjCImplementation(ObjCCategoryDecl *CatD, |
2778 | ObjCCategoryImplDecl *ImplD); |
2779 | |
2780 | /// Get the duplicate declaration of a ObjCMethod in the same |
2781 | /// interface, or null if none exists. |
2782 | const ObjCMethodDecl * |
2783 | getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const; |
2784 | |
2785 | void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, |
2786 | const ObjCMethodDecl *Redecl); |
2787 | |
2788 | /// Returns the Objective-C interface that \p ND belongs to if it is |
2789 | /// an Objective-C method/property/ivar etc. that is part of an interface, |
2790 | /// otherwise returns null. |
2791 | const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const; |
2792 | |
2793 | /// Set the copy initialization expression of a block var decl. \p CanThrow |
2794 | /// indicates whether the copy expression can throw or not. |
2795 | void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow); |
2796 | |
2797 | /// Get the copy initialization expression of the VarDecl \p VD, or |
2798 | /// nullptr if none exists. |
2799 | BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const; |
2800 | |
2801 | /// Allocate an uninitialized TypeSourceInfo. |
2802 | /// |
2803 | /// The caller should initialize the memory held by TypeSourceInfo using |
2804 | /// the TypeLoc wrappers. |
2805 | /// |
2806 | /// \param T the type that will be the basis for type source info. This type |
2807 | /// should refer to how the declarator was written in source code, not to |
2808 | /// what type semantic analysis resolved the declarator to. |
2809 | /// |
2810 | /// \param Size the size of the type info to create, or 0 if the size |
2811 | /// should be calculated based on the type. |
2812 | TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; |
2813 | |
2814 | /// Allocate a TypeSourceInfo where all locations have been |
2815 | /// initialized to a given location, which defaults to the empty |
2816 | /// location. |
2817 | TypeSourceInfo * |
2818 | getTrivialTypeSourceInfo(QualType T, |
2819 | SourceLocation Loc = SourceLocation()) const; |
2820 | |
2821 | /// Add a deallocation callback that will be invoked when the |
2822 | /// ASTContext is destroyed. |
2823 | /// |
2824 | /// \param Callback A callback function that will be invoked on destruction. |
2825 | /// |
2826 | /// \param Data Pointer data that will be provided to the callback function |
2827 | /// when it is called. |
2828 | void AddDeallocation(void (*Callback)(void *), void *Data) const; |
2829 | |
2830 | /// If T isn't trivially destructible, calls AddDeallocation to register it |
2831 | /// for destruction. |
2832 | template <typename T> void addDestruction(T *Ptr) const { |
2833 | if (!std::is_trivially_destructible<T>::value) { |
2834 | auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); }; |
2835 | AddDeallocation(DestroyPtr, Ptr); |
2836 | } |
2837 | } |
2838 | |
2839 | GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const; |
2840 | GVALinkage GetGVALinkageForVariable(const VarDecl *VD); |
2841 | |
2842 | /// Determines if the decl can be CodeGen'ed or deserialized from PCH |
2843 | /// lazily, only when used; this is only relevant for function or file scoped |
2844 | /// var definitions. |
2845 | /// |
2846 | /// \returns true if the function/var must be CodeGen'ed/deserialized even if |
2847 | /// it is not used. |
2848 | bool DeclMustBeEmitted(const Decl *D); |
2849 | |
2850 | /// Visits all versions of a multiversioned function with the passed |
2851 | /// predicate. |
2852 | void forEachMultiversionedFunctionVersion( |
2853 | const FunctionDecl *FD, |
2854 | llvm::function_ref<void(FunctionDecl *)> Pred) const; |
2855 | |
2856 | const CXXConstructorDecl * |
2857 | getCopyConstructorForExceptionObject(CXXRecordDecl *RD); |
2858 | |
2859 | void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, |
2860 | CXXConstructorDecl *CD); |
2861 | |
2862 | void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND); |
2863 | |
2864 | TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD); |
2865 | |
2866 | void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD); |
2867 | |
2868 | DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD); |
2869 | |
2870 | void setManglingNumber(const NamedDecl *ND, unsigned Number); |
2871 | unsigned getManglingNumber(const NamedDecl *ND) const; |
2872 | |
2873 | void setStaticLocalNumber(const VarDecl *VD, unsigned Number); |
2874 | unsigned getStaticLocalNumber(const VarDecl *VD) const; |
2875 | |
2876 | /// Retrieve the context for computing mangling numbers in the given |
2877 | /// DeclContext. |
2878 | MangleNumberingContext &getManglingNumberContext(const DeclContext *DC); |
2879 | enum NeedExtraManglingDecl_t { NeedExtraManglingDecl }; |
2880 | MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t, |
2881 | const Decl *D); |
2882 | |
2883 | std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const; |
2884 | |
2885 | /// Used by ParmVarDecl to store on the side the |
2886 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2887 | void setParameterIndex(const ParmVarDecl *D, unsigned index); |
2888 | |
2889 | /// Used by ParmVarDecl to retrieve on the side the |
2890 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2891 | unsigned getParameterIndex(const ParmVarDecl *D) const; |
2892 | |
2893 | /// Return a string representing the human readable name for the specified |
2894 | /// function declaration or file name. Used by SourceLocExpr and |
2895 | /// PredefinedExpr to cache evaluated results. |
2896 | StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const; |
2897 | |
2898 | /// Return a declaration for the global GUID object representing the given |
2899 | /// GUID value. |
2900 | MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const; |
2901 | |
2902 | /// Return the template parameter object of the given type with the given |
2903 | /// value. |
2904 | TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T, |
2905 | const APValue &V) const; |
2906 | |
2907 | /// Parses the target attributes passed in, and returns only the ones that are |
2908 | /// valid feature names. |
2909 | ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const; |
2910 | |
2911 | void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, |
2912 | const FunctionDecl *) const; |
2913 | void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, |
2914 | GlobalDecl GD) const; |
2915 | |
2916 | //===--------------------------------------------------------------------===// |
2917 | // Statistics |
2918 | //===--------------------------------------------------------------------===// |
2919 | |
2920 | /// The number of implicitly-declared default constructors. |
2921 | unsigned NumImplicitDefaultConstructors = 0; |
2922 | |
2923 | /// The number of implicitly-declared default constructors for |
2924 | /// which declarations were built. |
2925 | unsigned NumImplicitDefaultConstructorsDeclared = 0; |
2926 | |
2927 | /// The number of implicitly-declared copy constructors. |
2928 | unsigned NumImplicitCopyConstructors = 0; |
2929 | |
2930 | /// The number of implicitly-declared copy constructors for |
2931 | /// which declarations were built. |
2932 | unsigned NumImplicitCopyConstructorsDeclared = 0; |
2933 | |
2934 | /// The number of implicitly-declared move constructors. |
2935 | unsigned NumImplicitMoveConstructors = 0; |
2936 | |
2937 | /// The number of implicitly-declared move constructors for |
2938 | /// which declarations were built. |
2939 | unsigned NumImplicitMoveConstructorsDeclared = 0; |
2940 | |
2941 | /// The number of implicitly-declared copy assignment operators. |
2942 | unsigned NumImplicitCopyAssignmentOperators = 0; |
2943 | |
2944 | /// The number of implicitly-declared copy assignment operators for |
2945 | /// which declarations were built. |
2946 | unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0; |
2947 | |
2948 | /// The number of implicitly-declared move assignment operators. |
2949 | unsigned NumImplicitMoveAssignmentOperators = 0; |
2950 | |
2951 | /// The number of implicitly-declared move assignment operators for |
2952 | /// which declarations were built. |
2953 | unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0; |
2954 | |
2955 | /// The number of implicitly-declared destructors. |
2956 | unsigned NumImplicitDestructors = 0; |
2957 | |
2958 | /// The number of implicitly-declared destructors for which |
2959 | /// declarations were built. |
2960 | unsigned NumImplicitDestructorsDeclared = 0; |
2961 | |
2962 | public: |
2963 | /// Initialize built-in types. |
2964 | /// |
2965 | /// This routine may only be invoked once for a given ASTContext object. |
2966 | /// It is normally invoked after ASTContext construction. |
2967 | /// |
2968 | /// \param Target The target |
2969 | void InitBuiltinTypes(const TargetInfo &Target, |
2970 | const TargetInfo *AuxTarget = nullptr); |
2971 | |
2972 | private: |
2973 | void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); |
2974 | |
2975 | class ObjCEncOptions { |
2976 | unsigned Bits; |
2977 | |
2978 | ObjCEncOptions(unsigned Bits) : Bits(Bits) {} |
2979 | |
2980 | public: |
2981 | ObjCEncOptions() : Bits(0) {} |
2982 | ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {} |
2983 | |
2984 | #define OPT_LIST(V) \ |
2985 | V(ExpandPointedToStructures, 0) \ |
2986 | V(ExpandStructures, 1) \ |
2987 | V(IsOutermostType, 2) \ |
2988 | V(EncodingProperty, 3) \ |
2989 | V(IsStructField, 4) \ |
2990 | V(EncodeBlockParameters, 5) \ |
2991 | V(EncodeClassNames, 6) \ |
2992 | |
2993 | #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; } |
2994 | OPT_LIST(V) |
2995 | #undef V |
2996 | |
2997 | #define V(N,I) bool N() const { return Bits & 1 << I; } |
2998 | OPT_LIST(V) |
2999 | #undef V |
3000 | |
3001 | #undef OPT_LIST |
3002 | |
3003 | LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const { |
3004 | return Bits & Mask.Bits; |
3005 | } |
3006 | |
3007 | LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions forComponentType() const { |
3008 | ObjCEncOptions Mask = ObjCEncOptions() |
3009 | .setIsOutermostType() |
3010 | .setIsStructField(); |
3011 | return Bits & ~Mask.Bits; |
3012 | } |
3013 | }; |
3014 | |
3015 | // Return the Objective-C type encoding for a given type. |
3016 | void getObjCEncodingForTypeImpl(QualType t, std::string &S, |
3017 | ObjCEncOptions Options, |
3018 | const FieldDecl *Field, |
3019 | QualType *NotEncodedT = nullptr) const; |
3020 | |
3021 | // Adds the encoding of the structure's members. |
3022 | void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, |
3023 | const FieldDecl *Field, |
3024 | bool includeVBases = true, |
3025 | QualType *NotEncodedT=nullptr) const; |
3026 | |
3027 | public: |
3028 | // Adds the encoding of a method parameter or return type. |
3029 | void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, |
3030 | QualType T, std::string& S, |
3031 | bool Extended) const; |
3032 | |
3033 | /// Returns true if this is an inline-initialized static data member |
3034 | /// which is treated as a definition for MSVC compatibility. |
3035 | bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const; |
3036 | |
3037 | enum class InlineVariableDefinitionKind { |
3038 | /// Not an inline variable. |
3039 | None, |
3040 | |
3041 | /// Weak definition of inline variable. |
3042 | Weak, |
3043 | |
3044 | /// Weak for now, might become strong later in this TU. |
3045 | WeakUnknown, |
3046 | |
3047 | /// Strong definition. |
3048 | Strong |
3049 | }; |
3050 | |
3051 | /// Determine whether a definition of this inline variable should |
3052 | /// be treated as a weak or strong definition. For compatibility with |
3053 | /// C++14 and before, for a constexpr static data member, if there is an |
3054 | /// out-of-line declaration of the member, we may promote it from weak to |
3055 | /// strong. |
3056 | InlineVariableDefinitionKind |
3057 | getInlineVariableDefinitionKind(const VarDecl *VD) const; |
3058 | |
3059 | private: |
3060 | friend class DeclarationNameTable; |
3061 | friend class DeclContext; |
3062 | |
3063 | const ASTRecordLayout & |
3064 | getObjCLayout(const ObjCInterfaceDecl *D, |
3065 | const ObjCImplementationDecl *Impl) const; |
3066 | |
3067 | /// A set of deallocations that should be performed when the |
3068 | /// ASTContext is destroyed. |
3069 | // FIXME: We really should have a better mechanism in the ASTContext to |
3070 | // manage running destructors for types which do variable sized allocation |
3071 | // within the AST. In some places we thread the AST bump pointer allocator |
3072 | // into the datastructures which avoids this mess during deallocation but is |
3073 | // wasteful of memory, and here we require a lot of error prone book keeping |
3074 | // in order to track and run destructors while we're tearing things down. |
3075 | using DeallocationFunctionsAndArguments = |
3076 | llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>; |
3077 | mutable DeallocationFunctionsAndArguments Deallocations; |
3078 | |
3079 | // FIXME: This currently contains the set of StoredDeclMaps used |
3080 | // by DeclContext objects. This probably should not be in ASTContext, |
3081 | // but we include it here so that ASTContext can quickly deallocate them. |
3082 | llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM; |
3083 | |
3084 | std::vector<Decl *> TraversalScope; |
3085 | |
3086 | std::unique_ptr<VTableContextBase> VTContext; |
3087 | |
3088 | void ReleaseDeclContextMaps(); |
3089 | |
3090 | public: |
3091 | enum PragmaSectionFlag : unsigned { |
3092 | PSF_None = 0, |
3093 | PSF_Read = 0x1, |
3094 | PSF_Write = 0x2, |
3095 | PSF_Execute = 0x4, |
3096 | PSF_Implicit = 0x8, |
3097 | PSF_ZeroInit = 0x10, |
3098 | PSF_Invalid = 0x80000000U, |
3099 | }; |
3100 | |
3101 | struct SectionInfo { |
3102 | NamedDecl *Decl; |
3103 | SourceLocation PragmaSectionLocation; |
3104 | int SectionFlags; |
3105 | |
3106 | SectionInfo() = default; |
3107 | SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation, |
3108 | int SectionFlags) |
3109 | : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation), |
3110 | SectionFlags(SectionFlags) {} |
3111 | }; |
3112 | |
3113 | llvm::StringMap<SectionInfo> SectionInfos; |
3114 | |
3115 | /// Return a new OMPTraitInfo object owned by this context. |
3116 | OMPTraitInfo &getNewOMPTraitInfo(); |
3117 | |
3118 | /// Whether a C++ static variable may be externalized. |
3119 | bool mayExternalizeStaticVar(const Decl *D) const; |
3120 | |
3121 | /// Whether a C++ static variable should be externalized. |
3122 | bool shouldExternalizeStaticVar(const Decl *D) const; |
3123 | |
3124 | StringRef getCUIDHash() const; |
3125 | |
3126 | private: |
3127 | /// All OMPTraitInfo objects live in this collection, one per |
3128 | /// `pragma omp [begin] declare variant` directive. |
3129 | SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector; |
3130 | }; |
3131 | |
3132 | /// Insertion operator for diagnostics. |
3133 | const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, |
3134 | const ASTContext::SectionInfo &Section); |
3135 | |
3136 | /// Utility function for constructing a nullary selector. |
3137 | inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) { |
3138 | IdentifierInfo* II = &Ctx.Idents.get(name); |
3139 | return Ctx.Selectors.getSelector(0, &II); |
3140 | } |
3141 | |
3142 | /// Utility function for constructing an unary selector. |
3143 | inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) { |
3144 | IdentifierInfo* II = &Ctx.Idents.get(name); |
3145 | return Ctx.Selectors.getSelector(1, &II); |
3146 | } |
3147 | |
3148 | } // namespace clang |
3149 | |
3150 | // operator new and delete aren't allowed inside namespaces. |
3151 | |
3152 | /// Placement new for using the ASTContext's allocator. |
3153 | /// |
3154 | /// This placement form of operator new uses the ASTContext's allocator for |
3155 | /// obtaining memory. |
3156 | /// |
3157 | /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h! |
3158 | /// Any changes here need to also be made there. |
3159 | /// |
3160 | /// We intentionally avoid using a nothrow specification here so that the calls |
3161 | /// to this operator will not perform a null check on the result -- the |
3162 | /// underlying allocator never returns null pointers. |
3163 | /// |
3164 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
3165 | /// @code |
3166 | /// // Default alignment (8) |
3167 | /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); |
3168 | /// // Specific alignment |
3169 | /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); |
3170 | /// @endcode |
3171 | /// Memory allocated through this placement new operator does not need to be |
3172 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
3173 | /// destroyed. Please note that you cannot use delete on the pointer. |
3174 | /// |
3175 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
3176 | /// @param C The ASTContext that provides the allocator. |
3177 | /// @param Alignment The alignment of the allocated memory (if the underlying |
3178 | /// allocator supports it). |
3179 | /// @return The allocated memory. Could be nullptr. |
3180 | inline void *operator new(size_t Bytes, const clang::ASTContext &C, |
3181 | size_t Alignment /* = 8 */) { |
3182 | return C.Allocate(Bytes, Alignment); |
3183 | } |
3184 | |
3185 | /// Placement delete companion to the new above. |
3186 | /// |
3187 | /// This operator is just a companion to the new above. There is no way of |
3188 | /// invoking it directly; see the new operator for more details. This operator |
3189 | /// is called implicitly by the compiler if a placement new expression using |
3190 | /// the ASTContext throws in the object constructor. |
3191 | inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { |
3192 | C.Deallocate(Ptr); |
3193 | } |
3194 | |
3195 | /// This placement form of operator new[] uses the ASTContext's allocator for |
3196 | /// obtaining memory. |
3197 | /// |
3198 | /// We intentionally avoid using a nothrow specification here so that the calls |
3199 | /// to this operator will not perform a null check on the result -- the |
3200 | /// underlying allocator never returns null pointers. |
3201 | /// |
3202 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
3203 | /// @code |
3204 | /// // Default alignment (8) |
3205 | /// char *data = new (Context) char[10]; |
3206 | /// // Specific alignment |
3207 | /// char *data = new (Context, 4) char[10]; |
3208 | /// @endcode |
3209 | /// Memory allocated through this placement new[] operator does not need to be |
3210 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
3211 | /// destroyed. Please note that you cannot use delete on the pointer. |
3212 | /// |
3213 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
3214 | /// @param C The ASTContext that provides the allocator. |
3215 | /// @param Alignment The alignment of the allocated memory (if the underlying |
3216 | /// allocator supports it). |
3217 | /// @return The allocated memory. Could be nullptr. |
3218 | inline void *operator new[](size_t Bytes, const clang::ASTContext& C, |
3219 | size_t Alignment /* = 8 */) { |
3220 | return C.Allocate(Bytes, Alignment); |
3221 | } |
3222 | |
3223 | /// Placement delete[] companion to the new[] above. |
3224 | /// |
3225 | /// This operator is just a companion to the new[] above. There is no way of |
3226 | /// invoking it directly; see the new[] operator for more details. This operator |
3227 | /// is called implicitly by the compiler if a placement new[] expression using |
3228 | /// the ASTContext throws in the object constructor. |
3229 | inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { |
3230 | C.Deallocate(Ptr); |
3231 | } |
3232 | |
3233 | /// Create the representation of a LazyGenerationalUpdatePtr. |
3234 | template <typename Owner, typename T, |
3235 | void (clang::ExternalASTSource::*Update)(Owner)> |
3236 | typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType |
3237 | clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue( |
3238 | const clang::ASTContext &Ctx, T Value) { |
3239 | // Note, this is implemented here so that ExternalASTSource.h doesn't need to |
3240 | // include ASTContext.h. We explicitly instantiate it for all relevant types |
3241 | // in ASTContext.cpp. |
3242 | if (auto *Source = Ctx.getExternalSource()) |
3243 | return new (Ctx) LazyData(Source, Value); |
3244 | return Value; |
3245 | } |
3246 | |
3247 | #endif // LLVM_CLANG_AST_ASTCONTEXT_H |