Bug Summary

File:tools/clang/lib/Sema/SemaChecking.cpp
Warning:line 5607, column 35
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaChecking.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp

1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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 extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/FormatString.h"
30#include "clang/AST/NSAPI.h"
31#include "clang/AST/NonTrivialTypeVisitor.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/UnresolvedSet.h"
38#include "clang/Basic/AddressSpaces.h"
39#include "clang/Basic/CharInfo.h"
40#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
50#include "clang/Basic/SyncScope.h"
51#include "clang/Basic/TargetBuiltins.h"
52#include "clang/Basic/TargetCXXABI.h"
53#include "clang/Basic/TargetInfo.h"
54#include "clang/Basic/TypeTraits.h"
55#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56#include "clang/Sema/Initialization.h"
57#include "clang/Sema/Lookup.h"
58#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
60#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
62#include "clang/Sema/SemaInternal.h"
63#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/STLExtras.h"
72#include "llvm/ADT/SmallBitVector.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallString.h"
75#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/ConvertUTF.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
86#include "llvm/Support/MathExtras.h"
87#include "llvm/Support/SaveAndRestore.h"
88#include "llvm/Support/raw_ostream.h"
89#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
98
99using namespace clang;
100using namespace sema;
101
102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
106}
107
108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
118
119 // Highlight all the excess arguments.
120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121 call->getArg(argCount - 1)->getEndLoc());
122
123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124 << 0 /*function call*/ << desiredArgCount << argCount
125 << call->getArg(1)->getSourceRange();
126}
127
128/// Check that the first argument to __builtin_annotation is an integer
129/// and the second argument is a non-wide string literal.
130static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131 if (checkArgCount(S, TheCall, 2))
132 return true;
133
134 // First argument should be an integer.
135 Expr *ValArg = TheCall->getArg(0);
136 QualType Ty = ValArg->getType();
137 if (!Ty->isIntegerType()) {
138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
140 return true;
141 }
142
143 // Second argument should be a constant string.
144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146 if (!Literal || !Literal->isAscii()) {
147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
149 return true;
150 }
151
152 TheCall->setType(Ty);
153 return false;
154}
155
156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
178/// Check that the argument to __builtin_addressof is a glvalue, and set the
179/// result type to the corresponding pointer type.
180static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181 if (checkArgCount(S, TheCall, 1))
182 return true;
183
184 ExprResult Arg(TheCall->getArg(0));
185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186 if (ResultType.isNull())
187 return true;
188
189 TheCall->setArg(0, Arg.get());
190 TheCall->setType(ResultType);
191 return false;
192}
193
194/// Check the number of arguments and set the result type to
195/// the argument type.
196static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197 if (checkArgCount(S, TheCall, 1))
198 return true;
199
200 TheCall->setType(TheCall->getArg(0)->getType());
201 return false;
202}
203
204static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205 if (checkArgCount(S, TheCall, 3))
206 return true;
207
208 // First two arguments should be integers.
209 for (unsigned I = 0; I < 2; ++I) {
210 ExprResult Arg = TheCall->getArg(I);
211 QualType Ty = Arg.get()->getType();
212 if (!Ty->isIntegerType()) {
213 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
214 << Ty << Arg.get()->getSourceRange();
215 return true;
216 }
217 InitializedEntity Entity = InitializedEntity::InitializeParameter(
218 S.getASTContext(), Ty, /*consume*/ false);
219 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220 if (Arg.isInvalid())
221 return true;
222 TheCall->setArg(I, Arg.get());
223 }
224
225 // Third argument should be a pointer to a non-const integer.
226 // IRGen correctly handles volatile, restrict, and address spaces, and
227 // the other qualifiers aren't possible.
228 {
229 ExprResult Arg = TheCall->getArg(2);
230 QualType Ty = Arg.get()->getType();
231 const auto *PtrTy = Ty->getAs<PointerType>();
232 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233 !PtrTy->getPointeeType().isConstQualified())) {
234 S.Diag(Arg.get()->getBeginLoc(),
235 diag::err_overflow_builtin_must_be_ptr_int)
236 << Ty << Arg.get()->getSourceRange();
237 return true;
238 }
239 InitializedEntity Entity = InitializedEntity::InitializeParameter(
240 S.getASTContext(), Ty, /*consume*/ false);
241 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242 if (Arg.isInvalid())
243 return true;
244 TheCall->setArg(2, Arg.get());
245 }
246 return false;
247}
248
249static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250 if (checkArgCount(S, BuiltinCall, 2))
251 return true;
252
253 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
254 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255 Expr *Call = BuiltinCall->getArg(0);
256 Expr *Chain = BuiltinCall->getArg(1);
257
258 if (Call->getStmtClass() != Stmt::CallExprClass) {
259 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260 << Call->getSourceRange();
261 return true;
262 }
263
264 auto CE = cast<CallExpr>(Call);
265 if (CE->getCallee()->getType()->isBlockPointerType()) {
266 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267 << Call->getSourceRange();
268 return true;
269 }
270
271 const Decl *TargetDecl = CE->getCalleeDecl();
272 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273 if (FD->getBuiltinID()) {
274 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275 << Call->getSourceRange();
276 return true;
277 }
278
279 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281 << Call->getSourceRange();
282 return true;
283 }
284
285 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286 if (ChainResult.isInvalid())
287 return true;
288 if (!ChainResult.get()->getType()->isPointerType()) {
289 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290 << Chain->getSourceRange();
291 return true;
292 }
293
294 QualType ReturnTy = CE->getCallReturnType(S.Context);
295 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296 QualType BuiltinTy = S.Context.getFunctionType(
297 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299
300 Builtin =
301 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302
303 BuiltinCall->setType(CE->getType());
304 BuiltinCall->setValueKind(CE->getValueKind());
305 BuiltinCall->setObjectKind(CE->getObjectKind());
306 BuiltinCall->setCallee(Builtin);
307 BuiltinCall->setArg(1, ChainResult.get());
308
309 return false;
310}
311
312/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313/// __builtin_*_chk function, then use the object size argument specified in the
314/// source. Otherwise, infer the object size using __builtin_object_size.
315void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316 CallExpr *TheCall) {
317 // FIXME: There are some more useful checks we could be doing here:
318 // - Analyze the format string of sprintf to see how much of buffer is used.
319 // - Evaluate strlen of strcpy arguments, use as object size.
320
321 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322 isConstantEvaluated())
323 return;
324
325 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326 if (!BuiltinID)
327 return;
328
329 unsigned DiagID = 0;
330 bool IsChkVariant = false;
331 unsigned SizeIndex, ObjectIndex;
332 switch (BuiltinID) {
333 default:
334 return;
335 case Builtin::BI__builtin___memcpy_chk:
336 case Builtin::BI__builtin___memmove_chk:
337 case Builtin::BI__builtin___memset_chk:
338// case Builtin::BI__builtin___strlcat_chk:
339// case Builtin::BI__builtin___strlcpy_chk:
340 case Builtin::BI__builtin___strncat_chk:
341 case Builtin::BI__builtin___strncpy_chk:
342 case Builtin::BI__builtin___stpncpy_chk:
343 case Builtin::BI__builtin___memccpy_chk: {
344 DiagID = diag::warn_builtin_chk_overflow;
345 IsChkVariant = true;
346 SizeIndex = TheCall->getNumArgs() - 2;
347 ObjectIndex = TheCall->getNumArgs() - 1;
348 break;
349 }
350
351 case Builtin::BI__builtin___snprintf_chk:
352 case Builtin::BI__builtin___vsnprintf_chk: {
353 DiagID = diag::warn_builtin_chk_overflow;
354 IsChkVariant = true;
355 SizeIndex = 1;
356 ObjectIndex = 3;
357 break;
358 }
359
360 case Builtin::BIstrncat:
361 case Builtin::BI__builtin_strncat:
362 case Builtin::BIstrncpy:
363 case Builtin::BI__builtin_strncpy:
364 case Builtin::BIstpncpy:
365 case Builtin::BI__builtin_stpncpy: {
366 // Whether these functions overflow depends on the runtime strlen of the
367 // string, not just the buffer size, so emitting the "always overflow"
368 // diagnostic isn't quite right. We should still diagnose passing a buffer
369 // size larger than the destination buffer though; this is a runtime abort
370 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371 DiagID = diag::warn_fortify_source_size_mismatch;
372 SizeIndex = TheCall->getNumArgs() - 1;
373 ObjectIndex = 0;
374 break;
375 }
376
377 case Builtin::BImemcpy:
378 case Builtin::BI__builtin_memcpy:
379 case Builtin::BImemmove:
380 case Builtin::BI__builtin_memmove:
381 case Builtin::BImemset:
382 case Builtin::BI__builtin_memset: {
383 DiagID = diag::warn_fortify_source_overflow;
384 SizeIndex = TheCall->getNumArgs() - 1;
385 ObjectIndex = 0;
386 break;
387 }
388 case Builtin::BIsnprintf:
389 case Builtin::BI__builtin_snprintf:
390 case Builtin::BIvsnprintf:
391 case Builtin::BI__builtin_vsnprintf: {
392 DiagID = diag::warn_fortify_source_size_mismatch;
393 SizeIndex = 1;
394 ObjectIndex = 0;
395 break;
396 }
397 }
398
399 llvm::APSInt ObjectSize;
400 // For __builtin___*_chk, the object size is explicitly provided by the caller
401 // (usually using __builtin_object_size). Use that value to check this call.
402 if (IsChkVariant) {
403 Expr::EvalResult Result;
404 Expr *SizeArg = TheCall->getArg(ObjectIndex);
405 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406 return;
407 ObjectSize = Result.Val.getInt();
408
409 // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410 } else {
411 // If the parameter has a pass_object_size attribute, then we should use its
412 // (potentially) more strict checking mode. Otherwise, conservatively assume
413 // type 0.
414 int BOSType = 0;
415 if (const auto *POS =
416 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417 BOSType = POS->getType();
418
419 Expr *ObjArg = TheCall->getArg(ObjectIndex);
420 uint64_t Result;
421 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422 return;
423 // Get the object size in the target's size_t width.
424 const TargetInfo &TI = getASTContext().getTargetInfo();
425 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427 }
428
429 // Evaluate the number of bytes of the object that this call will use.
430 Expr::EvalResult Result;
431 Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433 return;
434 llvm::APSInt UsedSize = Result.Val.getInt();
435
436 if (UsedSize.ule(ObjectSize))
437 return;
438
439 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440 // Skim off the details of whichever builtin was called to produce a better
441 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442 if (IsChkVariant) {
443 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445 } else if (FunctionName.startswith("__builtin_")) {
446 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447 }
448
449 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450 PDiag(DiagID)
451 << FunctionName << ObjectSize.toString(/*Radix=*/10)
452 << UsedSize.toString(/*Radix=*/10));
453}
454
455static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456 Scope::ScopeFlags NeededScopeFlags,
457 unsigned DiagID) {
458 // Scopes aren't available during instantiation. Fortunately, builtin
459 // functions cannot be template args so they cannot be formed through template
460 // instantiation. Therefore checking once during the parse is sufficient.
461 if (SemaRef.inTemplateInstantiation())
462 return false;
463
464 Scope *S = SemaRef.getCurScope();
465 while (S && !S->isSEHExceptScope())
466 S = S->getParent();
467 if (!S || !(S->getFlags() & NeededScopeFlags)) {
468 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470 << DRE->getDecl()->getIdentifier();
471 return true;
472 }
473
474 return false;
475}
476
477static inline bool isBlockPointer(Expr *Arg) {
478 return Arg->getType()->isBlockPointerType();
479}
480
481/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482/// void*, which is a requirement of device side enqueue.
483static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484 const BlockPointerType *BPT =
485 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486 ArrayRef<QualType> Params =
487 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
488 unsigned ArgCounter = 0;
489 bool IllegalParams = false;
490 // Iterate through the block parameters until either one is found that is not
491 // a local void*, or the block is valid.
492 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493 I != E; ++I, ++ArgCounter) {
494 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496 LangAS::opencl_local) {
497 // Get the location of the error. If a block literal has been passed
498 // (BlockExpr) then we can point straight to the offending argument,
499 // else we just point to the variable reference.
500 SourceLocation ErrorLoc;
501 if (isa<BlockExpr>(BlockArg)) {
502 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
503 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
504 } else if (isa<DeclRefExpr>(BlockArg)) {
505 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
506 }
507 S.Diag(ErrorLoc,
508 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509 IllegalParams = true;
510 }
511 }
512
513 return IllegalParams;
514}
515
516static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
518 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
520 return true;
521 }
522 return false;
523}
524
525static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526 if (checkArgCount(S, TheCall, 2))
527 return true;
528
529 if (checkOpenCLSubgroupExt(S, TheCall))
530 return true;
531
532 // First argument is an ndrange_t type.
533 Expr *NDRangeArg = TheCall->getArg(0);
534 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
535 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "'ndrange_t'";
537 return true;
538 }
539
540 Expr *BlockArg = TheCall->getArg(1);
541 if (!isBlockPointer(BlockArg)) {
542 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543 << TheCall->getDirectCallee() << "block";
544 return true;
545 }
546 return checkOpenCLBlockArgs(S, BlockArg);
547}
548
549/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550/// get_kernel_work_group_size
551/// and get_kernel_preferred_work_group_size_multiple builtin functions.
552static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553 if (checkArgCount(S, TheCall, 1))
554 return true;
555
556 Expr *BlockArg = TheCall->getArg(0);
557 if (!isBlockPointer(BlockArg)) {
558 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
560 return true;
561 }
562 return checkOpenCLBlockArgs(S, BlockArg);
563}
564
565/// Diagnose integer type and any valid implicit conversion to it.
566static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567 const QualType &IntType);
568
569static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
570 unsigned Start, unsigned End) {
571 bool IllegalParams = false;
572 for (unsigned I = Start; I <= End; ++I)
573 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574 S.Context.getSizeType());
575 return IllegalParams;
576}
577
578/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579/// 'local void*' parameter of passed block.
580static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581 Expr *BlockArg,
582 unsigned NumNonVarArgs) {
583 const BlockPointerType *BPT =
584 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585 unsigned NumBlockParams =
586 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
587 unsigned TotalNumArgs = TheCall->getNumArgs();
588
589 // For each argument passed to the block, a corresponding uint needs to
590 // be passed to describe the size of the local memory.
591 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
592 S.Diag(TheCall->getBeginLoc(),
593 diag::err_opencl_enqueue_kernel_local_size_args);
594 return true;
595 }
596
597 // Check that the sizes of the local memory are specified by integers.
598 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599 TotalNumArgs - 1);
600}
601
602/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603/// overload formats specified in Table 6.13.17.1.
604/// int enqueue_kernel(queue_t queue,
605/// kernel_enqueue_flags_t flags,
606/// const ndrange_t ndrange,
607/// void (^block)(void))
608/// int enqueue_kernel(queue_t queue,
609/// kernel_enqueue_flags_t flags,
610/// const ndrange_t ndrange,
611/// uint num_events_in_wait_list,
612/// clk_event_t *event_wait_list,
613/// clk_event_t *event_ret,
614/// void (^block)(void))
615/// int enqueue_kernel(queue_t queue,
616/// kernel_enqueue_flags_t flags,
617/// const ndrange_t ndrange,
618/// void (^block)(local void*, ...),
619/// uint size0, ...)
620/// int enqueue_kernel(queue_t queue,
621/// kernel_enqueue_flags_t flags,
622/// const ndrange_t ndrange,
623/// uint num_events_in_wait_list,
624/// clk_event_t *event_wait_list,
625/// clk_event_t *event_ret,
626/// void (^block)(local void*, ...),
627/// uint size0, ...)
628static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629 unsigned NumArgs = TheCall->getNumArgs();
630
631 if (NumArgs < 4) {
632 S.Diag(TheCall->getBeginLoc(),
633 diag::err_typecheck_call_too_few_args_at_least)
634 << 0 << 4 << NumArgs;
635 return true;
636 }
637
638 Expr *Arg0 = TheCall->getArg(0);
639 Expr *Arg1 = TheCall->getArg(1);
640 Expr *Arg2 = TheCall->getArg(2);
641 Expr *Arg3 = TheCall->getArg(3);
642
643 // First argument always needs to be a queue_t type.
644 if (!Arg0->getType()->isQueueT()) {
645 S.Diag(TheCall->getArg(0)->getBeginLoc(),
646 diag::err_opencl_builtin_expected_type)
647 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
648 return true;
649 }
650
651 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652 if (!Arg1->getType()->isIntegerType()) {
653 S.Diag(TheCall->getArg(1)->getBeginLoc(),
654 diag::err_opencl_builtin_expected_type)
655 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
656 return true;
657 }
658
659 // Third argument is always an ndrange_t type.
660 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
661 S.Diag(TheCall->getArg(2)->getBeginLoc(),
662 diag::err_opencl_builtin_expected_type)
663 << TheCall->getDirectCallee() << "'ndrange_t'";
664 return true;
665 }
666
667 // With four arguments, there is only one form that the function could be
668 // called in: no events and no variable arguments.
669 if (NumArgs == 4) {
670 // check that the last argument is the right block type.
671 if (!isBlockPointer(Arg3)) {
672 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
673 << TheCall->getDirectCallee() << "block";
674 return true;
675 }
676 // we have a block type, check the prototype
677 const BlockPointerType *BPT =
678 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
679 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
680 S.Diag(Arg3->getBeginLoc(),
681 diag::err_opencl_enqueue_kernel_blocks_no_args);
682 return true;
683 }
684 return false;
685 }
686 // we can have block + varargs.
687 if (isBlockPointer(Arg3))
688 return (checkOpenCLBlockArgs(S, Arg3) ||
689 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
690 // last two cases with either exactly 7 args or 7 args and varargs.
691 if (NumArgs >= 7) {
692 // check common block argument.
693 Expr *Arg6 = TheCall->getArg(6);
694 if (!isBlockPointer(Arg6)) {
695 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
696 << TheCall->getDirectCallee() << "block";
697 return true;
698 }
699 if (checkOpenCLBlockArgs(S, Arg6))
700 return true;
701
702 // Forth argument has to be any integer type.
703 if (!Arg3->getType()->isIntegerType()) {
704 S.Diag(TheCall->getArg(3)->getBeginLoc(),
705 diag::err_opencl_builtin_expected_type)
706 << TheCall->getDirectCallee() << "integer";
707 return true;
708 }
709 // check remaining common arguments.
710 Expr *Arg4 = TheCall->getArg(4);
711 Expr *Arg5 = TheCall->getArg(5);
712
713 // Fifth argument is always passed as a pointer to clk_event_t.
714 if (!Arg4->isNullPointerConstant(S.Context,
715 Expr::NPC_ValueDependentIsNotNull) &&
716 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
717 S.Diag(TheCall->getArg(4)->getBeginLoc(),
718 diag::err_opencl_builtin_expected_type)
719 << TheCall->getDirectCallee()
720 << S.Context.getPointerType(S.Context.OCLClkEventTy);
721 return true;
722 }
723
724 // Sixth argument is always passed as a pointer to clk_event_t.
725 if (!Arg5->isNullPointerConstant(S.Context,
726 Expr::NPC_ValueDependentIsNotNull) &&
727 !(Arg5->getType()->isPointerType() &&
728 Arg5->getType()->getPointeeType()->isClkEventT())) {
729 S.Diag(TheCall->getArg(5)->getBeginLoc(),
730 diag::err_opencl_builtin_expected_type)
731 << TheCall->getDirectCallee()
732 << S.Context.getPointerType(S.Context.OCLClkEventTy);
733 return true;
734 }
735
736 if (NumArgs == 7)
737 return false;
738
739 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
740 }
741
742 // None of the specific case has been detected, give generic error
743 S.Diag(TheCall->getBeginLoc(),
744 diag::err_opencl_enqueue_kernel_incorrect_args);
745 return true;
746}
747
748/// Returns OpenCL access qual.
749static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
750 return D->getAttr<OpenCLAccessAttr>();
751}
752
753/// Returns true if pipe element type is different from the pointer.
754static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
755 const Expr *Arg0 = Call->getArg(0);
756 // First argument type should always be pipe.
757 if (!Arg0->getType()->isPipeType()) {
758 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
759 << Call->getDirectCallee() << Arg0->getSourceRange();
760 return true;
761 }
762 OpenCLAccessAttr *AccessQual =
763 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
764 // Validates the access qualifier is compatible with the call.
765 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
766 // read_only and write_only, and assumed to be read_only if no qualifier is
767 // specified.
768 switch (Call->getDirectCallee()->getBuiltinID()) {
769 case Builtin::BIread_pipe:
770 case Builtin::BIreserve_read_pipe:
771 case Builtin::BIcommit_read_pipe:
772 case Builtin::BIwork_group_reserve_read_pipe:
773 case Builtin::BIsub_group_reserve_read_pipe:
774 case Builtin::BIwork_group_commit_read_pipe:
775 case Builtin::BIsub_group_commit_read_pipe:
776 if (!(!AccessQual || AccessQual->isReadOnly())) {
777 S.Diag(Arg0->getBeginLoc(),
778 diag::err_opencl_builtin_pipe_invalid_access_modifier)
779 << "read_only" << Arg0->getSourceRange();
780 return true;
781 }
782 break;
783 case Builtin::BIwrite_pipe:
784 case Builtin::BIreserve_write_pipe:
785 case Builtin::BIcommit_write_pipe:
786 case Builtin::BIwork_group_reserve_write_pipe:
787 case Builtin::BIsub_group_reserve_write_pipe:
788 case Builtin::BIwork_group_commit_write_pipe:
789 case Builtin::BIsub_group_commit_write_pipe:
790 if (!(AccessQual && AccessQual->isWriteOnly())) {
791 S.Diag(Arg0->getBeginLoc(),
792 diag::err_opencl_builtin_pipe_invalid_access_modifier)
793 << "write_only" << Arg0->getSourceRange();
794 return true;
795 }
796 break;
797 default:
798 break;
799 }
800 return false;
801}
802
803/// Returns true if pipe element type is different from the pointer.
804static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
805 const Expr *Arg0 = Call->getArg(0);
806 const Expr *ArgIdx = Call->getArg(Idx);
807 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
808 const QualType EltTy = PipeTy->getElementType();
809 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
810 // The Idx argument should be a pointer and the type of the pointer and
811 // the type of pipe element should also be the same.
812 if (!ArgTy ||
813 !S.Context.hasSameType(
814 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
815 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
816 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
817 << ArgIdx->getType() << ArgIdx->getSourceRange();
818 return true;
819 }
820 return false;
821}
822
823// Performs semantic analysis for the read/write_pipe call.
824// \param S Reference to the semantic analyzer.
825// \param Call A pointer to the builtin call.
826// \return True if a semantic error has been found, false otherwise.
827static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
828 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829 // functions have two forms.
830 switch (Call->getNumArgs()) {
831 case 2:
832 if (checkOpenCLPipeArg(S, Call))
833 return true;
834 // The call with 2 arguments should be
835 // read/write_pipe(pipe T, T*).
836 // Check packet type T.
837 if (checkOpenCLPipePacketType(S, Call, 1))
838 return true;
839 break;
840
841 case 4: {
842 if (checkOpenCLPipeArg(S, Call))
843 return true;
844 // The call with 4 arguments should be
845 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846 // Check reserve_id_t.
847 if (!Call->getArg(1)->getType()->isReserveIDT()) {
848 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
849 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
850 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
851 return true;
852 }
853
854 // Check the index.
855 const Expr *Arg2 = Call->getArg(2);
856 if (!Arg2->getType()->isIntegerType() &&
857 !Arg2->getType()->isUnsignedIntegerType()) {
858 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
859 << Call->getDirectCallee() << S.Context.UnsignedIntTy
860 << Arg2->getType() << Arg2->getSourceRange();
861 return true;
862 }
863
864 // Check packet type T.
865 if (checkOpenCLPipePacketType(S, Call, 3))
866 return true;
867 } break;
868 default:
869 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
870 << Call->getDirectCallee() << Call->getSourceRange();
871 return true;
872 }
873
874 return false;
875}
876
877// Performs a semantic analysis on the {work_group_/sub_group_
878// /_}reserve_{read/write}_pipe
879// \param S Reference to the semantic analyzer.
880// \param Call The call to the builtin function to be analyzed.
881// \return True if a semantic error was found, false otherwise.
882static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
883 if (checkArgCount(S, Call, 2))
884 return true;
885
886 if (checkOpenCLPipeArg(S, Call))
887 return true;
888
889 // Check the reserve size.
890 if (!Call->getArg(1)->getType()->isIntegerType() &&
891 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
892 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
893 << Call->getDirectCallee() << S.Context.UnsignedIntTy
894 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
895 return true;
896 }
897
898 // Since return type of reserve_read/write_pipe built-in function is
899 // reserve_id_t, which is not defined in the builtin def file , we used int
900 // as return type and need to override the return type of these functions.
901 Call->setType(S.Context.OCLReserveIDTy);
902
903 return false;
904}
905
906// Performs a semantic analysis on {work_group_/sub_group_
907// /_}commit_{read/write}_pipe
908// \param S Reference to the semantic analyzer.
909// \param Call The call to the builtin function to be analyzed.
910// \return True if a semantic error was found, false otherwise.
911static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
912 if (checkArgCount(S, Call, 2))
913 return true;
914
915 if (checkOpenCLPipeArg(S, Call))
916 return true;
917
918 // Check reserve_id_t.
919 if (!Call->getArg(1)->getType()->isReserveIDT()) {
920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
921 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
922 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
923 return true;
924 }
925
926 return false;
927}
928
929// Performs a semantic analysis on the call to built-in Pipe
930// Query Functions.
931// \param S Reference to the semantic analyzer.
932// \param Call The call to the builtin function to be analyzed.
933// \return True if a semantic error was found, false otherwise.
934static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
935 if (checkArgCount(S, Call, 1))
936 return true;
937
938 if (!Call->getArg(0)->getType()->isPipeType()) {
939 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
940 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
941 return true;
942 }
943
944 return false;
945}
946
947// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
948// Performs semantic analysis for the to_global/local/private call.
949// \param S Reference to the semantic analyzer.
950// \param BuiltinID ID of the builtin function.
951// \param Call A pointer to the builtin call.
952// \return True if a semantic error has been found, false otherwise.
953static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
954 CallExpr *Call) {
955 if (Call->getNumArgs() != 1) {
956 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
957 << Call->getDirectCallee() << Call->getSourceRange();
958 return true;
959 }
960
961 auto RT = Call->getArg(0)->getType();
962 if (!RT->isPointerType() || RT->getPointeeType()
963 .getAddressSpace() == LangAS::opencl_constant) {
964 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
965 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966 return true;
967 }
968
969 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
970 S.Diag(Call->getArg(0)->getBeginLoc(),
971 diag::warn_opencl_generic_address_space_arg)
972 << Call->getDirectCallee()->getNameInfo().getAsString()
973 << Call->getArg(0)->getSourceRange();
974 }
975
976 RT = RT->getPointeeType();
977 auto Qual = RT.getQualifiers();
978 switch (BuiltinID) {
979 case Builtin::BIto_global:
980 Qual.setAddressSpace(LangAS::opencl_global);
981 break;
982 case Builtin::BIto_local:
983 Qual.setAddressSpace(LangAS::opencl_local);
984 break;
985 case Builtin::BIto_private:
986 Qual.setAddressSpace(LangAS::opencl_private);
987 break;
988 default:
989 llvm_unreachable("Invalid builtin function")::llvm::llvm_unreachable_internal("Invalid builtin function",
"/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 989)
;
990 }
991 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992 RT.getUnqualifiedType(), Qual)));
993
994 return false;
995}
996
997static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
998 if (checkArgCount(S, TheCall, 1))
999 return ExprError();
1000
1001 // Compute __builtin_launder's parameter type from the argument.
1002 // The parameter type is:
1003 // * The type of the argument if it's not an array or function type,
1004 // Otherwise,
1005 // * The decayed argument type.
1006 QualType ParamTy = [&]() {
1007 QualType ArgTy = TheCall->getArg(0)->getType();
1008 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1009 return S.Context.getPointerType(Ty->getElementType());
1010 if (ArgTy->isFunctionType()) {
1011 return S.Context.getPointerType(ArgTy);
1012 }
1013 return ArgTy;
1014 }();
1015
1016 TheCall->setType(ParamTy);
1017
1018 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1019 if (!ParamTy->isPointerType())
1020 return 0;
1021 if (ParamTy->isFunctionPointerType())
1022 return 1;
1023 if (ParamTy->isVoidPointerType())
1024 return 2;
1025 return llvm::Optional<unsigned>{};
1026 }();
1027 if (DiagSelect.hasValue()) {
1028 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1029 << DiagSelect.getValue() << TheCall->getSourceRange();
1030 return ExprError();
1031 }
1032
1033 // We either have an incomplete class type, or we have a class template
1034 // whose instantiation has not been forced. Example:
1035 //
1036 // template <class T> struct Foo { T value; };
1037 // Foo<int> *p = nullptr;
1038 // auto *d = __builtin_launder(p);
1039 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1040 diag::err_incomplete_type))
1041 return ExprError();
1042
1043 assert(ParamTy->getPointeeType()->isObjectType() &&((ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case"
) ? static_cast<void> (0) : __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1044, __PRETTY_FUNCTION__))
1044 "Unhandled non-object pointer case")((ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case"
) ? static_cast<void> (0) : __assert_fail ("ParamTy->getPointeeType()->isObjectType() && \"Unhandled non-object pointer case\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1044, __PRETTY_FUNCTION__))
;
1045
1046 InitializedEntity Entity =
1047 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1048 ExprResult Arg =
1049 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1050 if (Arg.isInvalid())
1051 return ExprError();
1052 TheCall->setArg(0, Arg.get());
1053
1054 return TheCall;
1055}
1056
1057// Emit an error and return true if the current architecture is not in the list
1058// of supported architectures.
1059static bool
1060CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1061 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1062 llvm::Triple::ArchType CurArch =
1063 S.getASTContext().getTargetInfo().getTriple().getArch();
1064 if (llvm::is_contained(SupportedArchs, CurArch))
1065 return false;
1066 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1067 << TheCall->getSourceRange();
1068 return true;
1069}
1070
1071ExprResult
1072Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1073 CallExpr *TheCall) {
1074 ExprResult TheCallResult(TheCall);
1075
1076 // Find out if any arguments are required to be integer constant expressions.
1077 unsigned ICEArguments = 0;
1078 ASTContext::GetBuiltinTypeError Error;
1079 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1080 if (Error != ASTContext::GE_None)
1081 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
1082
1083 // If any arguments are required to be ICE's, check and diagnose.
1084 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1085 // Skip arguments not required to be ICE's.
1086 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1087
1088 llvm::APSInt Result;
1089 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090 return true;
1091 ICEArguments &= ~(1 << ArgNo);
1092 }
1093
1094 switch (BuiltinID) {
1095 case Builtin::BI__builtin___CFStringMakeConstantString:
1096 assert(TheCall->getNumArgs() == 1 &&((TheCall->getNumArgs() == 1 && "Wrong # arguments to builtin CFStringMakeConstantString"
) ? static_cast<void> (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1097, __PRETTY_FUNCTION__))
1097 "Wrong # arguments to builtin CFStringMakeConstantString")((TheCall->getNumArgs() == 1 && "Wrong # arguments to builtin CFStringMakeConstantString"
) ? static_cast<void> (0) : __assert_fail ("TheCall->getNumArgs() == 1 && \"Wrong # arguments to builtin CFStringMakeConstantString\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1097, __PRETTY_FUNCTION__))
;
1098 if (CheckObjCString(TheCall->getArg(0)))
1099 return ExprError();
1100 break;
1101 case Builtin::BI__builtin_ms_va_start:
1102 case Builtin::BI__builtin_stdarg_start:
1103 case Builtin::BI__builtin_va_start:
1104 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1105 return ExprError();
1106 break;
1107 case Builtin::BI__va_start: {
1108 switch (Context.getTargetInfo().getTriple().getArch()) {
1109 case llvm::Triple::aarch64:
1110 case llvm::Triple::arm:
1111 case llvm::Triple::thumb:
1112 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1113 return ExprError();
1114 break;
1115 default:
1116 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1117 return ExprError();
1118 break;
1119 }
1120 break;
1121 }
1122
1123 // The acquire, release, and no fence variants are ARM and AArch64 only.
1124 case Builtin::BI_interlockedbittestandset_acq:
1125 case Builtin::BI_interlockedbittestandset_rel:
1126 case Builtin::BI_interlockedbittestandset_nf:
1127 case Builtin::BI_interlockedbittestandreset_acq:
1128 case Builtin::BI_interlockedbittestandreset_rel:
1129 case Builtin::BI_interlockedbittestandreset_nf:
1130 if (CheckBuiltinTargetSupport(
1131 *this, BuiltinID, TheCall,
1132 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1133 return ExprError();
1134 break;
1135
1136 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1137 case Builtin::BI_bittest64:
1138 case Builtin::BI_bittestandcomplement64:
1139 case Builtin::BI_bittestandreset64:
1140 case Builtin::BI_bittestandset64:
1141 case Builtin::BI_interlockedbittestandreset64:
1142 case Builtin::BI_interlockedbittestandset64:
1143 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1144 {llvm::Triple::x86_64, llvm::Triple::arm,
1145 llvm::Triple::thumb, llvm::Triple::aarch64}))
1146 return ExprError();
1147 break;
1148
1149 case Builtin::BI__builtin_isgreater:
1150 case Builtin::BI__builtin_isgreaterequal:
1151 case Builtin::BI__builtin_isless:
1152 case Builtin::BI__builtin_islessequal:
1153 case Builtin::BI__builtin_islessgreater:
1154 case Builtin::BI__builtin_isunordered:
1155 if (SemaBuiltinUnorderedCompare(TheCall))
1156 return ExprError();
1157 break;
1158 case Builtin::BI__builtin_fpclassify:
1159 if (SemaBuiltinFPClassification(TheCall, 6))
1160 return ExprError();
1161 break;
1162 case Builtin::BI__builtin_isfinite:
1163 case Builtin::BI__builtin_isinf:
1164 case Builtin::BI__builtin_isinf_sign:
1165 case Builtin::BI__builtin_isnan:
1166 case Builtin::BI__builtin_isnormal:
1167 case Builtin::BI__builtin_signbit:
1168 case Builtin::BI__builtin_signbitf:
1169 case Builtin::BI__builtin_signbitl:
1170 if (SemaBuiltinFPClassification(TheCall, 1))
1171 return ExprError();
1172 break;
1173 case Builtin::BI__builtin_shufflevector:
1174 return SemaBuiltinShuffleVector(TheCall);
1175 // TheCall will be freed by the smart pointer here, but that's fine, since
1176 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1177 case Builtin::BI__builtin_prefetch:
1178 if (SemaBuiltinPrefetch(TheCall))
1179 return ExprError();
1180 break;
1181 case Builtin::BI__builtin_alloca_with_align:
1182 if (SemaBuiltinAllocaWithAlign(TheCall))
1183 return ExprError();
1184 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1185 case Builtin::BI__builtin_alloca:
1186 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187 << TheCall->getDirectCallee();
1188 break;
1189 case Builtin::BI__assume:
1190 case Builtin::BI__builtin_assume:
1191 if (SemaBuiltinAssume(TheCall))
1192 return ExprError();
1193 break;
1194 case Builtin::BI__builtin_assume_aligned:
1195 if (SemaBuiltinAssumeAligned(TheCall))
1196 return ExprError();
1197 break;
1198 case Builtin::BI__builtin_dynamic_object_size:
1199 case Builtin::BI__builtin_object_size:
1200 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1201 return ExprError();
1202 break;
1203 case Builtin::BI__builtin_longjmp:
1204 if (SemaBuiltinLongjmp(TheCall))
1205 return ExprError();
1206 break;
1207 case Builtin::BI__builtin_setjmp:
1208 if (SemaBuiltinSetjmp(TheCall))
1209 return ExprError();
1210 break;
1211 case Builtin::BI_setjmp:
1212 case Builtin::BI_setjmpex:
1213 if (checkArgCount(*this, TheCall, 1))
1214 return true;
1215 break;
1216 case Builtin::BI__builtin_classify_type:
1217 if (checkArgCount(*this, TheCall, 1)) return true;
1218 TheCall->setType(Context.IntTy);
1219 break;
1220 case Builtin::BI__builtin_constant_p: {
1221 if (checkArgCount(*this, TheCall, 1)) return true;
1222 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223 if (Arg.isInvalid()) return true;
1224 TheCall->setArg(0, Arg.get());
1225 TheCall->setType(Context.IntTy);
1226 break;
1227 }
1228 case Builtin::BI__builtin_launder:
1229 return SemaBuiltinLaunder(*this, TheCall);
1230 case Builtin::BI__sync_fetch_and_add:
1231 case Builtin::BI__sync_fetch_and_add_1:
1232 case Builtin::BI__sync_fetch_and_add_2:
1233 case Builtin::BI__sync_fetch_and_add_4:
1234 case Builtin::BI__sync_fetch_and_add_8:
1235 case Builtin::BI__sync_fetch_and_add_16:
1236 case Builtin::BI__sync_fetch_and_sub:
1237 case Builtin::BI__sync_fetch_and_sub_1:
1238 case Builtin::BI__sync_fetch_and_sub_2:
1239 case Builtin::BI__sync_fetch_and_sub_4:
1240 case Builtin::BI__sync_fetch_and_sub_8:
1241 case Builtin::BI__sync_fetch_and_sub_16:
1242 case Builtin::BI__sync_fetch_and_or:
1243 case Builtin::BI__sync_fetch_and_or_1:
1244 case Builtin::BI__sync_fetch_and_or_2:
1245 case Builtin::BI__sync_fetch_and_or_4:
1246 case Builtin::BI__sync_fetch_and_or_8:
1247 case Builtin::BI__sync_fetch_and_or_16:
1248 case Builtin::BI__sync_fetch_and_and:
1249 case Builtin::BI__sync_fetch_and_and_1:
1250 case Builtin::BI__sync_fetch_and_and_2:
1251 case Builtin::BI__sync_fetch_and_and_4:
1252 case Builtin::BI__sync_fetch_and_and_8:
1253 case Builtin::BI__sync_fetch_and_and_16:
1254 case Builtin::BI__sync_fetch_and_xor:
1255 case Builtin::BI__sync_fetch_and_xor_1:
1256 case Builtin::BI__sync_fetch_and_xor_2:
1257 case Builtin::BI__sync_fetch_and_xor_4:
1258 case Builtin::BI__sync_fetch_and_xor_8:
1259 case Builtin::BI__sync_fetch_and_xor_16:
1260 case Builtin::BI__sync_fetch_and_nand:
1261 case Builtin::BI__sync_fetch_and_nand_1:
1262 case Builtin::BI__sync_fetch_and_nand_2:
1263 case Builtin::BI__sync_fetch_and_nand_4:
1264 case Builtin::BI__sync_fetch_and_nand_8:
1265 case Builtin::BI__sync_fetch_and_nand_16:
1266 case Builtin::BI__sync_add_and_fetch:
1267 case Builtin::BI__sync_add_and_fetch_1:
1268 case Builtin::BI__sync_add_and_fetch_2:
1269 case Builtin::BI__sync_add_and_fetch_4:
1270 case Builtin::BI__sync_add_and_fetch_8:
1271 case Builtin::BI__sync_add_and_fetch_16:
1272 case Builtin::BI__sync_sub_and_fetch:
1273 case Builtin::BI__sync_sub_and_fetch_1:
1274 case Builtin::BI__sync_sub_and_fetch_2:
1275 case Builtin::BI__sync_sub_and_fetch_4:
1276 case Builtin::BI__sync_sub_and_fetch_8:
1277 case Builtin::BI__sync_sub_and_fetch_16:
1278 case Builtin::BI__sync_and_and_fetch:
1279 case Builtin::BI__sync_and_and_fetch_1:
1280 case Builtin::BI__sync_and_and_fetch_2:
1281 case Builtin::BI__sync_and_and_fetch_4:
1282 case Builtin::BI__sync_and_and_fetch_8:
1283 case Builtin::BI__sync_and_and_fetch_16:
1284 case Builtin::BI__sync_or_and_fetch:
1285 case Builtin::BI__sync_or_and_fetch_1:
1286 case Builtin::BI__sync_or_and_fetch_2:
1287 case Builtin::BI__sync_or_and_fetch_4:
1288 case Builtin::BI__sync_or_and_fetch_8:
1289 case Builtin::BI__sync_or_and_fetch_16:
1290 case Builtin::BI__sync_xor_and_fetch:
1291 case Builtin::BI__sync_xor_and_fetch_1:
1292 case Builtin::BI__sync_xor_and_fetch_2:
1293 case Builtin::BI__sync_xor_and_fetch_4:
1294 case Builtin::BI__sync_xor_and_fetch_8:
1295 case Builtin::BI__sync_xor_and_fetch_16:
1296 case Builtin::BI__sync_nand_and_fetch:
1297 case Builtin::BI__sync_nand_and_fetch_1:
1298 case Builtin::BI__sync_nand_and_fetch_2:
1299 case Builtin::BI__sync_nand_and_fetch_4:
1300 case Builtin::BI__sync_nand_and_fetch_8:
1301 case Builtin::BI__sync_nand_and_fetch_16:
1302 case Builtin::BI__sync_val_compare_and_swap:
1303 case Builtin::BI__sync_val_compare_and_swap_1:
1304 case Builtin::BI__sync_val_compare_and_swap_2:
1305 case Builtin::BI__sync_val_compare_and_swap_4:
1306 case Builtin::BI__sync_val_compare_and_swap_8:
1307 case Builtin::BI__sync_val_compare_and_swap_16:
1308 case Builtin::BI__sync_bool_compare_and_swap:
1309 case Builtin::BI__sync_bool_compare_and_swap_1:
1310 case Builtin::BI__sync_bool_compare_and_swap_2:
1311 case Builtin::BI__sync_bool_compare_and_swap_4:
1312 case Builtin::BI__sync_bool_compare_and_swap_8:
1313 case Builtin::BI__sync_bool_compare_and_swap_16:
1314 case Builtin::BI__sync_lock_test_and_set:
1315 case Builtin::BI__sync_lock_test_and_set_1:
1316 case Builtin::BI__sync_lock_test_and_set_2:
1317 case Builtin::BI__sync_lock_test_and_set_4:
1318 case Builtin::BI__sync_lock_test_and_set_8:
1319 case Builtin::BI__sync_lock_test_and_set_16:
1320 case Builtin::BI__sync_lock_release:
1321 case Builtin::BI__sync_lock_release_1:
1322 case Builtin::BI__sync_lock_release_2:
1323 case Builtin::BI__sync_lock_release_4:
1324 case Builtin::BI__sync_lock_release_8:
1325 case Builtin::BI__sync_lock_release_16:
1326 case Builtin::BI__sync_swap:
1327 case Builtin::BI__sync_swap_1:
1328 case Builtin::BI__sync_swap_2:
1329 case Builtin::BI__sync_swap_4:
1330 case Builtin::BI__sync_swap_8:
1331 case Builtin::BI__sync_swap_16:
1332 return SemaBuiltinAtomicOverloaded(TheCallResult);
1333 case Builtin::BI__sync_synchronize:
1334 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335 << TheCall->getCallee()->getSourceRange();
1336 break;
1337 case Builtin::BI__builtin_nontemporal_load:
1338 case Builtin::BI__builtin_nontemporal_store:
1339 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1340#define BUILTIN(ID, TYPE, ATTRS)
1341#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1342 case Builtin::BI##ID: \
1343 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1344#include "clang/Basic/Builtins.def"
1345 case Builtin::BI__annotation:
1346 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1347 return ExprError();
1348 break;
1349 case Builtin::BI__builtin_annotation:
1350 if (SemaBuiltinAnnotation(*this, TheCall))
1351 return ExprError();
1352 break;
1353 case Builtin::BI__builtin_addressof:
1354 if (SemaBuiltinAddressof(*this, TheCall))
1355 return ExprError();
1356 break;
1357 case Builtin::BI__builtin_add_overflow:
1358 case Builtin::BI__builtin_sub_overflow:
1359 case Builtin::BI__builtin_mul_overflow:
1360 if (SemaBuiltinOverflow(*this, TheCall))
1361 return ExprError();
1362 break;
1363 case Builtin::BI__builtin_operator_new:
1364 case Builtin::BI__builtin_operator_delete: {
1365 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1366 ExprResult Res =
1367 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1368 if (Res.isInvalid())
1369 CorrectDelayedTyposInExpr(TheCallResult.get());
1370 return Res;
1371 }
1372 case Builtin::BI__builtin_dump_struct: {
1373 // We first want to ensure we are called with 2 arguments
1374 if (checkArgCount(*this, TheCall, 2))
1375 return ExprError();
1376 // Ensure that the first argument is of type 'struct XX *'
1377 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1378 const QualType PtrArgType = PtrArg->getType();
1379 if (!PtrArgType->isPointerType() ||
1380 !PtrArgType->getPointeeType()->isRecordType()) {
1381 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1382 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383 << "structure pointer";
1384 return ExprError();
1385 }
1386
1387 // Ensure that the second argument is of type 'FunctionType'
1388 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1389 const QualType FnPtrArgType = FnPtrArg->getType();
1390 if (!FnPtrArgType->isPointerType()) {
1391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393 << FnPtrArgType << "'int (*)(const char *, ...)'";
1394 return ExprError();
1395 }
1396
1397 const auto *FuncType =
1398 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399
1400 if (!FuncType) {
1401 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403 << FnPtrArgType << "'int (*)(const char *, ...)'";
1404 return ExprError();
1405 }
1406
1407 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408 if (!FT->getNumParams()) {
1409 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1410 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1411 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1412 return ExprError();
1413 }
1414 QualType PT = FT->getParamType(0);
1415 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1416 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1417 !PT->getPointeeType().isConstQualified()) {
1418 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1419 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1420 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1421 return ExprError();
1422 }
1423 }
1424
1425 TheCall->setType(Context.IntTy);
1426 break;
1427 }
1428 case Builtin::BI__builtin_preserve_access_index:
1429 if (SemaBuiltinPreserveAI(*this, TheCall))
1430 return ExprError();
1431 break;
1432 case Builtin::BI__builtin_call_with_static_chain:
1433 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434 return ExprError();
1435 break;
1436 case Builtin::BI__exception_code:
1437 case Builtin::BI_exception_code:
1438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439 diag::err_seh___except_block))
1440 return ExprError();
1441 break;
1442 case Builtin::BI__exception_info:
1443 case Builtin::BI_exception_info:
1444 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445 diag::err_seh___except_filter))
1446 return ExprError();
1447 break;
1448 case Builtin::BI__GetExceptionInfo:
1449 if (checkArgCount(*this, TheCall, 1))
1450 return ExprError();
1451
1452 if (CheckCXXThrowOperand(
1453 TheCall->getBeginLoc(),
1454 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455 TheCall))
1456 return ExprError();
1457
1458 TheCall->setType(Context.VoidPtrTy);
1459 break;
1460 // OpenCL v2.0, s6.13.16 - Pipe functions
1461 case Builtin::BIread_pipe:
1462 case Builtin::BIwrite_pipe:
1463 // Since those two functions are declared with var args, we need a semantic
1464 // check for the argument.
1465 if (SemaBuiltinRWPipe(*this, TheCall))
1466 return ExprError();
1467 break;
1468 case Builtin::BIreserve_read_pipe:
1469 case Builtin::BIreserve_write_pipe:
1470 case Builtin::BIwork_group_reserve_read_pipe:
1471 case Builtin::BIwork_group_reserve_write_pipe:
1472 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473 return ExprError();
1474 break;
1475 case Builtin::BIsub_group_reserve_read_pipe:
1476 case Builtin::BIsub_group_reserve_write_pipe:
1477 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478 SemaBuiltinReserveRWPipe(*this, TheCall))
1479 return ExprError();
1480 break;
1481 case Builtin::BIcommit_read_pipe:
1482 case Builtin::BIcommit_write_pipe:
1483 case Builtin::BIwork_group_commit_read_pipe:
1484 case Builtin::BIwork_group_commit_write_pipe:
1485 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486 return ExprError();
1487 break;
1488 case Builtin::BIsub_group_commit_read_pipe:
1489 case Builtin::BIsub_group_commit_write_pipe:
1490 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491 SemaBuiltinCommitRWPipe(*this, TheCall))
1492 return ExprError();
1493 break;
1494 case Builtin::BIget_pipe_num_packets:
1495 case Builtin::BIget_pipe_max_packets:
1496 if (SemaBuiltinPipePackets(*this, TheCall))
1497 return ExprError();
1498 break;
1499 case Builtin::BIto_global:
1500 case Builtin::BIto_local:
1501 case Builtin::BIto_private:
1502 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1503 return ExprError();
1504 break;
1505 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1506 case Builtin::BIenqueue_kernel:
1507 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1508 return ExprError();
1509 break;
1510 case Builtin::BIget_kernel_work_group_size:
1511 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1512 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1513 return ExprError();
1514 break;
1515 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1516 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1517 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1518 return ExprError();
1519 break;
1520 case Builtin::BI__builtin_os_log_format:
1521 case Builtin::BI__builtin_os_log_format_buffer_size:
1522 if (SemaBuiltinOSLogFormat(TheCall))
1523 return ExprError();
1524 break;
1525 }
1526
1527 // Since the target specific builtins for each arch overlap, only check those
1528 // of the arch we are compiling for.
1529 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1530 switch (Context.getTargetInfo().getTriple().getArch()) {
1531 case llvm::Triple::arm:
1532 case llvm::Triple::armeb:
1533 case llvm::Triple::thumb:
1534 case llvm::Triple::thumbeb:
1535 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536 return ExprError();
1537 break;
1538 case llvm::Triple::aarch64:
1539 case llvm::Triple::aarch64_be:
1540 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1541 return ExprError();
1542 break;
1543 case llvm::Triple::hexagon:
1544 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1545 return ExprError();
1546 break;
1547 case llvm::Triple::mips:
1548 case llvm::Triple::mipsel:
1549 case llvm::Triple::mips64:
1550 case llvm::Triple::mips64el:
1551 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1552 return ExprError();
1553 break;
1554 case llvm::Triple::systemz:
1555 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1556 return ExprError();
1557 break;
1558 case llvm::Triple::x86:
1559 case llvm::Triple::x86_64:
1560 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1561 return ExprError();
1562 break;
1563 case llvm::Triple::ppc:
1564 case llvm::Triple::ppc64:
1565 case llvm::Triple::ppc64le:
1566 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1567 return ExprError();
1568 break;
1569 default:
1570 break;
1571 }
1572 }
1573
1574 return TheCallResult;
1575}
1576
1577// Get the valid immediate range for the specified NEON type code.
1578static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1579 NeonTypeFlags Type(t);
1580 int IsQuad = ForceQuad ? true : Type.isQuad();
1581 switch (Type.getEltType()) {
1582 case NeonTypeFlags::Int8:
1583 case NeonTypeFlags::Poly8:
1584 return shift ? 7 : (8 << IsQuad) - 1;
1585 case NeonTypeFlags::Int16:
1586 case NeonTypeFlags::Poly16:
1587 return shift ? 15 : (4 << IsQuad) - 1;
1588 case NeonTypeFlags::Int32:
1589 return shift ? 31 : (2 << IsQuad) - 1;
1590 case NeonTypeFlags::Int64:
1591 case NeonTypeFlags::Poly64:
1592 return shift ? 63 : (1 << IsQuad) - 1;
1593 case NeonTypeFlags::Poly128:
1594 return shift ? 127 : (1 << IsQuad) - 1;
1595 case NeonTypeFlags::Float16:
1596 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1596, __PRETTY_FUNCTION__))
;
1597 return (4 << IsQuad) - 1;
1598 case NeonTypeFlags::Float32:
1599 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1599, __PRETTY_FUNCTION__))
;
1600 return (2 << IsQuad) - 1;
1601 case NeonTypeFlags::Float64:
1602 assert(!shift && "cannot shift float types!")((!shift && "cannot shift float types!") ? static_cast
<void> (0) : __assert_fail ("!shift && \"cannot shift float types!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1602, __PRETTY_FUNCTION__))
;
1603 return (1 << IsQuad) - 1;
1604 }
1605 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1605)
;
1606}
1607
1608/// getNeonEltType - Return the QualType corresponding to the elements of
1609/// the vector type specified by the NeonTypeFlags. This is used to check
1610/// the pointer arguments for Neon load/store intrinsics.
1611static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1612 bool IsPolyUnsigned, bool IsInt64Long) {
1613 switch (Flags.getEltType()) {
1614 case NeonTypeFlags::Int8:
1615 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1616 case NeonTypeFlags::Int16:
1617 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1618 case NeonTypeFlags::Int32:
1619 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1620 case NeonTypeFlags::Int64:
1621 if (IsInt64Long)
1622 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1623 else
1624 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1625 : Context.LongLongTy;
1626 case NeonTypeFlags::Poly8:
1627 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1628 case NeonTypeFlags::Poly16:
1629 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1630 case NeonTypeFlags::Poly64:
1631 if (IsInt64Long)
1632 return Context.UnsignedLongTy;
1633 else
1634 return Context.UnsignedLongLongTy;
1635 case NeonTypeFlags::Poly128:
1636 break;
1637 case NeonTypeFlags::Float16:
1638 return Context.HalfTy;
1639 case NeonTypeFlags::Float32:
1640 return Context.FloatTy;
1641 case NeonTypeFlags::Float64:
1642 return Context.DoubleTy;
1643 }
1644 llvm_unreachable("Invalid NeonTypeFlag!")::llvm::llvm_unreachable_internal("Invalid NeonTypeFlag!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1644)
;
1645}
1646
1647bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1648 llvm::APSInt Result;
1649 uint64_t mask = 0;
1650 unsigned TV = 0;
1651 int PtrArgNum = -1;
1652 bool HasConstPtr = false;
1653 switch (BuiltinID) {
1654#define GET_NEON_OVERLOAD_CHECK
1655#include "clang/Basic/arm_neon.inc"
1656#include "clang/Basic/arm_fp16.inc"
1657#undef GET_NEON_OVERLOAD_CHECK
1658 }
1659
1660 // For NEON intrinsics which are overloaded on vector element type, validate
1661 // the immediate which specifies which variant to emit.
1662 unsigned ImmArg = TheCall->getNumArgs()-1;
1663 if (mask) {
1664 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1665 return true;
1666
1667 TV = Result.getLimitedValue(64);
1668 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1669 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1670 << TheCall->getArg(ImmArg)->getSourceRange();
1671 }
1672
1673 if (PtrArgNum >= 0) {
1674 // Check that pointer arguments have the specified type.
1675 Expr *Arg = TheCall->getArg(PtrArgNum);
1676 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1677 Arg = ICE->getSubExpr();
1678 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1679 QualType RHSTy = RHS.get()->getType();
1680
1681 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1682 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1683 Arch == llvm::Triple::aarch64_be;
1684 bool IsInt64Long =
1685 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1686 QualType EltTy =
1687 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1688 if (HasConstPtr)
1689 EltTy = EltTy.withConst();
1690 QualType LHSTy = Context.getPointerType(EltTy);
1691 AssignConvertType ConvTy;
1692 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1693 if (RHS.isInvalid())
1694 return true;
1695 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1696 RHS.get(), AA_Assigning))
1697 return true;
1698 }
1699
1700 // For NEON intrinsics which take an immediate value as part of the
1701 // instruction, range check them here.
1702 unsigned i = 0, l = 0, u = 0;
1703 switch (BuiltinID) {
1704 default:
1705 return false;
1706 #define GET_NEON_IMMEDIATE_CHECK
1707 #include "clang/Basic/arm_neon.inc"
1708 #include "clang/Basic/arm_fp16.inc"
1709 #undef GET_NEON_IMMEDIATE_CHECK
1710 }
1711
1712 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1713}
1714
1715bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1716 unsigned MaxWidth) {
1717 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1718 BuiltinID == ARM::BI__builtin_arm_ldaex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1719 BuiltinID == ARM::BI__builtin_arm_strex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1720 BuiltinID == ARM::BI__builtin_arm_stlex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1721 BuiltinID == AArch64::BI__builtin_arm_ldrex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1722 BuiltinID == AArch64::BI__builtin_arm_ldaex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1723 BuiltinID == AArch64::BI__builtin_arm_strex ||(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1724 BuiltinID == AArch64::BI__builtin_arm_stlex) &&(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
1725 "unexpected ARM builtin")(((BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM
::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex
|| BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64
::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex
|| BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID ==
AArch64::BI__builtin_arm_stlex) && "unexpected ARM builtin"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == ARM::BI__builtin_arm_ldrex || BuiltinID == ARM::BI__builtin_arm_ldaex || BuiltinID == ARM::BI__builtin_arm_strex || BuiltinID == ARM::BI__builtin_arm_stlex || BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || BuiltinID == AArch64::BI__builtin_arm_stlex) && \"unexpected ARM builtin\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1725, __PRETTY_FUNCTION__))
;
1726 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1727 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1728 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1729 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1730
1731 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1732
1733 // Ensure that we have the proper number of arguments.
1734 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1735 return true;
1736
1737 // Inspect the pointer argument of the atomic builtin. This should always be
1738 // a pointer type, whose element is an integral scalar or pointer type.
1739 // Because it is a pointer type, we don't have to worry about any implicit
1740 // casts here.
1741 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1742 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1743 if (PointerArgRes.isInvalid())
1744 return true;
1745 PointerArg = PointerArgRes.get();
1746
1747 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1748 if (!pointerType) {
1749 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1750 << PointerArg->getType() << PointerArg->getSourceRange();
1751 return true;
1752 }
1753
1754 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1755 // task is to insert the appropriate casts into the AST. First work out just
1756 // what the appropriate type is.
1757 QualType ValType = pointerType->getPointeeType();
1758 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1759 if (IsLdrex)
1760 AddrType.addConst();
1761
1762 // Issue a warning if the cast is dodgy.
1763 CastKind CastNeeded = CK_NoOp;
1764 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1765 CastNeeded = CK_BitCast;
1766 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1767 << PointerArg->getType() << Context.getPointerType(AddrType)
1768 << AA_Passing << PointerArg->getSourceRange();
1769 }
1770
1771 // Finally, do the cast and replace the argument with the corrected version.
1772 AddrType = Context.getPointerType(AddrType);
1773 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1774 if (PointerArgRes.isInvalid())
1775 return true;
1776 PointerArg = PointerArgRes.get();
1777
1778 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1779
1780 // In general, we allow ints, floats and pointers to be loaded and stored.
1781 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1782 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1783 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1784 << PointerArg->getType() << PointerArg->getSourceRange();
1785 return true;
1786 }
1787
1788 // But ARM doesn't have instructions to deal with 128-bit versions.
1789 if (Context.getTypeSize(ValType) > MaxWidth) {
1790 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate")((MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"
) ? static_cast<void> (0) : __assert_fail ("MaxWidth == 64 && \"Diagnostic unexpectedly inaccurate\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 1790, __PRETTY_FUNCTION__))
;
1791 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1792 << PointerArg->getType() << PointerArg->getSourceRange();
1793 return true;
1794 }
1795
1796 switch (ValType.getObjCLifetime()) {
1797 case Qualifiers::OCL_None:
1798 case Qualifiers::OCL_ExplicitNone:
1799 // okay
1800 break;
1801
1802 case Qualifiers::OCL_Weak:
1803 case Qualifiers::OCL_Strong:
1804 case Qualifiers::OCL_Autoreleasing:
1805 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1806 << ValType << PointerArg->getSourceRange();
1807 return true;
1808 }
1809
1810 if (IsLdrex) {
1811 TheCall->setType(ValType);
1812 return false;
1813 }
1814
1815 // Initialize the argument to be stored.
1816 ExprResult ValArg = TheCall->getArg(0);
1817 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1818 Context, ValType, /*consume*/ false);
1819 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1820 if (ValArg.isInvalid())
1821 return true;
1822 TheCall->setArg(0, ValArg.get());
1823
1824 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1825 // but the custom checker bypasses all default analysis.
1826 TheCall->setType(Context.IntTy);
1827 return false;
1828}
1829
1830bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1831 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1832 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1833 BuiltinID == ARM::BI__builtin_arm_strex ||
1834 BuiltinID == ARM::BI__builtin_arm_stlex) {
1835 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1836 }
1837
1838 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1839 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1840 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1841 }
1842
1843 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1844 BuiltinID == ARM::BI__builtin_arm_wsr64)
1845 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1846
1847 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1848 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1849 BuiltinID == ARM::BI__builtin_arm_wsr ||
1850 BuiltinID == ARM::BI__builtin_arm_wsrp)
1851 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1852
1853 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1854 return true;
1855
1856 // For intrinsics which take an immediate value as part of the instruction,
1857 // range check them here.
1858 // FIXME: VFP Intrinsics should error if VFP not present.
1859 switch (BuiltinID) {
1860 default: return false;
1861 case ARM::BI__builtin_arm_ssat:
1862 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1863 case ARM::BI__builtin_arm_usat:
1864 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1865 case ARM::BI__builtin_arm_ssat16:
1866 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1867 case ARM::BI__builtin_arm_usat16:
1868 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1869 case ARM::BI__builtin_arm_vcvtr_f:
1870 case ARM::BI__builtin_arm_vcvtr_d:
1871 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1872 case ARM::BI__builtin_arm_dmb:
1873 case ARM::BI__builtin_arm_dsb:
1874 case ARM::BI__builtin_arm_isb:
1875 case ARM::BI__builtin_arm_dbg:
1876 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1877 }
1878}
1879
1880bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1881 CallExpr *TheCall) {
1882 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1883 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1884 BuiltinID == AArch64::BI__builtin_arm_strex ||
1885 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1886 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1887 }
1888
1889 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1890 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1891 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1892 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1893 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1894 }
1895
1896 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1897 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1898 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1899
1900 // Memory Tagging Extensions (MTE) Intrinsics
1901 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1902 BuiltinID == AArch64::BI__builtin_arm_addg ||
1903 BuiltinID == AArch64::BI__builtin_arm_gmi ||
1904 BuiltinID == AArch64::BI__builtin_arm_ldg ||
1905 BuiltinID == AArch64::BI__builtin_arm_stg ||
1906 BuiltinID == AArch64::BI__builtin_arm_subp) {
1907 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1908 }
1909
1910 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1911 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1912 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1913 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1914 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1915
1916 // Only check the valid encoding range. Any constant in this range would be
1917 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1918 // an exception for incorrect registers. This matches MSVC behavior.
1919 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1920 BuiltinID == AArch64::BI_WriteStatusReg)
1921 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1922
1923 if (BuiltinID == AArch64::BI__getReg)
1924 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1925
1926 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1927 return true;
1928
1929 // For intrinsics which take an immediate value as part of the instruction,
1930 // range check them here.
1931 unsigned i = 0, l = 0, u = 0;
1932 switch (BuiltinID) {
1933 default: return false;
1934 case AArch64::BI__builtin_arm_dmb:
1935 case AArch64::BI__builtin_arm_dsb:
1936 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1937 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1938 }
1939
1940 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1941}
1942
1943bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1944 struct BuiltinAndString {
1945 unsigned BuiltinID;
1946 const char *Str;
1947 };
1948
1949 static BuiltinAndString ValidCPU[] = {
1950 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1951 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1952 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1953 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1954 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1955 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1956 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1957 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1958 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1959 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1960 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1961 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1962 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1963 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1964 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1965 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1966 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1967 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1968 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1969 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1970 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1971 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1972 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1973 };
1974
1975 static BuiltinAndString ValidHVX[] = {
1976 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2553 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2554 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2555 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2556 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2557 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2558 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2559 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2560 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2561 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2562 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2563 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2564 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2565 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2566 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2567 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2568 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2569 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2570 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2571 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2572 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2573 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2574 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2575 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2576 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2577 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2578 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2579 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2580 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2581 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2582 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2583 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2584 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2585 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2586 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2587 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2588 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2589 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2590 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2591 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2592 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2593 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2594 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2595 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2596 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2597 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2598 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2599 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2600 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2601 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2602 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2603 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2604 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2605 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2606 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2607 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2608 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2609 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2610 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2611 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2612 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2613 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2614 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2615 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2616 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2617 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2618 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2619 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2620 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2621 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2622 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2623 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2624 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2625 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2626 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2627 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2628 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2629 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2643 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2644 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2645 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2646 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2647 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2648 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2649 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2650 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2651 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2652 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2653 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2654 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2655 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2656 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2657 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2658 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2659 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2660 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2661 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2662 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2663 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2664 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2665 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2666 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2667 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2668 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2669 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2670 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2671 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2672 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2673 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2674 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2675 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2676 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2677 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2678 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2679 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2680 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2681 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2682 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2683 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2684 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2685 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2686 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2687 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2688 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2689 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2690 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2691 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2692 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2693 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2694 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2695 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2696 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2697 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2698 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2699 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2700 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2701 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2702 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2703 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2704 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2705 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2706 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2707 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2708 };
2709
2710 // Sort the tables on first execution so we can binary search them.
2711 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2712 return LHS.BuiltinID < RHS.BuiltinID;
2713 };
2714 static const bool SortOnce =
2715 (llvm::sort(ValidCPU, SortCmp),
2716 llvm::sort(ValidHVX, SortCmp), true);
2717 (void)SortOnce;
2718 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2719 return BI.BuiltinID < BuiltinID;
2720 };
2721
2722 const TargetInfo &TI = Context.getTargetInfo();
2723
2724 const BuiltinAndString *FC =
2725 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2726 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2727 const TargetOptions &Opts = TI.getTargetOpts();
2728 StringRef CPU = Opts.CPU;
2729 if (!CPU.empty()) {
2730 assert(CPU.startswith("hexagon") && "Unexpected CPU name")((CPU.startswith("hexagon") && "Unexpected CPU name")
? static_cast<void> (0) : __assert_fail ("CPU.startswith(\"hexagon\") && \"Unexpected CPU name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 2730, __PRETTY_FUNCTION__))
;
2731 CPU.consume_front("hexagon");
2732 SmallVector<StringRef, 3> CPUs;
2733 StringRef(FC->Str).split(CPUs, ',');
2734 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2735 return Diag(TheCall->getBeginLoc(),
2736 diag::err_hexagon_builtin_unsupported_cpu);
2737 }
2738 }
2739
2740 const BuiltinAndString *FH =
2741 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2742 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2743 if (!TI.hasFeature("hvx"))
2744 return Diag(TheCall->getBeginLoc(),
2745 diag::err_hexagon_builtin_requires_hvx);
2746
2747 SmallVector<StringRef, 3> HVXs;
2748 StringRef(FH->Str).split(HVXs, ',');
2749 bool IsValid = llvm::any_of(HVXs,
2750 [&TI] (StringRef V) {
2751 std::string F = "hvx" + V.str();
2752 return TI.hasFeature(F);
2753 });
2754 if (!IsValid)
2755 return Diag(TheCall->getBeginLoc(),
2756 diag::err_hexagon_builtin_unsupported_hvx);
2757 }
2758
2759 return false;
2760}
2761
2762bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2763 struct ArgInfo {
2764 uint8_t OpNum;
2765 bool IsSigned;
2766 uint8_t BitWidth;
2767 uint8_t Align;
2768 };
2769 struct BuiltinInfo {
2770 unsigned BuiltinID;
2771 ArgInfo Infos[2];
2772 };
2773
2774 static BuiltinInfo Infos[] = {
2775 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2776 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2777 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2778 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2779 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2780 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2781 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2782 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2783 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2784 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2785 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2786
2787 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2790 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2791 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2792 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2793 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2795 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2796 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2797 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2798
2799 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2804 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2819 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2821 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2825 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2851 {{ 1, false, 6, 0 }} },
2852 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2859 {{ 1, false, 5, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2864 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2865 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2866 { 2, false, 5, 0 }} },
2867 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2868 { 2, false, 6, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2870 { 3, false, 5, 0 }} },
2871 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2872 { 3, false, 6, 0 }} },
2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2888 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2889 {{ 2, false, 4, 0 },
2890 { 3, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2892 {{ 2, false, 4, 0 },
2893 { 3, false, 5, 0 }} },
2894 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2895 {{ 2, false, 4, 0 },
2896 { 3, false, 5, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2898 {{ 2, false, 4, 0 },
2899 { 3, false, 5, 0 }} },
2900 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2901 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2902 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2906 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2909 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2910 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2911 { 2, false, 5, 0 }} },
2912 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2913 { 2, false, 6, 0 }} },
2914 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2915 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2916 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2918 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2920 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2922 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2923 {{ 1, false, 4, 0 }} },
2924 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2925 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2926 {{ 1, false, 4, 0 }} },
2927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2939 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2941 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2943 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2947 {{ 3, false, 1, 0 }} },
2948 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2952 {{ 3, false, 1, 0 }} },
2953 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2957 {{ 3, false, 1, 0 }} },
2958 };
2959
2960 // Use a dynamically initialized static to sort the table exactly once on
2961 // first run.
2962 static const bool SortOnce =
2963 (llvm::sort(Infos,
2964 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2965 return LHS.BuiltinID < RHS.BuiltinID;
2966 }),
2967 true);
2968 (void)SortOnce;
2969
2970 const BuiltinInfo *F = llvm::partition_point(
2971 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2972 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2973 return false;
2974
2975 bool Error = false;
2976
2977 for (const ArgInfo &A : F->Infos) {
2978 // Ignore empty ArgInfo elements.
2979 if (A.BitWidth == 0)
2980 continue;
2981
2982 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2983 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2984 if (!A.Align) {
2985 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2986 } else {
2987 unsigned M = 1 << A.Align;
2988 Min *= M;
2989 Max *= M;
2990 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2991 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2992 }
2993 }
2994 return Error;
2995}
2996
2997bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2998 CallExpr *TheCall) {
2999 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3000 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001}
3002
3003
3004// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3005// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3006// ordering for DSP is unspecified. MSA is ordered by the data format used
3007// by the underlying instruction i.e., df/m, df/n and then by size.
3008//
3009// FIXME: The size tests here should instead be tablegen'd along with the
3010// definitions from include/clang/Basic/BuiltinsMips.def.
3011// FIXME: GCC is strict on signedness for some of these intrinsics, we should
3012// be too.
3013bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3014 unsigned i = 0, l = 0, u = 0, m = 0;
3015 switch (BuiltinID) {
3016 default: return false;
3017 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3018 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3019 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3020 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3021 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3022 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3023 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3024 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3025 // df/m field.
3026 // These intrinsics take an unsigned 3 bit immediate.
3027 case Mips::BI__builtin_msa_bclri_b:
3028 case Mips::BI__builtin_msa_bnegi_b:
3029 case Mips::BI__builtin_msa_bseti_b:
3030 case Mips::BI__builtin_msa_sat_s_b:
3031 case Mips::BI__builtin_msa_sat_u_b:
3032 case Mips::BI__builtin_msa_slli_b:
3033 case Mips::BI__builtin_msa_srai_b:
3034 case Mips::BI__builtin_msa_srari_b:
3035 case Mips::BI__builtin_msa_srli_b:
3036 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3037 case Mips::BI__builtin_msa_binsli_b:
3038 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3039 // These intrinsics take an unsigned 4 bit immediate.
3040 case Mips::BI__builtin_msa_bclri_h:
3041 case Mips::BI__builtin_msa_bnegi_h:
3042 case Mips::BI__builtin_msa_bseti_h:
3043 case Mips::BI__builtin_msa_sat_s_h:
3044 case Mips::BI__builtin_msa_sat_u_h:
3045 case Mips::BI__builtin_msa_slli_h:
3046 case Mips::BI__builtin_msa_srai_h:
3047 case Mips::BI__builtin_msa_srari_h:
3048 case Mips::BI__builtin_msa_srli_h:
3049 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3050 case Mips::BI__builtin_msa_binsli_h:
3051 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3052 // These intrinsics take an unsigned 5 bit immediate.
3053 // The first block of intrinsics actually have an unsigned 5 bit field,
3054 // not a df/n field.
3055 case Mips::BI__builtin_msa_cfcmsa:
3056 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3057 case Mips::BI__builtin_msa_clei_u_b:
3058 case Mips::BI__builtin_msa_clei_u_h:
3059 case Mips::BI__builtin_msa_clei_u_w:
3060 case Mips::BI__builtin_msa_clei_u_d:
3061 case Mips::BI__builtin_msa_clti_u_b:
3062 case Mips::BI__builtin_msa_clti_u_h:
3063 case Mips::BI__builtin_msa_clti_u_w:
3064 case Mips::BI__builtin_msa_clti_u_d:
3065 case Mips::BI__builtin_msa_maxi_u_b:
3066 case Mips::BI__builtin_msa_maxi_u_h:
3067 case Mips::BI__builtin_msa_maxi_u_w:
3068 case Mips::BI__builtin_msa_maxi_u_d:
3069 case Mips::BI__builtin_msa_mini_u_b:
3070 case Mips::BI__builtin_msa_mini_u_h:
3071 case Mips::BI__builtin_msa_mini_u_w:
3072 case Mips::BI__builtin_msa_mini_u_d:
3073 case Mips::BI__builtin_msa_addvi_b:
3074 case Mips::BI__builtin_msa_addvi_h:
3075 case Mips::BI__builtin_msa_addvi_w:
3076 case Mips::BI__builtin_msa_addvi_d:
3077 case Mips::BI__builtin_msa_bclri_w:
3078 case Mips::BI__builtin_msa_bnegi_w:
3079 case Mips::BI__builtin_msa_bseti_w:
3080 case Mips::BI__builtin_msa_sat_s_w:
3081 case Mips::BI__builtin_msa_sat_u_w:
3082 case Mips::BI__builtin_msa_slli_w:
3083 case Mips::BI__builtin_msa_srai_w:
3084 case Mips::BI__builtin_msa_srari_w:
3085 case Mips::BI__builtin_msa_srli_w:
3086 case Mips::BI__builtin_msa_srlri_w:
3087 case Mips::BI__builtin_msa_subvi_b:
3088 case Mips::BI__builtin_msa_subvi_h:
3089 case Mips::BI__builtin_msa_subvi_w:
3090 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3091 case Mips::BI__builtin_msa_binsli_w:
3092 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3093 // These intrinsics take an unsigned 6 bit immediate.
3094 case Mips::BI__builtin_msa_bclri_d:
3095 case Mips::BI__builtin_msa_bnegi_d:
3096 case Mips::BI__builtin_msa_bseti_d:
3097 case Mips::BI__builtin_msa_sat_s_d:
3098 case Mips::BI__builtin_msa_sat_u_d:
3099 case Mips::BI__builtin_msa_slli_d:
3100 case Mips::BI__builtin_msa_srai_d:
3101 case Mips::BI__builtin_msa_srari_d:
3102 case Mips::BI__builtin_msa_srli_d:
3103 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3104 case Mips::BI__builtin_msa_binsli_d:
3105 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3106 // These intrinsics take a signed 5 bit immediate.
3107 case Mips::BI__builtin_msa_ceqi_b:
3108 case Mips::BI__builtin_msa_ceqi_h:
3109 case Mips::BI__builtin_msa_ceqi_w:
3110 case Mips::BI__builtin_msa_ceqi_d:
3111 case Mips::BI__builtin_msa_clti_s_b:
3112 case Mips::BI__builtin_msa_clti_s_h:
3113 case Mips::BI__builtin_msa_clti_s_w:
3114 case Mips::BI__builtin_msa_clti_s_d:
3115 case Mips::BI__builtin_msa_clei_s_b:
3116 case Mips::BI__builtin_msa_clei_s_h:
3117 case Mips::BI__builtin_msa_clei_s_w:
3118 case Mips::BI__builtin_msa_clei_s_d:
3119 case Mips::BI__builtin_msa_maxi_s_b:
3120 case Mips::BI__builtin_msa_maxi_s_h:
3121 case Mips::BI__builtin_msa_maxi_s_w:
3122 case Mips::BI__builtin_msa_maxi_s_d:
3123 case Mips::BI__builtin_msa_mini_s_b:
3124 case Mips::BI__builtin_msa_mini_s_h:
3125 case Mips::BI__builtin_msa_mini_s_w:
3126 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3127 // These intrinsics take an unsigned 8 bit immediate.
3128 case Mips::BI__builtin_msa_andi_b:
3129 case Mips::BI__builtin_msa_nori_b:
3130 case Mips::BI__builtin_msa_ori_b:
3131 case Mips::BI__builtin_msa_shf_b:
3132 case Mips::BI__builtin_msa_shf_h:
3133 case Mips::BI__builtin_msa_shf_w:
3134 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3135 case Mips::BI__builtin_msa_bseli_b:
3136 case Mips::BI__builtin_msa_bmnzi_b:
3137 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3138 // df/n format
3139 // These intrinsics take an unsigned 4 bit immediate.
3140 case Mips::BI__builtin_msa_copy_s_b:
3141 case Mips::BI__builtin_msa_copy_u_b:
3142 case Mips::BI__builtin_msa_insve_b:
3143 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3144 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3145 // These intrinsics take an unsigned 3 bit immediate.
3146 case Mips::BI__builtin_msa_copy_s_h:
3147 case Mips::BI__builtin_msa_copy_u_h:
3148 case Mips::BI__builtin_msa_insve_h:
3149 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3150 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3151 // These intrinsics take an unsigned 2 bit immediate.
3152 case Mips::BI__builtin_msa_copy_s_w:
3153 case Mips::BI__builtin_msa_copy_u_w:
3154 case Mips::BI__builtin_msa_insve_w:
3155 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3156 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3157 // These intrinsics take an unsigned 1 bit immediate.
3158 case Mips::BI__builtin_msa_copy_s_d:
3159 case Mips::BI__builtin_msa_copy_u_d:
3160 case Mips::BI__builtin_msa_insve_d:
3161 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3162 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3163 // Memory offsets and immediate loads.
3164 // These intrinsics take a signed 10 bit immediate.
3165 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3166 case Mips::BI__builtin_msa_ldi_h:
3167 case Mips::BI__builtin_msa_ldi_w:
3168 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3169 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3170 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3171 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3172 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3173 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3174 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3175 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3176 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3177 }
3178
3179 if (!m)
3180 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3181
3182 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3183 SemaBuiltinConstantArgMultiple(TheCall, i, m);
3184}
3185
3186bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3187 unsigned i = 0, l = 0, u = 0;
3188 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3189 BuiltinID == PPC::BI__builtin_divdeu ||
3190 BuiltinID == PPC::BI__builtin_bpermd;
3191 bool IsTarget64Bit = Context.getTargetInfo()
3192 .getTypeWidth(Context
3193 .getTargetInfo()
3194 .getIntPtrType()) == 64;
3195 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3196 BuiltinID == PPC::BI__builtin_divweu ||
3197 BuiltinID == PPC::BI__builtin_divde ||
3198 BuiltinID == PPC::BI__builtin_divdeu;
3199
3200 if (Is64BitBltin && !IsTarget64Bit)
3201 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3202 << TheCall->getSourceRange();
3203
3204 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3205 (BuiltinID == PPC::BI__builtin_bpermd &&
3206 !Context.getTargetInfo().hasFeature("bpermd")))
3207 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3208 << TheCall->getSourceRange();
3209
3210 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3211 if (!Context.getTargetInfo().hasFeature("vsx"))
3212 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3213 << TheCall->getSourceRange();
3214 return false;
3215 };
3216
3217 switch (BuiltinID) {
3218 default: return false;
3219 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3220 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3221 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3222 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3223 case PPC::BI__builtin_altivec_dss:
3224 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3225 case PPC::BI__builtin_tbegin:
3226 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3227 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3228 case PPC::BI__builtin_tabortwc:
3229 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3230 case PPC::BI__builtin_tabortwci:
3231 case PPC::BI__builtin_tabortdci:
3232 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3233 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3234 case PPC::BI__builtin_altivec_dst:
3235 case PPC::BI__builtin_altivec_dstt:
3236 case PPC::BI__builtin_altivec_dstst:
3237 case PPC::BI__builtin_altivec_dststt:
3238 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3239 case PPC::BI__builtin_vsx_xxpermdi:
3240 case PPC::BI__builtin_vsx_xxsldwi:
3241 return SemaBuiltinVSX(TheCall);
3242 case PPC::BI__builtin_unpack_vector_int128:
3243 return SemaVSXCheck(TheCall) ||
3244 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3245 case PPC::BI__builtin_pack_vector_int128:
3246 return SemaVSXCheck(TheCall);
3247 }
3248 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3249}
3250
3251bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3252 CallExpr *TheCall) {
3253 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3254 Expr *Arg = TheCall->getArg(0);
3255 llvm::APSInt AbortCode(32);
3256 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3257 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3258 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3259 << Arg->getSourceRange();
3260 }
3261
3262 // For intrinsics which take an immediate value as part of the instruction,
3263 // range check them here.
3264 unsigned i = 0, l = 0, u = 0;
3265 switch (BuiltinID) {
3266 default: return false;
3267 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3268 case SystemZ::BI__builtin_s390_verimb:
3269 case SystemZ::BI__builtin_s390_verimh:
3270 case SystemZ::BI__builtin_s390_verimf:
3271 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3272 case SystemZ::BI__builtin_s390_vfaeb:
3273 case SystemZ::BI__builtin_s390_vfaeh:
3274 case SystemZ::BI__builtin_s390_vfaef:
3275 case SystemZ::BI__builtin_s390_vfaebs:
3276 case SystemZ::BI__builtin_s390_vfaehs:
3277 case SystemZ::BI__builtin_s390_vfaefs:
3278 case SystemZ::BI__builtin_s390_vfaezb:
3279 case SystemZ::BI__builtin_s390_vfaezh:
3280 case SystemZ::BI__builtin_s390_vfaezf:
3281 case SystemZ::BI__builtin_s390_vfaezbs:
3282 case SystemZ::BI__builtin_s390_vfaezhs:
3283 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3284 case SystemZ::BI__builtin_s390_vfisb:
3285 case SystemZ::BI__builtin_s390_vfidb:
3286 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3287 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3288 case SystemZ::BI__builtin_s390_vftcisb:
3289 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3290 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3291 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3292 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3293 case SystemZ::BI__builtin_s390_vstrcb:
3294 case SystemZ::BI__builtin_s390_vstrch:
3295 case SystemZ::BI__builtin_s390_vstrcf:
3296 case SystemZ::BI__builtin_s390_vstrczb:
3297 case SystemZ::BI__builtin_s390_vstrczh:
3298 case SystemZ::BI__builtin_s390_vstrczf:
3299 case SystemZ::BI__builtin_s390_vstrcbs:
3300 case SystemZ::BI__builtin_s390_vstrchs:
3301 case SystemZ::BI__builtin_s390_vstrcfs:
3302 case SystemZ::BI__builtin_s390_vstrczbs:
3303 case SystemZ::BI__builtin_s390_vstrczhs:
3304 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3305 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3306 case SystemZ::BI__builtin_s390_vfminsb:
3307 case SystemZ::BI__builtin_s390_vfmaxsb:
3308 case SystemZ::BI__builtin_s390_vfmindb:
3309 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3310 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3311 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3312 }
3313 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3314}
3315
3316/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3317/// This checks that the target supports __builtin_cpu_supports and
3318/// that the string argument is constant and valid.
3319static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3320 Expr *Arg = TheCall->getArg(0);
3321
3322 // Check if the argument is a string literal.
3323 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3324 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3325 << Arg->getSourceRange();
3326
3327 // Check the contents of the string.
3328 StringRef Feature =
3329 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3330 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3331 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3332 << Arg->getSourceRange();
3333 return false;
3334}
3335
3336/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3337/// This checks that the target supports __builtin_cpu_is and
3338/// that the string argument is constant and valid.
3339static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3340 Expr *Arg = TheCall->getArg(0);
3341
3342 // Check if the argument is a string literal.
3343 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3344 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3345 << Arg->getSourceRange();
3346
3347 // Check the contents of the string.
3348 StringRef Feature =
3349 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3350 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3351 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3352 << Arg->getSourceRange();
3353 return false;
3354}
3355
3356// Check if the rounding mode is legal.
3357bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3358 // Indicates if this instruction has rounding control or just SAE.
3359 bool HasRC = false;
3360
3361 unsigned ArgNum = 0;
3362 switch (BuiltinID) {
3363 default:
3364 return false;
3365 case X86::BI__builtin_ia32_vcvttsd2si32:
3366 case X86::BI__builtin_ia32_vcvttsd2si64:
3367 case X86::BI__builtin_ia32_vcvttsd2usi32:
3368 case X86::BI__builtin_ia32_vcvttsd2usi64:
3369 case X86::BI__builtin_ia32_vcvttss2si32:
3370 case X86::BI__builtin_ia32_vcvttss2si64:
3371 case X86::BI__builtin_ia32_vcvttss2usi32:
3372 case X86::BI__builtin_ia32_vcvttss2usi64:
3373 ArgNum = 1;
3374 break;
3375 case X86::BI__builtin_ia32_maxpd512:
3376 case X86::BI__builtin_ia32_maxps512:
3377 case X86::BI__builtin_ia32_minpd512:
3378 case X86::BI__builtin_ia32_minps512:
3379 ArgNum = 2;
3380 break;
3381 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3382 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3383 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3384 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3385 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3386 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3387 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3388 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3389 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3390 case X86::BI__builtin_ia32_exp2pd_mask:
3391 case X86::BI__builtin_ia32_exp2ps_mask:
3392 case X86::BI__builtin_ia32_getexppd512_mask:
3393 case X86::BI__builtin_ia32_getexpps512_mask:
3394 case X86::BI__builtin_ia32_rcp28pd_mask:
3395 case X86::BI__builtin_ia32_rcp28ps_mask:
3396 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3397 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3398 case X86::BI__builtin_ia32_vcomisd:
3399 case X86::BI__builtin_ia32_vcomiss:
3400 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3401 ArgNum = 3;
3402 break;
3403 case X86::BI__builtin_ia32_cmppd512_mask:
3404 case X86::BI__builtin_ia32_cmpps512_mask:
3405 case X86::BI__builtin_ia32_cmpsd_mask:
3406 case X86::BI__builtin_ia32_cmpss_mask:
3407 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3408 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3409 case X86::BI__builtin_ia32_getexpss128_round_mask:
3410 case X86::BI__builtin_ia32_getmantpd512_mask:
3411 case X86::BI__builtin_ia32_getmantps512_mask:
3412 case X86::BI__builtin_ia32_maxsd_round_mask:
3413 case X86::BI__builtin_ia32_maxss_round_mask:
3414 case X86::BI__builtin_ia32_minsd_round_mask:
3415 case X86::BI__builtin_ia32_minss_round_mask:
3416 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3417 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3418 case X86::BI__builtin_ia32_reducepd512_mask:
3419 case X86::BI__builtin_ia32_reduceps512_mask:
3420 case X86::BI__builtin_ia32_rndscalepd_mask:
3421 case X86::BI__builtin_ia32_rndscaleps_mask:
3422 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3423 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3424 ArgNum = 4;
3425 break;
3426 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3427 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3428 case X86::BI__builtin_ia32_fixupimmps512_mask:
3429 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3430 case X86::BI__builtin_ia32_fixupimmsd_mask:
3431 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3432 case X86::BI__builtin_ia32_fixupimmss_mask:
3433 case X86::BI__builtin_ia32_fixupimmss_maskz:
3434 case X86::BI__builtin_ia32_getmantsd_round_mask:
3435 case X86::BI__builtin_ia32_getmantss_round_mask:
3436 case X86::BI__builtin_ia32_rangepd512_mask:
3437 case X86::BI__builtin_ia32_rangeps512_mask:
3438 case X86::BI__builtin_ia32_rangesd128_round_mask:
3439 case X86::BI__builtin_ia32_rangess128_round_mask:
3440 case X86::BI__builtin_ia32_reducesd_mask:
3441 case X86::BI__builtin_ia32_reducess_mask:
3442 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3443 case X86::BI__builtin_ia32_rndscaless_round_mask:
3444 ArgNum = 5;
3445 break;
3446 case X86::BI__builtin_ia32_vcvtsd2si64:
3447 case X86::BI__builtin_ia32_vcvtsd2si32:
3448 case X86::BI__builtin_ia32_vcvtsd2usi32:
3449 case X86::BI__builtin_ia32_vcvtsd2usi64:
3450 case X86::BI__builtin_ia32_vcvtss2si32:
3451 case X86::BI__builtin_ia32_vcvtss2si64:
3452 case X86::BI__builtin_ia32_vcvtss2usi32:
3453 case X86::BI__builtin_ia32_vcvtss2usi64:
3454 case X86::BI__builtin_ia32_sqrtpd512:
3455 case X86::BI__builtin_ia32_sqrtps512:
3456 ArgNum = 1;
3457 HasRC = true;
3458 break;
3459 case X86::BI__builtin_ia32_addpd512:
3460 case X86::BI__builtin_ia32_addps512:
3461 case X86::BI__builtin_ia32_divpd512:
3462 case X86::BI__builtin_ia32_divps512:
3463 case X86::BI__builtin_ia32_mulpd512:
3464 case X86::BI__builtin_ia32_mulps512:
3465 case X86::BI__builtin_ia32_subpd512:
3466 case X86::BI__builtin_ia32_subps512:
3467 case X86::BI__builtin_ia32_cvtsi2sd64:
3468 case X86::BI__builtin_ia32_cvtsi2ss32:
3469 case X86::BI__builtin_ia32_cvtsi2ss64:
3470 case X86::BI__builtin_ia32_cvtusi2sd64:
3471 case X86::BI__builtin_ia32_cvtusi2ss32:
3472 case X86::BI__builtin_ia32_cvtusi2ss64:
3473 ArgNum = 2;
3474 HasRC = true;
3475 break;
3476 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3477 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3478 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3479 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3480 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3481 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3482 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3483 case X86::BI__builtin_ia32_cvtps2dq512_mask:
3484 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3485 case X86::BI__builtin_ia32_cvtps2udq512_mask:
3486 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3487 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3488 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3489 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3490 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3491 ArgNum = 3;
3492 HasRC = true;
3493 break;
3494 case X86::BI__builtin_ia32_addss_round_mask:
3495 case X86::BI__builtin_ia32_addsd_round_mask:
3496 case X86::BI__builtin_ia32_divss_round_mask:
3497 case X86::BI__builtin_ia32_divsd_round_mask:
3498 case X86::BI__builtin_ia32_mulss_round_mask:
3499 case X86::BI__builtin_ia32_mulsd_round_mask:
3500 case X86::BI__builtin_ia32_subss_round_mask:
3501 case X86::BI__builtin_ia32_subsd_round_mask:
3502 case X86::BI__builtin_ia32_scalefpd512_mask:
3503 case X86::BI__builtin_ia32_scalefps512_mask:
3504 case X86::BI__builtin_ia32_scalefsd_round_mask:
3505 case X86::BI__builtin_ia32_scalefss_round_mask:
3506 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3507 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3508 case X86::BI__builtin_ia32_sqrtss_round_mask:
3509 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3510 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3511 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3512 case X86::BI__builtin_ia32_vfmaddss3_mask:
3513 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3514 case X86::BI__builtin_ia32_vfmaddss3_mask3:
3515 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3516 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3517 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3518 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3519 case X86::BI__builtin_ia32_vfmaddps512_mask:
3520 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3521 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3522 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3523 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3524 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3525 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3526 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3527 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3528 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3529 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3530 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3531 ArgNum = 4;
3532 HasRC = true;
3533 break;
3534 }
3535
3536 llvm::APSInt Result;
3537
3538 // We can't check the value of a dependent argument.
3539 Expr *Arg = TheCall->getArg(ArgNum);
3540 if (Arg->isTypeDependent() || Arg->isValueDependent())
3541 return false;
3542
3543 // Check constant-ness first.
3544 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3545 return true;
3546
3547 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3548 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3549 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3550 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3551 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3552 Result == 8/*ROUND_NO_EXC*/ ||
3553 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3554 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3555 return false;
3556
3557 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3558 << Arg->getSourceRange();
3559}
3560
3561// Check if the gather/scatter scale is legal.
3562bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3563 CallExpr *TheCall) {
3564 unsigned ArgNum = 0;
3565 switch (BuiltinID) {
3566 default:
3567 return false;
3568 case X86::BI__builtin_ia32_gatherpfdpd:
3569 case X86::BI__builtin_ia32_gatherpfdps:
3570 case X86::BI__builtin_ia32_gatherpfqpd:
3571 case X86::BI__builtin_ia32_gatherpfqps:
3572 case X86::BI__builtin_ia32_scatterpfdpd:
3573 case X86::BI__builtin_ia32_scatterpfdps:
3574 case X86::BI__builtin_ia32_scatterpfqpd:
3575 case X86::BI__builtin_ia32_scatterpfqps:
3576 ArgNum = 3;
3577 break;
3578 case X86::BI__builtin_ia32_gatherd_pd:
3579 case X86::BI__builtin_ia32_gatherd_pd256:
3580 case X86::BI__builtin_ia32_gatherq_pd:
3581 case X86::BI__builtin_ia32_gatherq_pd256:
3582 case X86::BI__builtin_ia32_gatherd_ps:
3583 case X86::BI__builtin_ia32_gatherd_ps256:
3584 case X86::BI__builtin_ia32_gatherq_ps:
3585 case X86::BI__builtin_ia32_gatherq_ps256:
3586 case X86::BI__builtin_ia32_gatherd_q:
3587 case X86::BI__builtin_ia32_gatherd_q256:
3588 case X86::BI__builtin_ia32_gatherq_q:
3589 case X86::BI__builtin_ia32_gatherq_q256:
3590 case X86::BI__builtin_ia32_gatherd_d:
3591 case X86::BI__builtin_ia32_gatherd_d256:
3592 case X86::BI__builtin_ia32_gatherq_d:
3593 case X86::BI__builtin_ia32_gatherq_d256:
3594 case X86::BI__builtin_ia32_gather3div2df:
3595 case X86::BI__builtin_ia32_gather3div2di:
3596 case X86::BI__builtin_ia32_gather3div4df:
3597 case X86::BI__builtin_ia32_gather3div4di:
3598 case X86::BI__builtin_ia32_gather3div4sf:
3599 case X86::BI__builtin_ia32_gather3div4si:
3600 case X86::BI__builtin_ia32_gather3div8sf:
3601 case X86::BI__builtin_ia32_gather3div8si:
3602 case X86::BI__builtin_ia32_gather3siv2df:
3603 case X86::BI__builtin_ia32_gather3siv2di:
3604 case X86::BI__builtin_ia32_gather3siv4df:
3605 case X86::BI__builtin_ia32_gather3siv4di:
3606 case X86::BI__builtin_ia32_gather3siv4sf:
3607 case X86::BI__builtin_ia32_gather3siv4si:
3608 case X86::BI__builtin_ia32_gather3siv8sf:
3609 case X86::BI__builtin_ia32_gather3siv8si:
3610 case X86::BI__builtin_ia32_gathersiv8df:
3611 case X86::BI__builtin_ia32_gathersiv16sf:
3612 case X86::BI__builtin_ia32_gatherdiv8df:
3613 case X86::BI__builtin_ia32_gatherdiv16sf:
3614 case X86::BI__builtin_ia32_gathersiv8di:
3615 case X86::BI__builtin_ia32_gathersiv16si:
3616 case X86::BI__builtin_ia32_gatherdiv8di:
3617 case X86::BI__builtin_ia32_gatherdiv16si:
3618 case X86::BI__builtin_ia32_scatterdiv2df:
3619 case X86::BI__builtin_ia32_scatterdiv2di:
3620 case X86::BI__builtin_ia32_scatterdiv4df:
3621 case X86::BI__builtin_ia32_scatterdiv4di:
3622 case X86::BI__builtin_ia32_scatterdiv4sf:
3623 case X86::BI__builtin_ia32_scatterdiv4si:
3624 case X86::BI__builtin_ia32_scatterdiv8sf:
3625 case X86::BI__builtin_ia32_scatterdiv8si:
3626 case X86::BI__builtin_ia32_scattersiv2df:
3627 case X86::BI__builtin_ia32_scattersiv2di:
3628 case X86::BI__builtin_ia32_scattersiv4df:
3629 case X86::BI__builtin_ia32_scattersiv4di:
3630 case X86::BI__builtin_ia32_scattersiv4sf:
3631 case X86::BI__builtin_ia32_scattersiv4si:
3632 case X86::BI__builtin_ia32_scattersiv8sf:
3633 case X86::BI__builtin_ia32_scattersiv8si:
3634 case X86::BI__builtin_ia32_scattersiv8df:
3635 case X86::BI__builtin_ia32_scattersiv16sf:
3636 case X86::BI__builtin_ia32_scatterdiv8df:
3637 case X86::BI__builtin_ia32_scatterdiv16sf:
3638 case X86::BI__builtin_ia32_scattersiv8di:
3639 case X86::BI__builtin_ia32_scattersiv16si:
3640 case X86::BI__builtin_ia32_scatterdiv8di:
3641 case X86::BI__builtin_ia32_scatterdiv16si:
3642 ArgNum = 4;
3643 break;
3644 }
3645
3646 llvm::APSInt Result;
3647
3648 // We can't check the value of a dependent argument.
3649 Expr *Arg = TheCall->getArg(ArgNum);
3650 if (Arg->isTypeDependent() || Arg->isValueDependent())
3651 return false;
3652
3653 // Check constant-ness first.
3654 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3655 return true;
3656
3657 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3658 return false;
3659
3660 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3661 << Arg->getSourceRange();
3662}
3663
3664static bool isX86_32Builtin(unsigned BuiltinID) {
3665 // These builtins only work on x86-32 targets.
3666 switch (BuiltinID) {
3667 case X86::BI__builtin_ia32_readeflags_u32:
3668 case X86::BI__builtin_ia32_writeeflags_u32:
3669 return true;
3670 }
3671
3672 return false;
3673}
3674
3675bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3676 if (BuiltinID == X86::BI__builtin_cpu_supports)
3677 return SemaBuiltinCpuSupports(*this, TheCall);
3678
3679 if (BuiltinID == X86::BI__builtin_cpu_is)
3680 return SemaBuiltinCpuIs(*this, TheCall);
3681
3682 // Check for 32-bit only builtins on a 64-bit target.
3683 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3684 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3685 return Diag(TheCall->getCallee()->getBeginLoc(),
3686 diag::err_32_bit_builtin_64_bit_tgt);
3687
3688 // If the intrinsic has rounding or SAE make sure its valid.
3689 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3690 return true;
3691
3692 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3693 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3694 return true;
3695
3696 // For intrinsics which take an immediate value as part of the instruction,
3697 // range check them here.
3698 int i = 0, l = 0, u = 0;
3699 switch (BuiltinID) {
3700 default:
3701 return false;
3702 case X86::BI__builtin_ia32_vec_ext_v2si:
3703 case X86::BI__builtin_ia32_vec_ext_v2di:
3704 case X86::BI__builtin_ia32_vextractf128_pd256:
3705 case X86::BI__builtin_ia32_vextractf128_ps256:
3706 case X86::BI__builtin_ia32_vextractf128_si256:
3707 case X86::BI__builtin_ia32_extract128i256:
3708 case X86::BI__builtin_ia32_extractf64x4_mask:
3709 case X86::BI__builtin_ia32_extracti64x4_mask:
3710 case X86::BI__builtin_ia32_extractf32x8_mask:
3711 case X86::BI__builtin_ia32_extracti32x8_mask:
3712 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3713 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3714 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3715 case X86::BI__builtin_ia32_extracti32x4_256_mask:
3716 i = 1; l = 0; u = 1;
3717 break;
3718 case X86::BI__builtin_ia32_vec_set_v2di:
3719 case X86::BI__builtin_ia32_vinsertf128_pd256:
3720 case X86::BI__builtin_ia32_vinsertf128_ps256:
3721 case X86::BI__builtin_ia32_vinsertf128_si256:
3722 case X86::BI__builtin_ia32_insert128i256:
3723 case X86::BI__builtin_ia32_insertf32x8:
3724 case X86::BI__builtin_ia32_inserti32x8:
3725 case X86::BI__builtin_ia32_insertf64x4:
3726 case X86::BI__builtin_ia32_inserti64x4:
3727 case X86::BI__builtin_ia32_insertf64x2_256:
3728 case X86::BI__builtin_ia32_inserti64x2_256:
3729 case X86::BI__builtin_ia32_insertf32x4_256:
3730 case X86::BI__builtin_ia32_inserti32x4_256:
3731 i = 2; l = 0; u = 1;
3732 break;
3733 case X86::BI__builtin_ia32_vpermilpd:
3734 case X86::BI__builtin_ia32_vec_ext_v4hi:
3735 case X86::BI__builtin_ia32_vec_ext_v4si:
3736 case X86::BI__builtin_ia32_vec_ext_v4sf:
3737 case X86::BI__builtin_ia32_vec_ext_v4di:
3738 case X86::BI__builtin_ia32_extractf32x4_mask:
3739 case X86::BI__builtin_ia32_extracti32x4_mask:
3740 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3741 case X86::BI__builtin_ia32_extracti64x2_512_mask:
3742 i = 1; l = 0; u = 3;
3743 break;
3744 case X86::BI_mm_prefetch:
3745 case X86::BI__builtin_ia32_vec_ext_v8hi:
3746 case X86::BI__builtin_ia32_vec_ext_v8si:
3747 i = 1; l = 0; u = 7;
3748 break;
3749 case X86::BI__builtin_ia32_sha1rnds4:
3750 case X86::BI__builtin_ia32_blendpd:
3751 case X86::BI__builtin_ia32_shufpd:
3752 case X86::BI__builtin_ia32_vec_set_v4hi:
3753 case X86::BI__builtin_ia32_vec_set_v4si:
3754 case X86::BI__builtin_ia32_vec_set_v4di:
3755 case X86::BI__builtin_ia32_shuf_f32x4_256:
3756 case X86::BI__builtin_ia32_shuf_f64x2_256:
3757 case X86::BI__builtin_ia32_shuf_i32x4_256:
3758 case X86::BI__builtin_ia32_shuf_i64x2_256:
3759 case X86::BI__builtin_ia32_insertf64x2_512:
3760 case X86::BI__builtin_ia32_inserti64x2_512:
3761 case X86::BI__builtin_ia32_insertf32x4:
3762 case X86::BI__builtin_ia32_inserti32x4:
3763 i = 2; l = 0; u = 3;
3764 break;
3765 case X86::BI__builtin_ia32_vpermil2pd:
3766 case X86::BI__builtin_ia32_vpermil2pd256:
3767 case X86::BI__builtin_ia32_vpermil2ps:
3768 case X86::BI__builtin_ia32_vpermil2ps256:
3769 i = 3; l = 0; u = 3;
3770 break;
3771 case X86::BI__builtin_ia32_cmpb128_mask:
3772 case X86::BI__builtin_ia32_cmpw128_mask:
3773 case X86::BI__builtin_ia32_cmpd128_mask:
3774 case X86::BI__builtin_ia32_cmpq128_mask:
3775 case X86::BI__builtin_ia32_cmpb256_mask:
3776 case X86::BI__builtin_ia32_cmpw256_mask:
3777 case X86::BI__builtin_ia32_cmpd256_mask:
3778 case X86::BI__builtin_ia32_cmpq256_mask:
3779 case X86::BI__builtin_ia32_cmpb512_mask:
3780 case X86::BI__builtin_ia32_cmpw512_mask:
3781 case X86::BI__builtin_ia32_cmpd512_mask:
3782 case X86::BI__builtin_ia32_cmpq512_mask:
3783 case X86::BI__builtin_ia32_ucmpb128_mask:
3784 case X86::BI__builtin_ia32_ucmpw128_mask:
3785 case X86::BI__builtin_ia32_ucmpd128_mask:
3786 case X86::BI__builtin_ia32_ucmpq128_mask:
3787 case X86::BI__builtin_ia32_ucmpb256_mask:
3788 case X86::BI__builtin_ia32_ucmpw256_mask:
3789 case X86::BI__builtin_ia32_ucmpd256_mask:
3790 case X86::BI__builtin_ia32_ucmpq256_mask:
3791 case X86::BI__builtin_ia32_ucmpb512_mask:
3792 case X86::BI__builtin_ia32_ucmpw512_mask:
3793 case X86::BI__builtin_ia32_ucmpd512_mask:
3794 case X86::BI__builtin_ia32_ucmpq512_mask:
3795 case X86::BI__builtin_ia32_vpcomub:
3796 case X86::BI__builtin_ia32_vpcomuw:
3797 case X86::BI__builtin_ia32_vpcomud:
3798 case X86::BI__builtin_ia32_vpcomuq:
3799 case X86::BI__builtin_ia32_vpcomb:
3800 case X86::BI__builtin_ia32_vpcomw:
3801 case X86::BI__builtin_ia32_vpcomd:
3802 case X86::BI__builtin_ia32_vpcomq:
3803 case X86::BI__builtin_ia32_vec_set_v8hi:
3804 case X86::BI__builtin_ia32_vec_set_v8si:
3805 i = 2; l = 0; u = 7;
3806 break;
3807 case X86::BI__builtin_ia32_vpermilpd256:
3808 case X86::BI__builtin_ia32_roundps:
3809 case X86::BI__builtin_ia32_roundpd:
3810 case X86::BI__builtin_ia32_roundps256:
3811 case X86::BI__builtin_ia32_roundpd256:
3812 case X86::BI__builtin_ia32_getmantpd128_mask:
3813 case X86::BI__builtin_ia32_getmantpd256_mask:
3814 case X86::BI__builtin_ia32_getmantps128_mask:
3815 case X86::BI__builtin_ia32_getmantps256_mask:
3816 case X86::BI__builtin_ia32_getmantpd512_mask:
3817 case X86::BI__builtin_ia32_getmantps512_mask:
3818 case X86::BI__builtin_ia32_vec_ext_v16qi:
3819 case X86::BI__builtin_ia32_vec_ext_v16hi:
3820 i = 1; l = 0; u = 15;
3821 break;
3822 case X86::BI__builtin_ia32_pblendd128:
3823 case X86::BI__builtin_ia32_blendps:
3824 case X86::BI__builtin_ia32_blendpd256:
3825 case X86::BI__builtin_ia32_shufpd256:
3826 case X86::BI__builtin_ia32_roundss:
3827 case X86::BI__builtin_ia32_roundsd:
3828 case X86::BI__builtin_ia32_rangepd128_mask:
3829 case X86::BI__builtin_ia32_rangepd256_mask:
3830 case X86::BI__builtin_ia32_rangepd512_mask:
3831 case X86::BI__builtin_ia32_rangeps128_mask:
3832 case X86::BI__builtin_ia32_rangeps256_mask:
3833 case X86::BI__builtin_ia32_rangeps512_mask:
3834 case X86::BI__builtin_ia32_getmantsd_round_mask:
3835 case X86::BI__builtin_ia32_getmantss_round_mask:
3836 case X86::BI__builtin_ia32_vec_set_v16qi:
3837 case X86::BI__builtin_ia32_vec_set_v16hi:
3838 i = 2; l = 0; u = 15;
3839 break;
3840 case X86::BI__builtin_ia32_vec_ext_v32qi:
3841 i = 1; l = 0; u = 31;
3842 break;
3843 case X86::BI__builtin_ia32_cmpps:
3844 case X86::BI__builtin_ia32_cmpss:
3845 case X86::BI__builtin_ia32_cmppd:
3846 case X86::BI__builtin_ia32_cmpsd:
3847 case X86::BI__builtin_ia32_cmpps256:
3848 case X86::BI__builtin_ia32_cmppd256:
3849 case X86::BI__builtin_ia32_cmpps128_mask:
3850 case X86::BI__builtin_ia32_cmppd128_mask:
3851 case X86::BI__builtin_ia32_cmpps256_mask:
3852 case X86::BI__builtin_ia32_cmppd256_mask:
3853 case X86::BI__builtin_ia32_cmpps512_mask:
3854 case X86::BI__builtin_ia32_cmppd512_mask:
3855 case X86::BI__builtin_ia32_cmpsd_mask:
3856 case X86::BI__builtin_ia32_cmpss_mask:
3857 case X86::BI__builtin_ia32_vec_set_v32qi:
3858 i = 2; l = 0; u = 31;
3859 break;
3860 case X86::BI__builtin_ia32_permdf256:
3861 case X86::BI__builtin_ia32_permdi256:
3862 case X86::BI__builtin_ia32_permdf512:
3863 case X86::BI__builtin_ia32_permdi512:
3864 case X86::BI__builtin_ia32_vpermilps:
3865 case X86::BI__builtin_ia32_vpermilps256:
3866 case X86::BI__builtin_ia32_vpermilpd512:
3867 case X86::BI__builtin_ia32_vpermilps512:
3868 case X86::BI__builtin_ia32_pshufd:
3869 case X86::BI__builtin_ia32_pshufd256:
3870 case X86::BI__builtin_ia32_pshufd512:
3871 case X86::BI__builtin_ia32_pshufhw:
3872 case X86::BI__builtin_ia32_pshufhw256:
3873 case X86::BI__builtin_ia32_pshufhw512:
3874 case X86::BI__builtin_ia32_pshuflw:
3875 case X86::BI__builtin_ia32_pshuflw256:
3876 case X86::BI__builtin_ia32_pshuflw512:
3877 case X86::BI__builtin_ia32_vcvtps2ph:
3878 case X86::BI__builtin_ia32_vcvtps2ph_mask:
3879 case X86::BI__builtin_ia32_vcvtps2ph256:
3880 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3881 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3882 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3883 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3884 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3885 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3886 case X86::BI__builtin_ia32_rndscaleps_mask:
3887 case X86::BI__builtin_ia32_rndscalepd_mask:
3888 case X86::BI__builtin_ia32_reducepd128_mask:
3889 case X86::BI__builtin_ia32_reducepd256_mask:
3890 case X86::BI__builtin_ia32_reducepd512_mask:
3891 case X86::BI__builtin_ia32_reduceps128_mask:
3892 case X86::BI__builtin_ia32_reduceps256_mask:
3893 case X86::BI__builtin_ia32_reduceps512_mask:
3894 case X86::BI__builtin_ia32_prold512:
3895 case X86::BI__builtin_ia32_prolq512:
3896 case X86::BI__builtin_ia32_prold128:
3897 case X86::BI__builtin_ia32_prold256:
3898 case X86::BI__builtin_ia32_prolq128:
3899 case X86::BI__builtin_ia32_prolq256:
3900 case X86::BI__builtin_ia32_prord512:
3901 case X86::BI__builtin_ia32_prorq512:
3902 case X86::BI__builtin_ia32_prord128:
3903 case X86::BI__builtin_ia32_prord256:
3904 case X86::BI__builtin_ia32_prorq128:
3905 case X86::BI__builtin_ia32_prorq256:
3906 case X86::BI__builtin_ia32_fpclasspd128_mask:
3907 case X86::BI__builtin_ia32_fpclasspd256_mask:
3908 case X86::BI__builtin_ia32_fpclassps128_mask:
3909 case X86::BI__builtin_ia32_fpclassps256_mask:
3910 case X86::BI__builtin_ia32_fpclassps512_mask:
3911 case X86::BI__builtin_ia32_fpclasspd512_mask:
3912 case X86::BI__builtin_ia32_fpclasssd_mask:
3913 case X86::BI__builtin_ia32_fpclassss_mask:
3914 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3915 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3916 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3917 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3918 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3919 case X86::BI__builtin_ia32_psrldqi512_byteshift:
3920 case X86::BI__builtin_ia32_kshiftliqi:
3921 case X86::BI__builtin_ia32_kshiftlihi:
3922 case X86::BI__builtin_ia32_kshiftlisi:
3923 case X86::BI__builtin_ia32_kshiftlidi:
3924 case X86::BI__builtin_ia32_kshiftriqi:
3925 case X86::BI__builtin_ia32_kshiftrihi:
3926 case X86::BI__builtin_ia32_kshiftrisi:
3927 case X86::BI__builtin_ia32_kshiftridi:
3928 i = 1; l = 0; u = 255;
3929 break;
3930 case X86::BI__builtin_ia32_vperm2f128_pd256:
3931 case X86::BI__builtin_ia32_vperm2f128_ps256:
3932 case X86::BI__builtin_ia32_vperm2f128_si256:
3933 case X86::BI__builtin_ia32_permti256:
3934 case X86::BI__builtin_ia32_pblendw128:
3935 case X86::BI__builtin_ia32_pblendw256:
3936 case X86::BI__builtin_ia32_blendps256:
3937 case X86::BI__builtin_ia32_pblendd256:
3938 case X86::BI__builtin_ia32_palignr128:
3939 case X86::BI__builtin_ia32_palignr256:
3940 case X86::BI__builtin_ia32_palignr512:
3941 case X86::BI__builtin_ia32_alignq512:
3942 case X86::BI__builtin_ia32_alignd512:
3943 case X86::BI__builtin_ia32_alignd128:
3944 case X86::BI__builtin_ia32_alignd256:
3945 case X86::BI__builtin_ia32_alignq128:
3946 case X86::BI__builtin_ia32_alignq256:
3947 case X86::BI__builtin_ia32_vcomisd:
3948 case X86::BI__builtin_ia32_vcomiss:
3949 case X86::BI__builtin_ia32_shuf_f32x4:
3950 case X86::BI__builtin_ia32_shuf_f64x2:
3951 case X86::BI__builtin_ia32_shuf_i32x4:
3952 case X86::BI__builtin_ia32_shuf_i64x2:
3953 case X86::BI__builtin_ia32_shufpd512:
3954 case X86::BI__builtin_ia32_shufps:
3955 case X86::BI__builtin_ia32_shufps256:
3956 case X86::BI__builtin_ia32_shufps512:
3957 case X86::BI__builtin_ia32_dbpsadbw128:
3958 case X86::BI__builtin_ia32_dbpsadbw256:
3959 case X86::BI__builtin_ia32_dbpsadbw512:
3960 case X86::BI__builtin_ia32_vpshldd128:
3961 case X86::BI__builtin_ia32_vpshldd256:
3962 case X86::BI__builtin_ia32_vpshldd512:
3963 case X86::BI__builtin_ia32_vpshldq128:
3964 case X86::BI__builtin_ia32_vpshldq256:
3965 case X86::BI__builtin_ia32_vpshldq512:
3966 case X86::BI__builtin_ia32_vpshldw128:
3967 case X86::BI__builtin_ia32_vpshldw256:
3968 case X86::BI__builtin_ia32_vpshldw512:
3969 case X86::BI__builtin_ia32_vpshrdd128:
3970 case X86::BI__builtin_ia32_vpshrdd256:
3971 case X86::BI__builtin_ia32_vpshrdd512:
3972 case X86::BI__builtin_ia32_vpshrdq128:
3973 case X86::BI__builtin_ia32_vpshrdq256:
3974 case X86::BI__builtin_ia32_vpshrdq512:
3975 case X86::BI__builtin_ia32_vpshrdw128:
3976 case X86::BI__builtin_ia32_vpshrdw256:
3977 case X86::BI__builtin_ia32_vpshrdw512:
3978 i = 2; l = 0; u = 255;
3979 break;
3980 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3981 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3982 case X86::BI__builtin_ia32_fixupimmps512_mask:
3983 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3984 case X86::BI__builtin_ia32_fixupimmsd_mask:
3985 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3986 case X86::BI__builtin_ia32_fixupimmss_mask:
3987 case X86::BI__builtin_ia32_fixupimmss_maskz:
3988 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3989 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3990 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3991 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3992 case X86::BI__builtin_ia32_fixupimmps128_mask:
3993 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3994 case X86::BI__builtin_ia32_fixupimmps256_mask:
3995 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3996 case X86::BI__builtin_ia32_pternlogd512_mask:
3997 case X86::BI__builtin_ia32_pternlogd512_maskz:
3998 case X86::BI__builtin_ia32_pternlogq512_mask:
3999 case X86::BI__builtin_ia32_pternlogq512_maskz:
4000 case X86::BI__builtin_ia32_pternlogd128_mask:
4001 case X86::BI__builtin_ia32_pternlogd128_maskz:
4002 case X86::BI__builtin_ia32_pternlogd256_mask:
4003 case X86::BI__builtin_ia32_pternlogd256_maskz:
4004 case X86::BI__builtin_ia32_pternlogq128_mask:
4005 case X86::BI__builtin_ia32_pternlogq128_maskz:
4006 case X86::BI__builtin_ia32_pternlogq256_mask:
4007 case X86::BI__builtin_ia32_pternlogq256_maskz:
4008 i = 3; l = 0; u = 255;
4009 break;
4010 case X86::BI__builtin_ia32_gatherpfdpd:
4011 case X86::BI__builtin_ia32_gatherpfdps:
4012 case X86::BI__builtin_ia32_gatherpfqpd:
4013 case X86::BI__builtin_ia32_gatherpfqps:
4014 case X86::BI__builtin_ia32_scatterpfdpd:
4015 case X86::BI__builtin_ia32_scatterpfdps:
4016 case X86::BI__builtin_ia32_scatterpfqpd:
4017 case X86::BI__builtin_ia32_scatterpfqps:
4018 i = 4; l = 2; u = 3;
4019 break;
4020 case X86::BI__builtin_ia32_reducesd_mask:
4021 case X86::BI__builtin_ia32_reducess_mask:
4022 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4023 case X86::BI__builtin_ia32_rndscaless_round_mask:
4024 i = 4; l = 0; u = 255;
4025 break;
4026 }
4027
4028 // Note that we don't force a hard error on the range check here, allowing
4029 // template-generated or macro-generated dead code to potentially have out-of-
4030 // range values. These need to code generate, but don't need to necessarily
4031 // make any sense. We use a warning that defaults to an error.
4032 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4033}
4034
4035/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4036/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4037/// Returns true when the format fits the function and the FormatStringInfo has
4038/// been populated.
4039bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4040 FormatStringInfo *FSI) {
4041 FSI->HasVAListArg = Format->getFirstArg() == 0;
4042 FSI->FormatIdx = Format->getFormatIdx() - 1;
4043 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4044
4045 // The way the format attribute works in GCC, the implicit this argument
4046 // of member functions is counted. However, it doesn't appear in our own
4047 // lists, so decrement format_idx in that case.
4048 if (IsCXXMember) {
4049 if(FSI->FormatIdx == 0)
4050 return false;
4051 --FSI->FormatIdx;
4052 if (FSI->FirstDataArg != 0)
4053 --FSI->FirstDataArg;
4054 }
4055 return true;
4056}
4057
4058/// Checks if a the given expression evaluates to null.
4059///
4060/// Returns true if the value evaluates to null.
4061static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4062 // If the expression has non-null type, it doesn't evaluate to null.
4063 if (auto nullability
4064 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4065 if (*nullability == NullabilityKind::NonNull)
4066 return false;
4067 }
4068
4069 // As a special case, transparent unions initialized with zero are
4070 // considered null for the purposes of the nonnull attribute.
4071 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4072 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4073 if (const CompoundLiteralExpr *CLE =
4074 dyn_cast<CompoundLiteralExpr>(Expr))
4075 if (const InitListExpr *ILE =
4076 dyn_cast<InitListExpr>(CLE->getInitializer()))
4077 Expr = ILE->getInit(0);
4078 }
4079
4080 bool Result;
4081 return (!Expr->isValueDependent() &&
4082 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4083 !Result);
4084}
4085
4086static void CheckNonNullArgument(Sema &S,
4087 const Expr *ArgExpr,
4088 SourceLocation CallSiteLoc) {
4089 if (CheckNonNullExpr(S, ArgExpr))
4090 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4091 S.PDiag(diag::warn_null_arg)
4092 << ArgExpr->getSourceRange());
4093}
4094
4095bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4096 FormatStringInfo FSI;
4097 if ((GetFormatStringType(Format) == FST_NSString) &&
4098 getFormatStringInfo(Format, false, &FSI)) {
4099 Idx = FSI.FormatIdx;
4100 return true;
4101 }
4102 return false;
4103}
4104
4105/// Diagnose use of %s directive in an NSString which is being passed
4106/// as formatting string to formatting method.
4107static void
4108DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4109 const NamedDecl *FDecl,
4110 Expr **Args,
4111 unsigned NumArgs) {
4112 unsigned Idx = 0;
4113 bool Format = false;
4114 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4115 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4116 Idx = 2;
4117 Format = true;
4118 }
4119 else
4120 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4121 if (S.GetFormatNSStringIdx(I, Idx)) {
4122 Format = true;
4123 break;
4124 }
4125 }
4126 if (!Format || NumArgs <= Idx)
4127 return;
4128 const Expr *FormatExpr = Args[Idx];
4129 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4130 FormatExpr = CSCE->getSubExpr();
4131 const StringLiteral *FormatString;
4132 if (const ObjCStringLiteral *OSL =
4133 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4134 FormatString = OSL->getString();
4135 else
4136 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4137 if (!FormatString)
4138 return;
4139 if (S.FormatStringHasSArg(FormatString)) {
4140 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4141 << "%s" << 1 << 1;
4142 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4143 << FDecl->getDeclName();
4144 }
4145}
4146
4147/// Determine whether the given type has a non-null nullability annotation.
4148static bool isNonNullType(ASTContext &ctx, QualType type) {
4149 if (auto nullability = type->getNullability(ctx))
4150 return *nullability == NullabilityKind::NonNull;
4151
4152 return false;
4153}
4154
4155static void CheckNonNullArguments(Sema &S,
4156 const NamedDecl *FDecl,
4157 const FunctionProtoType *Proto,
4158 ArrayRef<const Expr *> Args,
4159 SourceLocation CallSiteLoc) {
4160 assert((FDecl || Proto) && "Need a function declaration or prototype")(((FDecl || Proto) && "Need a function declaration or prototype"
) ? static_cast<void> (0) : __assert_fail ("(FDecl || Proto) && \"Need a function declaration or prototype\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 4160, __PRETTY_FUNCTION__))
;
4161
4162 // Already checked by by constant evaluator.
4163 if (S.isConstantEvaluated())
4164 return;
4165 // Check the attributes attached to the method/function itself.
4166 llvm::SmallBitVector NonNullArgs;
4167 if (FDecl) {
4168 // Handle the nonnull attribute on the function/method declaration itself.
4169 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4170 if (!NonNull->args_size()) {
4171 // Easy case: all pointer arguments are nonnull.
4172 for (const auto *Arg : Args)
4173 if (S.isValidPointerAttrType(Arg->getType()))
4174 CheckNonNullArgument(S, Arg, CallSiteLoc);
4175 return;
4176 }
4177
4178 for (const ParamIdx &Idx : NonNull->args()) {
4179 unsigned IdxAST = Idx.getASTIndex();
4180 if (IdxAST >= Args.size())
4181 continue;
4182 if (NonNullArgs.empty())
4183 NonNullArgs.resize(Args.size());
4184 NonNullArgs.set(IdxAST);
4185 }
4186 }
4187 }
4188
4189 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4190 // Handle the nonnull attribute on the parameters of the
4191 // function/method.
4192 ArrayRef<ParmVarDecl*> parms;
4193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4194 parms = FD->parameters();
4195 else
4196 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4197
4198 unsigned ParamIndex = 0;
4199 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4200 I != E; ++I, ++ParamIndex) {
4201 const ParmVarDecl *PVD = *I;
4202 if (PVD->hasAttr<NonNullAttr>() ||
4203 isNonNullType(S.Context, PVD->getType())) {
4204 if (NonNullArgs.empty())
4205 NonNullArgs.resize(Args.size());
4206
4207 NonNullArgs.set(ParamIndex);
4208 }
4209 }
4210 } else {
4211 // If we have a non-function, non-method declaration but no
4212 // function prototype, try to dig out the function prototype.
4213 if (!Proto) {
4214 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4215 QualType type = VD->getType().getNonReferenceType();
4216 if (auto pointerType = type->getAs<PointerType>())
4217 type = pointerType->getPointeeType();
4218 else if (auto blockType = type->getAs<BlockPointerType>())
4219 type = blockType->getPointeeType();
4220 // FIXME: data member pointers?
4221
4222 // Dig out the function prototype, if there is one.
4223 Proto = type->getAs<FunctionProtoType>();
4224 }
4225 }
4226
4227 // Fill in non-null argument information from the nullability
4228 // information on the parameter types (if we have them).
4229 if (Proto) {
4230 unsigned Index = 0;
4231 for (auto paramType : Proto->getParamTypes()) {
4232 if (isNonNullType(S.Context, paramType)) {
4233 if (NonNullArgs.empty())
4234 NonNullArgs.resize(Args.size());
4235
4236 NonNullArgs.set(Index);
4237 }
4238
4239 ++Index;
4240 }
4241 }
4242 }
4243
4244 // Check for non-null arguments.
4245 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4246 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4247 if (NonNullArgs[ArgIndex])
4248 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4249 }
4250}
4251
4252/// Handles the checks for format strings, non-POD arguments to vararg
4253/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4254/// attributes.
4255void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4256 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4257 bool IsMemberFunction, SourceLocation Loc,
4258 SourceRange Range, VariadicCallType CallType) {
4259 // FIXME: We should check as much as we can in the template definition.
4260 if (CurContext->isDependentContext())
4261 return;
4262
4263 // Printf and scanf checking.
4264 llvm::SmallBitVector CheckedVarArgs;
4265 if (FDecl) {
4266 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4267 // Only create vector if there are format attributes.
4268 CheckedVarArgs.resize(Args.size());
4269
4270 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4271 CheckedVarArgs);
4272 }
4273 }
4274
4275 // Refuse POD arguments that weren't caught by the format string
4276 // checks above.
4277 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4278 if (CallType != VariadicDoesNotApply &&
4279 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4280 unsigned NumParams = Proto ? Proto->getNumParams()
4281 : FDecl && isa<FunctionDecl>(FDecl)
4282 ? cast<FunctionDecl>(FDecl)->getNumParams()
4283 : FDecl && isa<ObjCMethodDecl>(FDecl)
4284 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4285 : 0;
4286
4287 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4288 // Args[ArgIdx] can be null in malformed code.
4289 if (const Expr *Arg = Args[ArgIdx]) {
4290 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4291 checkVariadicArgument(Arg, CallType);
4292 }
4293 }
4294 }
4295
4296 if (FDecl || Proto) {
4297 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4298
4299 // Type safety checking.
4300 if (FDecl) {
4301 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4302 CheckArgumentWithTypeTag(I, Args, Loc);
4303 }
4304 }
4305
4306 if (FD)
4307 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4308}
4309
4310/// CheckConstructorCall - Check a constructor call for correctness and safety
4311/// properties not enforced by the C type system.
4312void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4313 ArrayRef<const Expr *> Args,
4314 const FunctionProtoType *Proto,
4315 SourceLocation Loc) {
4316 VariadicCallType CallType =
4317 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4318 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4319 Loc, SourceRange(), CallType);
4320}
4321
4322/// CheckFunctionCall - Check a direct function call for various correctness
4323/// and safety properties not strictly enforced by the C type system.
4324bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4325 const FunctionProtoType *Proto) {
4326 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4327 isa<CXXMethodDecl>(FDecl);
4328 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4329 IsMemberOperatorCall;
4330 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4331 TheCall->getCallee());
4332 Expr** Args = TheCall->getArgs();
4333 unsigned NumArgs = TheCall->getNumArgs();
4334
4335 Expr *ImplicitThis = nullptr;
4336 if (IsMemberOperatorCall) {
4337 // If this is a call to a member operator, hide the first argument
4338 // from checkCall.
4339 // FIXME: Our choice of AST representation here is less than ideal.
4340 ImplicitThis = Args[0];
4341 ++Args;
4342 --NumArgs;
4343 } else if (IsMemberFunction)
4344 ImplicitThis =
4345 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4346
4347 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4348 IsMemberFunction, TheCall->getRParenLoc(),
4349 TheCall->getCallee()->getSourceRange(), CallType);
4350
4351 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4352 // None of the checks below are needed for functions that don't have
4353 // simple names (e.g., C++ conversion functions).
4354 if (!FnInfo)
4355 return false;
4356
4357 CheckAbsoluteValueFunction(TheCall, FDecl);
4358 CheckMaxUnsignedZero(TheCall, FDecl);
4359
4360 if (getLangOpts().ObjC)
4361 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4362
4363 unsigned CMId = FDecl->getMemoryFunctionKind();
4364 if (CMId == 0)
4365 return false;
4366
4367 // Handle memory setting and copying functions.
4368// if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4369// CheckStrlcpycatArguments(TheCall, FnInfo);
4370// else
4371 if (CMId == Builtin::BIstrncat)
4372 CheckStrncatArguments(TheCall, FnInfo);
4373 else
4374 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4375
4376 return false;
4377}
4378
4379bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4380 ArrayRef<const Expr *> Args) {
4381 VariadicCallType CallType =
4382 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4383
4384 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4385 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4386 CallType);
4387
4388 return false;
4389}
4390
4391bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4392 const FunctionProtoType *Proto) {
4393 QualType Ty;
4394 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4395 Ty = V->getType().getNonReferenceType();
4396 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4397 Ty = F->getType().getNonReferenceType();
4398 else
4399 return false;
4400
4401 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4402 !Ty->isFunctionProtoType())
4403 return false;
4404
4405 VariadicCallType CallType;
4406 if (!Proto || !Proto->isVariadic()) {
4407 CallType = VariadicDoesNotApply;
4408 } else if (Ty->isBlockPointerType()) {
4409 CallType = VariadicBlock;
4410 } else { // Ty->isFunctionPointerType()
4411 CallType = VariadicFunction;
4412 }
4413
4414 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4415 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4416 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4417 TheCall->getCallee()->getSourceRange(), CallType);
4418
4419 return false;
4420}
4421
4422/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4423/// such as function pointers returned from functions.
4424bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4425 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4426 TheCall->getCallee());
4427 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4428 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4429 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4430 TheCall->getCallee()->getSourceRange(), CallType);
4431
4432 return false;
4433}
4434
4435static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4436 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4437 return false;
4438
4439 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4440 switch (Op) {
4441 case AtomicExpr::AO__c11_atomic_init:
4442 case AtomicExpr::AO__opencl_atomic_init:
4443 llvm_unreachable("There is no ordering argument for an init")::llvm::llvm_unreachable_internal("There is no ordering argument for an init"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 4443)
;
4444
4445 case AtomicExpr::AO__c11_atomic_load:
4446 case AtomicExpr::AO__opencl_atomic_load:
4447 case AtomicExpr::AO__atomic_load_n:
4448 case AtomicExpr::AO__atomic_load:
4449 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4450 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4451
4452 case AtomicExpr::AO__c11_atomic_store:
4453 case AtomicExpr::AO__opencl_atomic_store:
4454 case AtomicExpr::AO__atomic_store:
4455 case AtomicExpr::AO__atomic_store_n:
4456 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4457 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4458 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4459
4460 default:
4461 return true;
4462 }
4463}
4464
4465ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4466 AtomicExpr::AtomicOp Op) {
4467 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4468 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4469 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4470 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4471 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4472 Op);
4473}
4474
4475ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4476 SourceLocation RParenLoc, MultiExprArg Args,
4477 AtomicExpr::AtomicOp Op,
4478 AtomicArgumentOrder ArgOrder) {
4479 // All the non-OpenCL operations take one of the following forms.
4480 // The OpenCL operations take the __c11 forms with one extra argument for
4481 // synchronization scope.
4482 enum {
4483 // C __c11_atomic_init(A *, C)
4484 Init,
4485
4486 // C __c11_atomic_load(A *, int)
4487 Load,
4488
4489 // void __atomic_load(A *, CP, int)
4490 LoadCopy,
4491
4492 // void __atomic_store(A *, CP, int)
4493 Copy,
4494
4495 // C __c11_atomic_add(A *, M, int)
4496 Arithmetic,
4497
4498 // C __atomic_exchange_n(A *, CP, int)
4499 Xchg,
4500
4501 // void __atomic_exchange(A *, C *, CP, int)
4502 GNUXchg,
4503
4504 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4505 C11CmpXchg,
4506
4507 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4508 GNUCmpXchg
4509 } Form = Init;
4510
4511 const unsigned NumForm = GNUCmpXchg + 1;
4512 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4513 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4514 // where:
4515 // C is an appropriate type,
4516 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4517 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4518 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4519 // the int parameters are for orderings.
4520
4521 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4522 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4523 "need to update code for modified forms");
4524 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4525 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4526 AtomicExpr::AO__atomic_load,
4527 "need to update code for modified C11 atomics");
4528 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4529 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4530 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4531 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4532 IsOpenCL;
4533 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4534 Op == AtomicExpr::AO__atomic_store_n ||
4535 Op == AtomicExpr::AO__atomic_exchange_n ||
4536 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4537 bool IsAddSub = false;
4538 bool IsMinMax = false;
4539
4540 switch (Op) {
4541 case AtomicExpr::AO__c11_atomic_init:
4542 case AtomicExpr::AO__opencl_atomic_init:
4543 Form = Init;
4544 break;
4545
4546 case AtomicExpr::AO__c11_atomic_load:
4547 case AtomicExpr::AO__opencl_atomic_load:
4548 case AtomicExpr::AO__atomic_load_n:
4549 Form = Load;
4550 break;
4551
4552 case AtomicExpr::AO__atomic_load:
4553 Form = LoadCopy;
4554 break;
4555
4556 case AtomicExpr::AO__c11_atomic_store:
4557 case AtomicExpr::AO__opencl_atomic_store:
4558 case AtomicExpr::AO__atomic_store:
4559 case AtomicExpr::AO__atomic_store_n:
4560 Form = Copy;
4561 break;
4562
4563 case AtomicExpr::AO__c11_atomic_fetch_add:
4564 case AtomicExpr::AO__c11_atomic_fetch_sub:
4565 case AtomicExpr::AO__opencl_atomic_fetch_add:
4566 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4567 case AtomicExpr::AO__opencl_atomic_fetch_min:
4568 case AtomicExpr::AO__opencl_atomic_fetch_max:
4569 case AtomicExpr::AO__atomic_fetch_add:
4570 case AtomicExpr::AO__atomic_fetch_sub:
4571 case AtomicExpr::AO__atomic_add_fetch:
4572 case AtomicExpr::AO__atomic_sub_fetch:
4573 IsAddSub = true;
4574 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4575 case AtomicExpr::AO__c11_atomic_fetch_and:
4576 case AtomicExpr::AO__c11_atomic_fetch_or:
4577 case AtomicExpr::AO__c11_atomic_fetch_xor:
4578 case AtomicExpr::AO__opencl_atomic_fetch_and:
4579 case AtomicExpr::AO__opencl_atomic_fetch_or:
4580 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4581 case AtomicExpr::AO__atomic_fetch_and:
4582 case AtomicExpr::AO__atomic_fetch_or:
4583 case AtomicExpr::AO__atomic_fetch_xor:
4584 case AtomicExpr::AO__atomic_fetch_nand:
4585 case AtomicExpr::AO__atomic_and_fetch:
4586 case AtomicExpr::AO__atomic_or_fetch:
4587 case AtomicExpr::AO__atomic_xor_fetch:
4588 case AtomicExpr::AO__atomic_nand_fetch:
4589 Form = Arithmetic;
4590 break;
4591
4592 case AtomicExpr::AO__atomic_fetch_min:
4593 case AtomicExpr::AO__atomic_fetch_max:
4594 IsMinMax = true;
4595 Form = Arithmetic;
4596 break;
4597
4598 case AtomicExpr::AO__c11_atomic_exchange:
4599 case AtomicExpr::AO__opencl_atomic_exchange:
4600 case AtomicExpr::AO__atomic_exchange_n:
4601 Form = Xchg;
4602 break;
4603
4604 case AtomicExpr::AO__atomic_exchange:
4605 Form = GNUXchg;
4606 break;
4607
4608 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4609 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4610 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4611 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4612 Form = C11CmpXchg;
4613 break;
4614
4615 case AtomicExpr::AO__atomic_compare_exchange:
4616 case AtomicExpr::AO__atomic_compare_exchange_n:
4617 Form = GNUCmpXchg;
4618 break;
4619 }
4620
4621 unsigned AdjustedNumArgs = NumArgs[Form];
4622 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4623 ++AdjustedNumArgs;
4624 // Check we have the right number of arguments.
4625 if (Args.size() < AdjustedNumArgs) {
4626 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4627 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4628 << ExprRange;
4629 return ExprError();
4630 } else if (Args.size() > AdjustedNumArgs) {
4631 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4632 diag::err_typecheck_call_too_many_args)
4633 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4634 << ExprRange;
4635 return ExprError();
4636 }
4637
4638 // Inspect the first argument of the atomic operation.
4639 Expr *Ptr = Args[0];
4640 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4641 if (ConvertedPtr.isInvalid())
4642 return ExprError();
4643
4644 Ptr = ConvertedPtr.get();
4645 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4646 if (!pointerType) {
4647 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4648 << Ptr->getType() << Ptr->getSourceRange();
4649 return ExprError();
4650 }
4651
4652 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4653 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4654 QualType ValType = AtomTy; // 'C'
4655 if (IsC11) {
4656 if (!AtomTy->isAtomicType()) {
4657 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4658 << Ptr->getType() << Ptr->getSourceRange();
4659 return ExprError();
4660 }
4661 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4662 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4663 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4664 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4665 << Ptr->getSourceRange();
4666 return ExprError();
4667 }
4668 ValType = AtomTy->getAs<AtomicType>()->getValueType();
4669 } else if (Form != Load && Form != LoadCopy) {
4670 if (ValType.isConstQualified()) {
4671 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4672 << Ptr->getType() << Ptr->getSourceRange();
4673 return ExprError();
4674 }
4675 }
4676
4677 // For an arithmetic operation, the implied arithmetic must be well-formed.
4678 if (Form == Arithmetic) {
4679 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4680 if (IsAddSub && !ValType->isIntegerType()
4681 && !ValType->isPointerType()) {
4682 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4683 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4684 return ExprError();
4685 }
4686 if (IsMinMax) {
4687 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4688 if (!BT || (BT->getKind() != BuiltinType::Int &&
4689 BT->getKind() != BuiltinType::UInt)) {
4690 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
4691 return ExprError();
4692 }
4693 }
4694 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4695 Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
4696 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4697 return ExprError();
4698 }
4699 if (IsC11 && ValType->isPointerType() &&
4700 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4701 diag::err_incomplete_type)) {
4702 return ExprError();
4703 }
4704 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4705 // For __atomic_*_n operations, the value type must be a scalar integral or
4706 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4707 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4708 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4709 return ExprError();
4710 }
4711
4712 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4713 !AtomTy->isScalarType()) {
4714 // For GNU atomics, require a trivially-copyable type. This is not part of
4715 // the GNU atomics specification, but we enforce it for sanity.
4716 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4717 << Ptr->getType() << Ptr->getSourceRange();
4718 return ExprError();
4719 }
4720
4721 switch (ValType.getObjCLifetime()) {
4722 case Qualifiers::OCL_None:
4723 case Qualifiers::OCL_ExplicitNone:
4724 // okay
4725 break;
4726
4727 case Qualifiers::OCL_Weak:
4728 case Qualifiers::OCL_Strong:
4729 case Qualifiers::OCL_Autoreleasing:
4730 // FIXME: Can this happen? By this point, ValType should be known
4731 // to be trivially copyable.
4732 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4733 << ValType << Ptr->getSourceRange();
4734 return ExprError();
4735 }
4736
4737 // All atomic operations have an overload which takes a pointer to a volatile
4738 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4739 // into the result or the other operands. Similarly atomic_load takes a
4740 // pointer to a const 'A'.
4741 ValType.removeLocalVolatile();
4742 ValType.removeLocalConst();
4743 QualType ResultType = ValType;
4744 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4745 Form == Init)
4746 ResultType = Context.VoidTy;
4747 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4748 ResultType = Context.BoolTy;
4749
4750 // The type of a parameter passed 'by value'. In the GNU atomics, such
4751 // arguments are actually passed as pointers.
4752 QualType ByValType = ValType; // 'CP'
4753 bool IsPassedByAddress = false;
4754 if (!IsC11 && !IsN) {
4755 ByValType = Ptr->getType();
4756 IsPassedByAddress = true;
4757 }
4758
4759 SmallVector<Expr *, 5> APIOrderedArgs;
4760 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4761 APIOrderedArgs.push_back(Args[0]);
4762 switch (Form) {
4763 case Init:
4764 case Load:
4765 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4766 break;
4767 case LoadCopy:
4768 case Copy:
4769 case Arithmetic:
4770 case Xchg:
4771 APIOrderedArgs.push_back(Args[2]); // Val1
4772 APIOrderedArgs.push_back(Args[1]); // Order
4773 break;
4774 case GNUXchg:
4775 APIOrderedArgs.push_back(Args[2]); // Val1
4776 APIOrderedArgs.push_back(Args[3]); // Val2
4777 APIOrderedArgs.push_back(Args[1]); // Order
4778 break;
4779 case C11CmpXchg:
4780 APIOrderedArgs.push_back(Args[2]); // Val1
4781 APIOrderedArgs.push_back(Args[4]); // Val2
4782 APIOrderedArgs.push_back(Args[1]); // Order
4783 APIOrderedArgs.push_back(Args[3]); // OrderFail
4784 break;
4785 case GNUCmpXchg:
4786 APIOrderedArgs.push_back(Args[2]); // Val1
4787 APIOrderedArgs.push_back(Args[4]); // Val2
4788 APIOrderedArgs.push_back(Args[5]); // Weak
4789 APIOrderedArgs.push_back(Args[1]); // Order
4790 APIOrderedArgs.push_back(Args[3]); // OrderFail
4791 break;
4792 }
4793 } else
4794 APIOrderedArgs.append(Args.begin(), Args.end());
4795
4796 // The first argument's non-CV pointer type is used to deduce the type of
4797 // subsequent arguments, except for:
4798 // - weak flag (always converted to bool)
4799 // - memory order (always converted to int)
4800 // - scope (always converted to int)
4801 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4802 QualType Ty;
4803 if (i < NumVals[Form] + 1) {
4804 switch (i) {
4805 case 0:
4806 // The first argument is always a pointer. It has a fixed type.
4807 // It is always dereferenced, a nullptr is undefined.
4808 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4809 // Nothing else to do: we already know all we want about this pointer.
4810 continue;
4811 case 1:
4812 // The second argument is the non-atomic operand. For arithmetic, this
4813 // is always passed by value, and for a compare_exchange it is always
4814 // passed by address. For the rest, GNU uses by-address and C11 uses
4815 // by-value.
4816 assert(Form != Load)((Form != Load) ? static_cast<void> (0) : __assert_fail
("Form != Load", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 4816, __PRETTY_FUNCTION__))
;
4817 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4818 Ty = ValType;
4819 else if (Form == Copy || Form == Xchg) {
4820 if (IsPassedByAddress) {
4821 // The value pointer is always dereferenced, a nullptr is undefined.
4822 CheckNonNullArgument(*this, APIOrderedArgs[i],
4823 ExprRange.getBegin());
4824 }
4825 Ty = ByValType;
4826 } else if (Form == Arithmetic)
4827 Ty = Context.getPointerDiffType();
4828 else {
4829 Expr *ValArg = APIOrderedArgs[i];
4830 // The value pointer is always dereferenced, a nullptr is undefined.
4831 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4832 LangAS AS = LangAS::Default;
4833 // Keep address space of non-atomic pointer type.
4834 if (const PointerType *PtrTy =
4835 ValArg->getType()->getAs<PointerType>()) {
4836 AS = PtrTy->getPointeeType().getAddressSpace();
4837 }
4838 Ty = Context.getPointerType(
4839 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4840 }
4841 break;
4842 case 2:
4843 // The third argument to compare_exchange / GNU exchange is the desired
4844 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4845 if (IsPassedByAddress)
4846 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4847 Ty = ByValType;
4848 break;
4849 case 3:
4850 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4851 Ty = Context.BoolTy;
4852 break;
4853 }
4854 } else {
4855 // The order(s) and scope are always converted to int.
4856 Ty = Context.IntTy;
4857 }
4858
4859 InitializedEntity Entity =
4860 InitializedEntity::InitializeParameter(Context, Ty, false);
4861 ExprResult Arg = APIOrderedArgs[i];
4862 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4863 if (Arg.isInvalid())
4864 return true;
4865 APIOrderedArgs[i] = Arg.get();
4866 }
4867
4868 // Permute the arguments into a 'consistent' order.
4869 SmallVector<Expr*, 5> SubExprs;
4870 SubExprs.push_back(Ptr);
4871 switch (Form) {
4872 case Init:
4873 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4874 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4875 break;
4876 case Load:
4877 SubExprs.push_back(APIOrderedArgs[1]); // Order
4878 break;
4879 case LoadCopy:
4880 case Copy:
4881 case Arithmetic:
4882 case Xchg:
4883 SubExprs.push_back(APIOrderedArgs[2]); // Order
4884 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4885 break;
4886 case GNUXchg:
4887 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4888 SubExprs.push_back(APIOrderedArgs[3]); // Order
4889 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4890 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4891 break;
4892 case C11CmpXchg:
4893 SubExprs.push_back(APIOrderedArgs[3]); // Order
4894 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4895 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4896 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4897 break;
4898 case GNUCmpXchg:
4899 SubExprs.push_back(APIOrderedArgs[4]); // Order
4900 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4901 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4902 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4903 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4904 break;
4905 }
4906
4907 if (SubExprs.size() >= 2 && Form != Init) {
4908 llvm::APSInt Result(32);
4909 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4910 !isValidOrderingForOp(Result.getSExtValue(), Op))
4911 Diag(SubExprs[1]->getBeginLoc(),
4912 diag::warn_atomic_op_has_invalid_memory_order)
4913 << SubExprs[1]->getSourceRange();
4914 }
4915
4916 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4917 auto *Scope = Args[Args.size() - 1];
4918 llvm::APSInt Result(32);
4919 if (Scope->isIntegerConstantExpr(Result, Context) &&
4920 !ScopeModel->isValid(Result.getZExtValue())) {
4921 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4922 << Scope->getSourceRange();
4923 }
4924 SubExprs.push_back(Scope);
4925 }
4926
4927 AtomicExpr *AE = new (Context)
4928 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4929
4930 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4931 Op == AtomicExpr::AO__c11_atomic_store ||
4932 Op == AtomicExpr::AO__opencl_atomic_load ||
4933 Op == AtomicExpr::AO__opencl_atomic_store ) &&
4934 Context.AtomicUsesUnsupportedLibcall(AE))
4935 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4936 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4937 Op == AtomicExpr::AO__opencl_atomic_load)
4938 ? 0
4939 : 1);
4940
4941 return AE;
4942}
4943
4944/// checkBuiltinArgument - Given a call to a builtin function, perform
4945/// normal type-checking on the given argument, updating the call in
4946/// place. This is useful when a builtin function requires custom
4947/// type-checking for some of its arguments but not necessarily all of
4948/// them.
4949///
4950/// Returns true on error.
4951static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4952 FunctionDecl *Fn = E->getDirectCallee();
4953 assert(Fn && "builtin call without direct callee!")((Fn && "builtin call without direct callee!") ? static_cast
<void> (0) : __assert_fail ("Fn && \"builtin call without direct callee!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 4953, __PRETTY_FUNCTION__))
;
4954
4955 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4956 InitializedEntity Entity =
4957 InitializedEntity::InitializeParameter(S.Context, Param);
4958
4959 ExprResult Arg = E->getArg(0);
4960 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4961 if (Arg.isInvalid())
4962 return true;
4963
4964 E->setArg(ArgIndex, Arg.get());
4965 return false;
4966}
4967
4968/// We have a call to a function like __sync_fetch_and_add, which is an
4969/// overloaded function based on the pointer type of its first argument.
4970/// The main BuildCallExpr routines have already promoted the types of
4971/// arguments because all of these calls are prototyped as void(...).
4972///
4973/// This function goes through and does final semantic checking for these
4974/// builtins, as well as generating any warnings.
4975ExprResult
4976Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4977 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4978 Expr *Callee = TheCall->getCallee();
4979 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4980 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4981
4982 // Ensure that we have at least one argument to do type inference from.
4983 if (TheCall->getNumArgs() < 1) {
4984 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4985 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4986 return ExprError();
4987 }
4988
4989 // Inspect the first argument of the atomic builtin. This should always be
4990 // a pointer type, whose element is an integral scalar or pointer type.
4991 // Because it is a pointer type, we don't have to worry about any implicit
4992 // casts here.
4993 // FIXME: We don't allow floating point scalars as input.
4994 Expr *FirstArg = TheCall->getArg(0);
4995 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4996 if (FirstArgResult.isInvalid())
4997 return ExprError();
4998 FirstArg = FirstArgResult.get();
4999 TheCall->setArg(0, FirstArg);
5000
5001 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5002 if (!pointerType) {
5003 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5004 << FirstArg->getType() << FirstArg->getSourceRange();
5005 return ExprError();
5006 }
5007
5008 QualType ValType = pointerType->getPointeeType();
5009 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5010 !ValType->isBlockPointerType()) {
5011 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5012 << FirstArg->getType() << FirstArg->getSourceRange();
5013 return ExprError();
5014 }
5015
5016 if (ValType.isConstQualified()) {
5017 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5018 << FirstArg->getType() << FirstArg->getSourceRange();
5019 return ExprError();
5020 }
5021
5022 switch (ValType.getObjCLifetime()) {
5023 case Qualifiers::OCL_None:
5024 case Qualifiers::OCL_ExplicitNone:
5025 // okay
5026 break;
5027
5028 case Qualifiers::OCL_Weak:
5029 case Qualifiers::OCL_Strong:
5030 case Qualifiers::OCL_Autoreleasing:
5031 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5032 << ValType << FirstArg->getSourceRange();
5033 return ExprError();
5034 }
5035
5036 // Strip any qualifiers off ValType.
5037 ValType = ValType.getUnqualifiedType();
5038
5039 // The majority of builtins return a value, but a few have special return
5040 // types, so allow them to override appropriately below.
5041 QualType ResultType = ValType;
5042
5043 // We need to figure out which concrete builtin this maps onto. For example,
5044 // __sync_fetch_and_add with a 2 byte object turns into
5045 // __sync_fetch_and_add_2.
5046#define BUILTIN_ROW(x) \
5047 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5048 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5049
5050 static const unsigned BuiltinIndices[][5] = {
5051 BUILTIN_ROW(__sync_fetch_and_add),
5052 BUILTIN_ROW(__sync_fetch_and_sub),
5053 BUILTIN_ROW(__sync_fetch_and_or),
5054 BUILTIN_ROW(__sync_fetch_and_and),
5055 BUILTIN_ROW(__sync_fetch_and_xor),
5056 BUILTIN_ROW(__sync_fetch_and_nand),
5057
5058 BUILTIN_ROW(__sync_add_and_fetch),
5059 BUILTIN_ROW(__sync_sub_and_fetch),
5060 BUILTIN_ROW(__sync_and_and_fetch),
5061 BUILTIN_ROW(__sync_or_and_fetch),
5062 BUILTIN_ROW(__sync_xor_and_fetch),
5063 BUILTIN_ROW(__sync_nand_and_fetch),
5064
5065 BUILTIN_ROW(__sync_val_compare_and_swap),
5066 BUILTIN_ROW(__sync_bool_compare_and_swap),
5067 BUILTIN_ROW(__sync_lock_test_and_set),
5068 BUILTIN_ROW(__sync_lock_release),
5069 BUILTIN_ROW(__sync_swap)
5070 };
5071#undef BUILTIN_ROW
5072
5073 // Determine the index of the size.
5074 unsigned SizeIndex;
5075 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5076 case 1: SizeIndex = 0; break;
5077 case 2: SizeIndex = 1; break;
5078 case 4: SizeIndex = 2; break;
5079 case 8: SizeIndex = 3; break;
5080 case 16: SizeIndex = 4; break;
5081 default:
5082 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5083 << FirstArg->getType() << FirstArg->getSourceRange();
5084 return ExprError();
5085 }
5086
5087 // Each of these builtins has one pointer argument, followed by some number of
5088 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5089 // that we ignore. Find out which row of BuiltinIndices to read from as well
5090 // as the number of fixed args.
5091 unsigned BuiltinID = FDecl->getBuiltinID();
5092 unsigned BuiltinIndex, NumFixed = 1;
5093 bool WarnAboutSemanticsChange = false;
5094 switch (BuiltinID) {
5095 default: llvm_unreachable("Unknown overloaded atomic builtin!")::llvm::llvm_unreachable_internal("Unknown overloaded atomic builtin!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5095)
;
5096 case Builtin::BI__sync_fetch_and_add:
5097 case Builtin::BI__sync_fetch_and_add_1:
5098 case Builtin::BI__sync_fetch_and_add_2:
5099 case Builtin::BI__sync_fetch_and_add_4:
5100 case Builtin::BI__sync_fetch_and_add_8:
5101 case Builtin::BI__sync_fetch_and_add_16:
5102 BuiltinIndex = 0;
5103 break;
5104
5105 case Builtin::BI__sync_fetch_and_sub:
5106 case Builtin::BI__sync_fetch_and_sub_1:
5107 case Builtin::BI__sync_fetch_and_sub_2:
5108 case Builtin::BI__sync_fetch_and_sub_4:
5109 case Builtin::BI__sync_fetch_and_sub_8:
5110 case Builtin::BI__sync_fetch_and_sub_16:
5111 BuiltinIndex = 1;
5112 break;
5113
5114 case Builtin::BI__sync_fetch_and_or:
5115 case Builtin::BI__sync_fetch_and_or_1:
5116 case Builtin::BI__sync_fetch_and_or_2:
5117 case Builtin::BI__sync_fetch_and_or_4:
5118 case Builtin::BI__sync_fetch_and_or_8:
5119 case Builtin::BI__sync_fetch_and_or_16:
5120 BuiltinIndex = 2;
5121 break;
5122
5123 case Builtin::BI__sync_fetch_and_and:
5124 case Builtin::BI__sync_fetch_and_and_1:
5125 case Builtin::BI__sync_fetch_and_and_2:
5126 case Builtin::BI__sync_fetch_and_and_4:
5127 case Builtin::BI__sync_fetch_and_and_8:
5128 case Builtin::BI__sync_fetch_and_and_16:
5129 BuiltinIndex = 3;
5130 break;
5131
5132 case Builtin::BI__sync_fetch_and_xor:
5133 case Builtin::BI__sync_fetch_and_xor_1:
5134 case Builtin::BI__sync_fetch_and_xor_2:
5135 case Builtin::BI__sync_fetch_and_xor_4:
5136 case Builtin::BI__sync_fetch_and_xor_8:
5137 case Builtin::BI__sync_fetch_and_xor_16:
5138 BuiltinIndex = 4;
5139 break;
5140
5141 case Builtin::BI__sync_fetch_and_nand:
5142 case Builtin::BI__sync_fetch_and_nand_1:
5143 case Builtin::BI__sync_fetch_and_nand_2:
5144 case Builtin::BI__sync_fetch_and_nand_4:
5145 case Builtin::BI__sync_fetch_and_nand_8:
5146 case Builtin::BI__sync_fetch_and_nand_16:
5147 BuiltinIndex = 5;
5148 WarnAboutSemanticsChange = true;
5149 break;
5150
5151 case Builtin::BI__sync_add_and_fetch:
5152 case Builtin::BI__sync_add_and_fetch_1:
5153 case Builtin::BI__sync_add_and_fetch_2:
5154 case Builtin::BI__sync_add_and_fetch_4:
5155 case Builtin::BI__sync_add_and_fetch_8:
5156 case Builtin::BI__sync_add_and_fetch_16:
5157 BuiltinIndex = 6;
5158 break;
5159
5160 case Builtin::BI__sync_sub_and_fetch:
5161 case Builtin::BI__sync_sub_and_fetch_1:
5162 case Builtin::BI__sync_sub_and_fetch_2:
5163 case Builtin::BI__sync_sub_and_fetch_4:
5164 case Builtin::BI__sync_sub_and_fetch_8:
5165 case Builtin::BI__sync_sub_and_fetch_16:
5166 BuiltinIndex = 7;
5167 break;
5168
5169 case Builtin::BI__sync_and_and_fetch:
5170 case Builtin::BI__sync_and_and_fetch_1:
5171 case Builtin::BI__sync_and_and_fetch_2:
5172 case Builtin::BI__sync_and_and_fetch_4:
5173 case Builtin::BI__sync_and_and_fetch_8:
5174 case Builtin::BI__sync_and_and_fetch_16:
5175 BuiltinIndex = 8;
5176 break;
5177
5178 case Builtin::BI__sync_or_and_fetch:
5179 case Builtin::BI__sync_or_and_fetch_1:
5180 case Builtin::BI__sync_or_and_fetch_2:
5181 case Builtin::BI__sync_or_and_fetch_4:
5182 case Builtin::BI__sync_or_and_fetch_8:
5183 case Builtin::BI__sync_or_and_fetch_16:
5184 BuiltinIndex = 9;
5185 break;
5186
5187 case Builtin::BI__sync_xor_and_fetch:
5188 case Builtin::BI__sync_xor_and_fetch_1:
5189 case Builtin::BI__sync_xor_and_fetch_2:
5190 case Builtin::BI__sync_xor_and_fetch_4:
5191 case Builtin::BI__sync_xor_and_fetch_8:
5192 case Builtin::BI__sync_xor_and_fetch_16:
5193 BuiltinIndex = 10;
5194 break;
5195
5196 case Builtin::BI__sync_nand_and_fetch:
5197 case Builtin::BI__sync_nand_and_fetch_1:
5198 case Builtin::BI__sync_nand_and_fetch_2:
5199 case Builtin::BI__sync_nand_and_fetch_4:
5200 case Builtin::BI__sync_nand_and_fetch_8:
5201 case Builtin::BI__sync_nand_and_fetch_16:
5202 BuiltinIndex = 11;
5203 WarnAboutSemanticsChange = true;
5204 break;
5205
5206 case Builtin::BI__sync_val_compare_and_swap:
5207 case Builtin::BI__sync_val_compare_and_swap_1:
5208 case Builtin::BI__sync_val_compare_and_swap_2:
5209 case Builtin::BI__sync_val_compare_and_swap_4:
5210 case Builtin::BI__sync_val_compare_and_swap_8:
5211 case Builtin::BI__sync_val_compare_and_swap_16:
5212 BuiltinIndex = 12;
5213 NumFixed = 2;
5214 break;
5215
5216 case Builtin::BI__sync_bool_compare_and_swap:
5217 case Builtin::BI__sync_bool_compare_and_swap_1:
5218 case Builtin::BI__sync_bool_compare_and_swap_2:
5219 case Builtin::BI__sync_bool_compare_and_swap_4:
5220 case Builtin::BI__sync_bool_compare_and_swap_8:
5221 case Builtin::BI__sync_bool_compare_and_swap_16:
5222 BuiltinIndex = 13;
5223 NumFixed = 2;
5224 ResultType = Context.BoolTy;
5225 break;
5226
5227 case Builtin::BI__sync_lock_test_and_set:
5228 case Builtin::BI__sync_lock_test_and_set_1:
5229 case Builtin::BI__sync_lock_test_and_set_2:
5230 case Builtin::BI__sync_lock_test_and_set_4:
5231 case Builtin::BI__sync_lock_test_and_set_8:
5232 case Builtin::BI__sync_lock_test_and_set_16:
5233 BuiltinIndex = 14;
5234 break;
5235
5236 case Builtin::BI__sync_lock_release:
5237 case Builtin::BI__sync_lock_release_1:
5238 case Builtin::BI__sync_lock_release_2:
5239 case Builtin::BI__sync_lock_release_4:
5240 case Builtin::BI__sync_lock_release_8:
5241 case Builtin::BI__sync_lock_release_16:
5242 BuiltinIndex = 15;
5243 NumFixed = 0;
5244 ResultType = Context.VoidTy;
5245 break;
5246
5247 case Builtin::BI__sync_swap:
5248 case Builtin::BI__sync_swap_1:
5249 case Builtin::BI__sync_swap_2:
5250 case Builtin::BI__sync_swap_4:
5251 case Builtin::BI__sync_swap_8:
5252 case Builtin::BI__sync_swap_16:
5253 BuiltinIndex = 16;
5254 break;
5255 }
5256
5257 // Now that we know how many fixed arguments we expect, first check that we
5258 // have at least that many.
5259 if (TheCall->getNumArgs() < 1+NumFixed) {
5260 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5261 << 0 << 1 + NumFixed << TheCall->getNumArgs()
5262 << Callee->getSourceRange();
5263 return ExprError();
5264 }
5265
5266 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5267 << Callee->getSourceRange();
5268
5269 if (WarnAboutSemanticsChange) {
5270 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5271 << Callee->getSourceRange();
5272 }
5273
5274 // Get the decl for the concrete builtin from this, we can tell what the
5275 // concrete integer type we should convert to is.
5276 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5277 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5278 FunctionDecl *NewBuiltinDecl;
5279 if (NewBuiltinID == BuiltinID)
5280 NewBuiltinDecl = FDecl;
5281 else {
5282 // Perform builtin lookup to avoid redeclaring it.
5283 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5284 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5285 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5286 assert(Res.getFoundDecl())((Res.getFoundDecl()) ? static_cast<void> (0) : __assert_fail
("Res.getFoundDecl()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5286, __PRETTY_FUNCTION__))
;
5287 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5288 if (!NewBuiltinDecl)
5289 return ExprError();
5290 }
5291
5292 // The first argument --- the pointer --- has a fixed type; we
5293 // deduce the types of the rest of the arguments accordingly. Walk
5294 // the remaining arguments, converting them to the deduced value type.
5295 for (unsigned i = 0; i != NumFixed; ++i) {
5296 ExprResult Arg = TheCall->getArg(i+1);
5297
5298 // GCC does an implicit conversion to the pointer or integer ValType. This
5299 // can fail in some cases (1i -> int**), check for this error case now.
5300 // Initialize the argument.
5301 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5302 ValType, /*consume*/ false);
5303 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5304 if (Arg.isInvalid())
5305 return ExprError();
5306
5307 // Okay, we have something that *can* be converted to the right type. Check
5308 // to see if there is a potentially weird extension going on here. This can
5309 // happen when you do an atomic operation on something like an char* and
5310 // pass in 42. The 42 gets converted to char. This is even more strange
5311 // for things like 45.123 -> char, etc.
5312 // FIXME: Do this check.
5313 TheCall->setArg(i+1, Arg.get());
5314 }
5315
5316 // Create a new DeclRefExpr to refer to the new decl.
5317 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5318 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5319 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5320 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5321
5322 // Set the callee in the CallExpr.
5323 // FIXME: This loses syntactic information.
5324 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5325 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5326 CK_BuiltinFnToFnPtr);
5327 TheCall->setCallee(PromotedCall.get());
5328
5329 // Change the result type of the call to match the original value type. This
5330 // is arbitrary, but the codegen for these builtins ins design to handle it
5331 // gracefully.
5332 TheCall->setType(ResultType);
5333
5334 return TheCallResult;
5335}
5336
5337/// SemaBuiltinNontemporalOverloaded - We have a call to
5338/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5339/// overloaded function based on the pointer type of its last argument.
5340///
5341/// This function goes through and does final semantic checking for these
5342/// builtins.
5343ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5344 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5345 DeclRefExpr *DRE =
5346 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5347 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5348 unsigned BuiltinID = FDecl->getBuiltinID();
5349 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5351, __PRETTY_FUNCTION__))
5350 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5351, __PRETTY_FUNCTION__))
5351 "Unexpected nontemporal load/store builtin!")(((BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID
== Builtin::BI__builtin_nontemporal_load) && "Unexpected nontemporal load/store builtin!"
) ? static_cast<void> (0) : __assert_fail ("(BuiltinID == Builtin::BI__builtin_nontemporal_store || BuiltinID == Builtin::BI__builtin_nontemporal_load) && \"Unexpected nontemporal load/store builtin!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5351, __PRETTY_FUNCTION__))
;
5352 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5353 unsigned numArgs = isStore ? 2 : 1;
5354
5355 // Ensure that we have the proper number of arguments.
5356 if (checkArgCount(*this, TheCall, numArgs))
5357 return ExprError();
5358
5359 // Inspect the last argument of the nontemporal builtin. This should always
5360 // be a pointer type, from which we imply the type of the memory access.
5361 // Because it is a pointer type, we don't have to worry about any implicit
5362 // casts here.
5363 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5364 ExprResult PointerArgResult =
5365 DefaultFunctionArrayLvalueConversion(PointerArg);
5366
5367 if (PointerArgResult.isInvalid())
5368 return ExprError();
5369 PointerArg = PointerArgResult.get();
5370 TheCall->setArg(numArgs - 1, PointerArg);
5371
5372 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5373 if (!pointerType) {
5374 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5375 << PointerArg->getType() << PointerArg->getSourceRange();
5376 return ExprError();
5377 }
5378
5379 QualType ValType = pointerType->getPointeeType();
5380
5381 // Strip any qualifiers off ValType.
5382 ValType = ValType.getUnqualifiedType();
5383 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5384 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5385 !ValType->isVectorType()) {
5386 Diag(DRE->getBeginLoc(),
5387 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5388 << PointerArg->getType() << PointerArg->getSourceRange();
5389 return ExprError();
5390 }
5391
5392 if (!isStore) {
5393 TheCall->setType(ValType);
5394 return TheCallResult;
5395 }
5396
5397 ExprResult ValArg = TheCall->getArg(0);
5398 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5399 Context, ValType, /*consume*/ false);
5400 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5401 if (ValArg.isInvalid())
5402 return ExprError();
5403
5404 TheCall->setArg(0, ValArg.get());
5405 TheCall->setType(Context.VoidTy);
5406 return TheCallResult;
5407}
5408
5409/// CheckObjCString - Checks that the argument to the builtin
5410/// CFString constructor is correct
5411/// Note: It might also make sense to do the UTF-16 conversion here (would
5412/// simplify the backend).
5413bool Sema::CheckObjCString(Expr *Arg) {
5414 Arg = Arg->IgnoreParenCasts();
5415 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5416
5417 if (!Literal || !Literal->isAscii()) {
5418 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5419 << Arg->getSourceRange();
5420 return true;
5421 }
5422
5423 if (Literal->containsNonAsciiOrNull()) {
5424 StringRef String = Literal->getString();
5425 unsigned NumBytes = String.size();
5426 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5427 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5428 llvm::UTF16 *ToPtr = &ToBuf[0];
5429
5430 llvm::ConversionResult Result =
5431 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5432 ToPtr + NumBytes, llvm::strictConversion);
5433 // Check for conversion failure.
5434 if (Result != llvm::conversionOK)
5435 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5436 << Arg->getSourceRange();
5437 }
5438 return false;
5439}
5440
5441/// CheckObjCString - Checks that the format string argument to the os_log()
5442/// and os_trace() functions is correct, and converts it to const char *.
5443ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5444 Arg = Arg->IgnoreParenCasts();
5445 auto *Literal = dyn_cast<StringLiteral>(Arg);
5446 if (!Literal) {
5447 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5448 Literal = ObjcLiteral->getString();
5449 }
5450 }
5451
5452 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5453 return ExprError(
5454 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5455 << Arg->getSourceRange());
5456 }
5457
5458 ExprResult Result(Literal);
5459 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5460 InitializedEntity Entity =
5461 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5462 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5463 return Result;
5464}
5465
5466/// Check that the user is calling the appropriate va_start builtin for the
5467/// target and calling convention.
5468static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5469 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5470 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5471 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5472 bool IsWindows = TT.isOSWindows();
5473 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5474 if (IsX64 || IsAArch64) {
5475 CallingConv CC = CC_C;
5476 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5477 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5478 if (IsMSVAStart) {
5479 // Don't allow this in System V ABI functions.
5480 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5481 return S.Diag(Fn->getBeginLoc(),
5482 diag::err_ms_va_start_used_in_sysv_function);
5483 } else {
5484 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5485 // On x64 Windows, don't allow this in System V ABI functions.
5486 // (Yes, that means there's no corresponding way to support variadic
5487 // System V ABI functions on Windows.)
5488 if ((IsWindows && CC == CC_X86_64SysV) ||
5489 (!IsWindows && CC == CC_Win64))
5490 return S.Diag(Fn->getBeginLoc(),
5491 diag::err_va_start_used_in_wrong_abi_function)
5492 << !IsWindows;
5493 }
5494 return false;
5495 }
5496
5497 if (IsMSVAStart)
5498 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5499 return false;
5500}
5501
5502static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5503 ParmVarDecl **LastParam = nullptr) {
5504 // Determine whether the current function, block, or obj-c method is variadic
5505 // and get its parameter list.
5506 bool IsVariadic = false;
5507 ArrayRef<ParmVarDecl *> Params;
5508 DeclContext *Caller = S.CurContext;
5509 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5510 IsVariadic = Block->isVariadic();
5511 Params = Block->parameters();
5512 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5513 IsVariadic = FD->isVariadic();
5514 Params = FD->parameters();
5515 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5516 IsVariadic = MD->isVariadic();
5517 // FIXME: This isn't correct for methods (results in bogus warning).
5518 Params = MD->parameters();
5519 } else if (isa<CapturedDecl>(Caller)) {
5520 // We don't support va_start in a CapturedDecl.
5521 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5522 return true;
5523 } else {
5524 // This must be some other declcontext that parses exprs.
5525 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5526 return true;
5527 }
5528
5529 if (!IsVariadic) {
5530 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5531 return true;
5532 }
5533
5534 if (LastParam)
5535 *LastParam = Params.empty() ? nullptr : Params.back();
5536
5537 return false;
5538}
5539
5540/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5541/// for validity. Emit an error and return true on failure; return false
5542/// on success.
5543bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5544 Expr *Fn = TheCall->getCallee();
5545
5546 if (checkVAStartABI(*this, BuiltinID, Fn))
5547 return true;
5548
5549 if (TheCall->getNumArgs() > 2) {
5550 Diag(TheCall->getArg(2)->getBeginLoc(),
5551 diag::err_typecheck_call_too_many_args)
5552 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5553 << Fn->getSourceRange()
5554 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5555 (*(TheCall->arg_end() - 1))->getEndLoc());
5556 return true;
5557 }
5558
5559 if (TheCall->getNumArgs() < 2) {
5560 return Diag(TheCall->getEndLoc(),
5561 diag::err_typecheck_call_too_few_args_at_least)
5562 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5563 }
5564
5565 // Type-check the first argument normally.
5566 if (checkBuiltinArgument(*this, TheCall, 0))
5567 return true;
5568
5569 // Check that the current function is variadic, and get its last parameter.
5570 ParmVarDecl *LastParam;
5571 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5572 return true;
5573
5574 // Verify that the second argument to the builtin is the last argument of the
5575 // current function or method.
5576 bool SecondArgIsLastNamedArgument = false;
5577 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5578
5579 // These are valid if SecondArgIsLastNamedArgument is false after the next
5580 // block.
5581 QualType Type;
5582 SourceLocation ParamLoc;
5583 bool IsCRegister = false;
5584
5585 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5586 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5587 SecondArgIsLastNamedArgument = PV == LastParam;
5588
5589 Type = PV->getType();
5590 ParamLoc = PV->getLocation();
5591 IsCRegister =
5592 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5593 }
5594 }
5595
5596 if (!SecondArgIsLastNamedArgument)
5597 Diag(TheCall->getArg(1)->getBeginLoc(),
5598 diag::warn_second_arg_of_va_start_not_last_named_param);
5599 else if (IsCRegister || Type->isReferenceType() ||
5600 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5601 // Promotable integers are UB, but enumerations need a bit of
5602 // extra checking to see what their promotable type actually is.
5603 if (!Type->isPromotableIntegerType())
1
Assuming the condition is false
2
Taking false branch
5604 return false;
5605 if (!Type->isEnumeralType())
3
Calling 'Type::isEnumeralType'
6
Returning from 'Type::isEnumeralType'
7
Taking false branch
5606 return true;
5607 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
8
Assuming the object is not a 'EnumType'
9
Called C++ object pointer is null
5608 return !(ED &&
5609 Context.typesAreCompatible(ED->getPromotionType(), Type));
5610 }()) {
5611 unsigned Reason = 0;
5612 if (Type->isReferenceType()) Reason = 1;
5613 else if (IsCRegister) Reason = 2;
5614 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5615 Diag(ParamLoc, diag::note_parameter_type) << Type;
5616 }
5617
5618 TheCall->setType(Context.VoidTy);
5619 return false;
5620}
5621
5622bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5623 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5624 // const char *named_addr);
5625
5626 Expr *Func = Call->getCallee();
5627
5628 if (Call->getNumArgs() < 3)
5629 return Diag(Call->getEndLoc(),
5630 diag::err_typecheck_call_too_few_args_at_least)
5631 << 0 /*function call*/ << 3 << Call->getNumArgs();
5632
5633 // Type-check the first argument normally.
5634 if (checkBuiltinArgument(*this, Call, 0))
5635 return true;
5636
5637 // Check that the current function is variadic.
5638 if (checkVAStartIsInVariadicFunction(*this, Func))
5639 return true;
5640
5641 // __va_start on Windows does not validate the parameter qualifiers
5642
5643 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5644 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5645
5646 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5647 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5648
5649 const QualType &ConstCharPtrTy =
5650 Context.getPointerType(Context.CharTy.withConst());
5651 if (!Arg1Ty->isPointerType() ||
5652 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5653 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5654 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5655 << 0 /* qualifier difference */
5656 << 3 /* parameter mismatch */
5657 << 2 << Arg1->getType() << ConstCharPtrTy;
5658
5659 const QualType SizeTy = Context.getSizeType();
5660 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5661 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5662 << Arg2->getType() << SizeTy << 1 /* different class */
5663 << 0 /* qualifier difference */
5664 << 3 /* parameter mismatch */
5665 << 3 << Arg2->getType() << SizeTy;
5666
5667 return false;
5668}
5669
5670/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5671/// friends. This is declared to take (...), so we have to check everything.
5672bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5673 if (TheCall->getNumArgs() < 2)
5674 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5675 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5676 if (TheCall->getNumArgs() > 2)
5677 return Diag(TheCall->getArg(2)->getBeginLoc(),
5678 diag::err_typecheck_call_too_many_args)
5679 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5680 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5681 (*(TheCall->arg_end() - 1))->getEndLoc());
5682
5683 ExprResult OrigArg0 = TheCall->getArg(0);
5684 ExprResult OrigArg1 = TheCall->getArg(1);
5685
5686 // Do standard promotions between the two arguments, returning their common
5687 // type.
5688 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5689 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5690 return true;
5691
5692 // Make sure any conversions are pushed back into the call; this is
5693 // type safe since unordered compare builtins are declared as "_Bool
5694 // foo(...)".
5695 TheCall->setArg(0, OrigArg0.get());
5696 TheCall->setArg(1, OrigArg1.get());
5697
5698 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5699 return false;
5700
5701 // If the common type isn't a real floating type, then the arguments were
5702 // invalid for this operation.
5703 if (Res.isNull() || !Res->isRealFloatingType())
5704 return Diag(OrigArg0.get()->getBeginLoc(),
5705 diag::err_typecheck_call_invalid_ordered_compare)
5706 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5707 << SourceRange(OrigArg0.get()->getBeginLoc(),
5708 OrigArg1.get()->getEndLoc());
5709
5710 return false;
5711}
5712
5713/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5714/// __builtin_isnan and friends. This is declared to take (...), so we have
5715/// to check everything. We expect the last argument to be a floating point
5716/// value.
5717bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5718 if (TheCall->getNumArgs() < NumArgs)
5719 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5720 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5721 if (TheCall->getNumArgs() > NumArgs)
5722 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5723 diag::err_typecheck_call_too_many_args)
5724 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5725 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5726 (*(TheCall->arg_end() - 1))->getEndLoc());
5727
5728 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5729
5730 if (OrigArg->isTypeDependent())
5731 return false;
5732
5733 // This operation requires a non-_Complex floating-point number.
5734 if (!OrigArg->getType()->isRealFloatingType())
5735 return Diag(OrigArg->getBeginLoc(),
5736 diag::err_typecheck_call_invalid_unary_fp)
5737 << OrigArg->getType() << OrigArg->getSourceRange();
5738
5739 // If this is an implicit conversion from float -> float, double, or
5740 // long double, remove it.
5741 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5742 // Only remove standard FloatCasts, leaving other casts inplace
5743 if (Cast->getCastKind() == CK_FloatingCast) {
5744 Expr *CastArg = Cast->getSubExpr();
5745 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5746 assert((((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
5747 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
5748 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
5749 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
5750 "promotion from float to either float, double, or long double is "(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
5751 "the only expected cast here")(((Cast->getType()->isSpecificBuiltinType(BuiltinType::
Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType
::LongDouble)) && "promotion from float to either float, double, or long double is "
"the only expected cast here") ? static_cast<void> (0)
: __assert_fail ("(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && \"promotion from float to either float, double, or long double is \" \"the only expected cast here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 5751, __PRETTY_FUNCTION__))
;
5752 Cast->setSubExpr(nullptr);
5753 TheCall->setArg(NumArgs-1, CastArg);
5754 }
5755 }
5756 }
5757
5758 return false;
5759}
5760
5761// Customized Sema Checking for VSX builtins that have the following signature:
5762// vector [...] builtinName(vector [...], vector [...], const int);
5763// Which takes the same type of vectors (any legal vector type) for the first
5764// two arguments and takes compile time constant for the third argument.
5765// Example builtins are :
5766// vector double vec_xxpermdi(vector double, vector double, int);
5767// vector short vec_xxsldwi(vector short, vector short, int);
5768bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5769 unsigned ExpectedNumArgs = 3;
5770 if (TheCall->getNumArgs() < ExpectedNumArgs)
5771 return Diag(TheCall->getEndLoc(),
5772 diag::err_typecheck_call_too_few_args_at_least)
5773 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5774 << TheCall->getSourceRange();
5775
5776 if (TheCall->getNumArgs() > ExpectedNumArgs)
5777 return Diag(TheCall->getEndLoc(),
5778 diag::err_typecheck_call_too_many_args_at_most)
5779 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5780 << TheCall->getSourceRange();
5781
5782 // Check the third argument is a compile time constant
5783 llvm::APSInt Value;
5784 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5785 return Diag(TheCall->getBeginLoc(),
5786 diag::err_vsx_builtin_nonconstant_argument)
5787 << 3 /* argument index */ << TheCall->getDirectCallee()
5788 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5789 TheCall->getArg(2)->getEndLoc());
5790
5791 QualType Arg1Ty = TheCall->getArg(0)->getType();
5792 QualType Arg2Ty = TheCall->getArg(1)->getType();
5793
5794 // Check the type of argument 1 and argument 2 are vectors.
5795 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5796 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5797 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5798 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5799 << TheCall->getDirectCallee()
5800 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5801 TheCall->getArg(1)->getEndLoc());
5802 }
5803
5804 // Check the first two arguments are the same type.
5805 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5806 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5807 << TheCall->getDirectCallee()
5808 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5809 TheCall->getArg(1)->getEndLoc());
5810 }
5811
5812 // When default clang type checking is turned off and the customized type
5813 // checking is used, the returning type of the function must be explicitly
5814 // set. Otherwise it is _Bool by default.
5815 TheCall->setType(Arg1Ty);
5816
5817 return false;
5818}
5819
5820/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5821// This is declared to take (...), so we have to check everything.
5822ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5823 if (TheCall->getNumArgs() < 2)
5824 return ExprError(Diag(TheCall->getEndLoc(),
5825 diag::err_typecheck_call_too_few_args_at_least)
5826 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5827 << TheCall->getSourceRange());
5828
5829 // Determine which of the following types of shufflevector we're checking:
5830 // 1) unary, vector mask: (lhs, mask)
5831 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5832 QualType resType = TheCall->getArg(0)->getType();
5833 unsigned numElements = 0;
5834
5835 if (!TheCall->getArg(0)->isTypeDependent() &&
5836 !TheCall->getArg(1)->isTypeDependent()) {
5837 QualType LHSType = TheCall->getArg(0)->getType();
5838 QualType RHSType = TheCall->getArg(1)->getType();
5839
5840 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5841 return ExprError(
5842 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5843 << TheCall->getDirectCallee()
5844 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5845 TheCall->getArg(1)->getEndLoc()));
5846
5847 numElements = LHSType->castAs<VectorType>()->getNumElements();
5848 unsigned numResElements = TheCall->getNumArgs() - 2;
5849
5850 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5851 // with mask. If so, verify that RHS is an integer vector type with the
5852 // same number of elts as lhs.
5853 if (TheCall->getNumArgs() == 2) {
5854 if (!RHSType->hasIntegerRepresentation() ||
5855 RHSType->castAs<VectorType>()->getNumElements() != numElements)
5856 return ExprError(Diag(TheCall->getBeginLoc(),
5857 diag::err_vec_builtin_incompatible_vector)
5858 << TheCall->getDirectCallee()
5859 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5860 TheCall->getArg(1)->getEndLoc()));
5861 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5862 return ExprError(Diag(TheCall->getBeginLoc(),
5863 diag::err_vec_builtin_incompatible_vector)
5864 << TheCall->getDirectCallee()
5865 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5866 TheCall->getArg(1)->getEndLoc()));
5867 } else if (numElements != numResElements) {
5868 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5869 resType = Context.getVectorType(eltType, numResElements,
5870 VectorType::GenericVector);
5871 }
5872 }
5873
5874 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5875 if (TheCall->getArg(i)->isTypeDependent() ||
5876 TheCall->getArg(i)->isValueDependent())
5877 continue;
5878
5879 llvm::APSInt Result(32);
5880 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5881 return ExprError(Diag(TheCall->getBeginLoc(),
5882 diag::err_shufflevector_nonconstant_argument)
5883 << TheCall->getArg(i)->getSourceRange());
5884
5885 // Allow -1 which will be translated to undef in the IR.
5886 if (Result.isSigned() && Result.isAllOnesValue())
5887 continue;
5888
5889 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5890 return ExprError(Diag(TheCall->getBeginLoc(),
5891 diag::err_shufflevector_argument_too_large)
5892 << TheCall->getArg(i)->getSourceRange());
5893 }
5894
5895 SmallVector<Expr*, 32> exprs;
5896
5897 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5898 exprs.push_back(TheCall->getArg(i));
5899 TheCall->setArg(i, nullptr);
5900 }
5901
5902 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5903 TheCall->getCallee()->getBeginLoc(),
5904 TheCall->getRParenLoc());
5905}
5906
5907/// SemaConvertVectorExpr - Handle __builtin_convertvector
5908ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5909 SourceLocation BuiltinLoc,
5910 SourceLocation RParenLoc) {
5911 ExprValueKind VK = VK_RValue;
5912 ExprObjectKind OK = OK_Ordinary;
5913 QualType DstTy = TInfo->getType();
5914 QualType SrcTy = E->getType();
5915
5916 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5917 return ExprError(Diag(BuiltinLoc,
5918 diag::err_convertvector_non_vector)
5919 << E->getSourceRange());
5920 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5921 return ExprError(Diag(BuiltinLoc,
5922 diag::err_convertvector_non_vector_type));
5923
5924 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5925 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5926 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5927 if (SrcElts != DstElts)
5928 return ExprError(Diag(BuiltinLoc,
5929 diag::err_convertvector_incompatible_vector)
5930 << E->getSourceRange());
5931 }
5932
5933 return new (Context)
5934 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5935}
5936
5937/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5938// This is declared to take (const void*, ...) and can take two
5939// optional constant int args.
5940bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5941 unsigned NumArgs = TheCall->getNumArgs();
5942
5943 if (NumArgs > 3)
5944 return Diag(TheCall->getEndLoc(),
5945 diag::err_typecheck_call_too_many_args_at_most)
5946 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5947
5948 // Argument 0 is checked for us and the remaining arguments must be
5949 // constant integers.
5950 for (unsigned i = 1; i != NumArgs; ++i)
5951 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5952 return true;
5953
5954 return false;
5955}
5956
5957/// SemaBuiltinAssume - Handle __assume (MS Extension).
5958// __assume does not evaluate its arguments, and should warn if its argument
5959// has side effects.
5960bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5961 Expr *Arg = TheCall->getArg(0);
5962 if (Arg->isInstantiationDependent()) return false;
5963
5964 if (Arg->HasSideEffects(Context))
5965 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5966 << Arg->getSourceRange()
5967 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5968
5969 return false;
5970}
5971
5972/// Handle __builtin_alloca_with_align. This is declared
5973/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5974/// than 8.
5975bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5976 // The alignment must be a constant integer.
5977 Expr *Arg = TheCall->getArg(1);
5978
5979 // We can't check the value of a dependent argument.
5980 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5981 if (const auto *UE =
5982 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5983 if (UE->getKind() == UETT_AlignOf ||
5984 UE->getKind() == UETT_PreferredAlignOf)
5985 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5986 << Arg->getSourceRange();
5987
5988 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5989
5990 if (!Result.isPowerOf2())
5991 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5992 << Arg->getSourceRange();
5993
5994 if (Result < Context.getCharWidth())
5995 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5996 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5997
5998 if (Result > std::numeric_limits<int32_t>::max())
5999 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6000 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6001 }
6002
6003 return false;
6004}
6005
6006/// Handle __builtin_assume_aligned. This is declared
6007/// as (const void*, size_t, ...) and can take one optional constant int arg.
6008bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6009 unsigned NumArgs = TheCall->getNumArgs();
6010
6011 if (NumArgs > 3)
6012 return Diag(TheCall->getEndLoc(),
6013 diag::err_typecheck_call_too_many_args_at_most)
6014 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6015
6016 // The alignment must be a constant integer.
6017 Expr *Arg = TheCall->getArg(1);
6018
6019 // We can't check the value of a dependent argument.
6020 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6021 llvm::APSInt Result;
6022 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6023 return true;
6024
6025 if (!Result.isPowerOf2())
6026 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6027 << Arg->getSourceRange();
6028 }
6029
6030 if (NumArgs > 2) {
6031 ExprResult Arg(TheCall->getArg(2));
6032 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6033 Context.getSizeType(), false);
6034 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6035 if (Arg.isInvalid()) return true;
6036 TheCall->setArg(2, Arg.get());
6037 }
6038
6039 return false;
6040}
6041
6042bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6043 unsigned BuiltinID =
6044 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6045 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6046
6047 unsigned NumArgs = TheCall->getNumArgs();
6048 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6049 if (NumArgs < NumRequiredArgs) {
6050 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6051 << 0 /* function call */ << NumRequiredArgs << NumArgs
6052 << TheCall->getSourceRange();
6053 }
6054 if (NumArgs >= NumRequiredArgs + 0x100) {
6055 return Diag(TheCall->getEndLoc(),
6056 diag::err_typecheck_call_too_many_args_at_most)
6057 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6058 << TheCall->getSourceRange();
6059 }
6060 unsigned i = 0;
6061
6062 // For formatting call, check buffer arg.
6063 if (!IsSizeCall) {
6064 ExprResult Arg(TheCall->getArg(i));
6065 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6066 Context, Context.VoidPtrTy, false);
6067 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6068 if (Arg.isInvalid())
6069 return true;
6070 TheCall->setArg(i, Arg.get());
6071 i++;
6072 }
6073
6074 // Check string literal arg.
6075 unsigned FormatIdx = i;
6076 {
6077 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6078 if (Arg.isInvalid())
6079 return true;
6080 TheCall->setArg(i, Arg.get());
6081 i++;
6082 }
6083
6084 // Make sure variadic args are scalar.
6085 unsigned FirstDataArg = i;
6086 while (i < NumArgs) {
6087 ExprResult Arg = DefaultVariadicArgumentPromotion(
6088 TheCall->getArg(i), VariadicFunction, nullptr);
6089 if (Arg.isInvalid())
6090 return true;
6091 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6092 if (ArgSize.getQuantity() >= 0x100) {
6093 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6094 << i << (int)ArgSize.getQuantity() << 0xff
6095 << TheCall->getSourceRange();
6096 }
6097 TheCall->setArg(i, Arg.get());
6098 i++;
6099 }
6100
6101 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6102 // call to avoid duplicate diagnostics.
6103 if (!IsSizeCall) {
6104 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6105 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6106 bool Success = CheckFormatArguments(
6107 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6108 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6109 CheckedVarArgs);
6110 if (!Success)
6111 return true;
6112 }
6113
6114 if (IsSizeCall) {
6115 TheCall->setType(Context.getSizeType());
6116 } else {
6117 TheCall->setType(Context.VoidPtrTy);
6118 }
6119 return false;
6120}
6121
6122/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6123/// TheCall is a constant expression.
6124bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6125 llvm::APSInt &Result) {
6126 Expr *Arg = TheCall->getArg(ArgNum);
6127 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6128 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6129
6130 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6131
6132 if (!Arg->isIntegerConstantExpr(Result, Context))
6133 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6134 << FDecl->getDeclName() << Arg->getSourceRange();
6135
6136 return false;
6137}
6138
6139/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6140/// TheCall is a constant expression in the range [Low, High].
6141bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6142 int Low, int High, bool RangeIsError) {
6143 if (isConstantEvaluated())
6144 return false;
6145 llvm::APSInt Result;
6146
6147 // We can't check the value of a dependent argument.
6148 Expr *Arg = TheCall->getArg(ArgNum);
6149 if (Arg->isTypeDependent() || Arg->isValueDependent())
6150 return false;
6151
6152 // Check constant-ness first.
6153 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6154 return true;
6155
6156 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6157 if (RangeIsError)
6158 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6159 << Result.toString(10) << Low << High << Arg->getSourceRange();
6160 else
6161 // Defer the warning until we know if the code will be emitted so that
6162 // dead code can ignore this.
6163 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6164 PDiag(diag::warn_argument_invalid_range)
6165 << Result.toString(10) << Low << High
6166 << Arg->getSourceRange());
6167 }
6168
6169 return false;
6170}
6171
6172/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6173/// TheCall is a constant expression is a multiple of Num..
6174bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6175 unsigned Num) {
6176 llvm::APSInt Result;
6177
6178 // We can't check the value of a dependent argument.
6179 Expr *Arg = TheCall->getArg(ArgNum);
6180 if (Arg->isTypeDependent() || Arg->isValueDependent())
6181 return false;
6182
6183 // Check constant-ness first.
6184 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6185 return true;
6186
6187 if (Result.getSExtValue() % Num != 0)
6188 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6189 << Num << Arg->getSourceRange();
6190
6191 return false;
6192}
6193
6194/// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6195bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6196 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6197 if (checkArgCount(*this, TheCall, 2))
6198 return true;
6199 Expr *Arg0 = TheCall->getArg(0);
6200 Expr *Arg1 = TheCall->getArg(1);
6201
6202 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6203 if (FirstArg.isInvalid())
6204 return true;
6205 QualType FirstArgType = FirstArg.get()->getType();
6206 if (!FirstArgType->isAnyPointerType())
6207 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6208 << "first" << FirstArgType << Arg0->getSourceRange();
6209 TheCall->setArg(0, FirstArg.get());
6210
6211 ExprResult SecArg = DefaultLvalueConversion(Arg1);
6212 if (SecArg.isInvalid())
6213 return true;
6214 QualType SecArgType = SecArg.get()->getType();
6215 if (!SecArgType->isIntegerType())
6216 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6217 << "second" << SecArgType << Arg1->getSourceRange();
6218
6219 // Derive the return type from the pointer argument.
6220 TheCall->setType(FirstArgType);
6221 return false;
6222 }
6223
6224 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6225 if (checkArgCount(*this, TheCall, 2))
6226 return true;
6227
6228 Expr *Arg0 = TheCall->getArg(0);
6229 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6230 if (FirstArg.isInvalid())
6231 return true;
6232 QualType FirstArgType = FirstArg.get()->getType();
6233 if (!FirstArgType->isAnyPointerType())
6234 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6235 << "first" << FirstArgType << Arg0->getSourceRange();
6236 TheCall->setArg(0, FirstArg.get());
6237
6238 // Derive the return type from the pointer argument.
6239 TheCall->setType(FirstArgType);
6240
6241 // Second arg must be an constant in range [0,15]
6242 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6243 }
6244
6245 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6246 if (checkArgCount(*this, TheCall, 2))
6247 return true;
6248 Expr *Arg0 = TheCall->getArg(0);
6249 Expr *Arg1 = TheCall->getArg(1);
6250
6251 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6252 if (FirstArg.isInvalid())
6253 return true;
6254 QualType FirstArgType = FirstArg.get()->getType();
6255 if (!FirstArgType->isAnyPointerType())
6256 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6257 << "first" << FirstArgType << Arg0->getSourceRange();
6258
6259 QualType SecArgType = Arg1->getType();
6260 if (!SecArgType->isIntegerType())
6261 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6262 << "second" << SecArgType << Arg1->getSourceRange();
6263 TheCall->setType(Context.IntTy);
6264 return false;
6265 }
6266
6267 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6268 BuiltinID == AArch64::BI__builtin_arm_stg) {
6269 if (checkArgCount(*this, TheCall, 1))
6270 return true;
6271 Expr *Arg0 = TheCall->getArg(0);
6272 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6273 if (FirstArg.isInvalid())
6274 return true;
6275
6276 QualType FirstArgType = FirstArg.get()->getType();
6277 if (!FirstArgType->isAnyPointerType())
6278 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6279 << "first" << FirstArgType << Arg0->getSourceRange();
6280 TheCall->setArg(0, FirstArg.get());
6281
6282 // Derive the return type from the pointer argument.
6283 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6284 TheCall->setType(FirstArgType);
6285 return false;
6286 }
6287
6288 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6289 Expr *ArgA = TheCall->getArg(0);
6290 Expr *ArgB = TheCall->getArg(1);
6291
6292 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6293 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6294
6295 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6296 return true;
6297
6298 QualType ArgTypeA = ArgExprA.get()->getType();
6299 QualType ArgTypeB = ArgExprB.get()->getType();
6300
6301 auto isNull = [&] (Expr *E) -> bool {
6302 return E->isNullPointerConstant(
6303 Context, Expr::NPC_ValueDependentIsNotNull); };
6304
6305 // argument should be either a pointer or null
6306 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6307 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6308 << "first" << ArgTypeA << ArgA->getSourceRange();
6309
6310 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6311 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6312 << "second" << ArgTypeB << ArgB->getSourceRange();
6313
6314 // Ensure Pointee types are compatible
6315 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6316 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6317 QualType pointeeA = ArgTypeA->getPointeeType();
6318 QualType pointeeB = ArgTypeB->getPointeeType();
6319 if (!Context.typesAreCompatible(
6320 Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6321 Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6322 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6323 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6324 << ArgB->getSourceRange();
6325 }
6326 }
6327
6328 // at least one argument should be pointer type
6329 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6330 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6331 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6332
6333 if (isNull(ArgA)) // adopt type of the other pointer
6334 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6335
6336 if (isNull(ArgB))
6337 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6338
6339 TheCall->setArg(0, ArgExprA.get());
6340 TheCall->setArg(1, ArgExprB.get());
6341 TheCall->setType(Context.LongLongTy);
6342 return false;
6343 }
6344 assert(false && "Unhandled ARM MTE intrinsic")((false && "Unhandled ARM MTE intrinsic") ? static_cast
<void> (0) : __assert_fail ("false && \"Unhandled ARM MTE intrinsic\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6344, __PRETTY_FUNCTION__))
;
6345 return true;
6346}
6347
6348/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6349/// TheCall is an ARM/AArch64 special register string literal.
6350bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6351 int ArgNum, unsigned ExpectedFieldNum,
6352 bool AllowName) {
6353 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6354 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6355 BuiltinID == ARM::BI__builtin_arm_rsr ||
6356 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6357 BuiltinID == ARM::BI__builtin_arm_wsr ||
6358 BuiltinID == ARM::BI__builtin_arm_wsrp;
6359 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6360 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6361 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6362 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6363 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6364 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6365 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.")(((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."
) ? static_cast<void> (0) : __assert_fail ("(IsARMBuiltin || IsAArch64Builtin) && \"Unexpected ARM builtin.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6365, __PRETTY_FUNCTION__))
;
6366
6367 // We can't check the value of a dependent argument.
6368 Expr *Arg = TheCall->getArg(ArgNum);
6369 if (Arg->isTypeDependent() || Arg->isValueDependent())
6370 return false;
6371
6372 // Check if the argument is a string literal.
6373 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6374 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6375 << Arg->getSourceRange();
6376
6377 // Check the type of special register given.
6378 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6379 SmallVector<StringRef, 6> Fields;
6380 Reg.split(Fields, ":");
6381
6382 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6383 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6384 << Arg->getSourceRange();
6385
6386 // If the string is the name of a register then we cannot check that it is
6387 // valid here but if the string is of one the forms described in ACLE then we
6388 // can check that the supplied fields are integers and within the valid
6389 // ranges.
6390 if (Fields.size() > 1) {
6391 bool FiveFields = Fields.size() == 5;
6392
6393 bool ValidString = true;
6394 if (IsARMBuiltin) {
6395 ValidString &= Fields[0].startswith_lower("cp") ||
6396 Fields[0].startswith_lower("p");
6397 if (ValidString)
6398 Fields[0] =
6399 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6400
6401 ValidString &= Fields[2].startswith_lower("c");
6402 if (ValidString)
6403 Fields[2] = Fields[2].drop_front(1);
6404
6405 if (FiveFields) {
6406 ValidString &= Fields[3].startswith_lower("c");
6407 if (ValidString)
6408 Fields[3] = Fields[3].drop_front(1);
6409 }
6410 }
6411
6412 SmallVector<int, 5> Ranges;
6413 if (FiveFields)
6414 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6415 else
6416 Ranges.append({15, 7, 15});
6417
6418 for (unsigned i=0; i<Fields.size(); ++i) {
6419 int IntField;
6420 ValidString &= !Fields[i].getAsInteger(10, IntField);
6421 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6422 }
6423
6424 if (!ValidString)
6425 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6426 << Arg->getSourceRange();
6427 } else if (IsAArch64Builtin && Fields.size() == 1) {
6428 // If the register name is one of those that appear in the condition below
6429 // and the special register builtin being used is one of the write builtins,
6430 // then we require that the argument provided for writing to the register
6431 // is an integer constant expression. This is because it will be lowered to
6432 // an MSR (immediate) instruction, so we need to know the immediate at
6433 // compile time.
6434 if (TheCall->getNumArgs() != 2)
6435 return false;
6436
6437 std::string RegLower = Reg.lower();
6438 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6439 RegLower != "pan" && RegLower != "uao")
6440 return false;
6441
6442 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6443 }
6444
6445 return false;
6446}
6447
6448/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6449/// This checks that the target supports __builtin_longjmp and
6450/// that val is a constant 1.
6451bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6452 if (!Context.getTargetInfo().hasSjLjLowering())
6453 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6454 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6455
6456 Expr *Arg = TheCall->getArg(1);
6457 llvm::APSInt Result;
6458
6459 // TODO: This is less than ideal. Overload this to take a value.
6460 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6461 return true;
6462
6463 if (Result != 1)
6464 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6465 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6466
6467 return false;
6468}
6469
6470/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6471/// This checks that the target supports __builtin_setjmp.
6472bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6473 if (!Context.getTargetInfo().hasSjLjLowering())
6474 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6475 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6476 return false;
6477}
6478
6479namespace {
6480
6481class UncoveredArgHandler {
6482 enum { Unknown = -1, AllCovered = -2 };
6483
6484 signed FirstUncoveredArg = Unknown;
6485 SmallVector<const Expr *, 4> DiagnosticExprs;
6486
6487public:
6488 UncoveredArgHandler() = default;
6489
6490 bool hasUncoveredArg() const {
6491 return (FirstUncoveredArg >= 0);
6492 }
6493
6494 unsigned getUncoveredArg() const {
6495 assert(hasUncoveredArg() && "no uncovered argument")((hasUncoveredArg() && "no uncovered argument") ? static_cast
<void> (0) : __assert_fail ("hasUncoveredArg() && \"no uncovered argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6495, __PRETTY_FUNCTION__))
;
6496 return FirstUncoveredArg;
6497 }
6498
6499 void setAllCovered() {
6500 // A string has been found with all arguments covered, so clear out
6501 // the diagnostics.
6502 DiagnosticExprs.clear();
6503 FirstUncoveredArg = AllCovered;
6504 }
6505
6506 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6507 assert(NewFirstUncoveredArg >= 0 && "Outside range")((NewFirstUncoveredArg >= 0 && "Outside range") ? static_cast
<void> (0) : __assert_fail ("NewFirstUncoveredArg >= 0 && \"Outside range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6507, __PRETTY_FUNCTION__))
;
6508
6509 // Don't update if a previous string covers all arguments.
6510 if (FirstUncoveredArg == AllCovered)
6511 return;
6512
6513 // UncoveredArgHandler tracks the highest uncovered argument index
6514 // and with it all the strings that match this index.
6515 if (NewFirstUncoveredArg == FirstUncoveredArg)
6516 DiagnosticExprs.push_back(StrExpr);
6517 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6518 DiagnosticExprs.clear();
6519 DiagnosticExprs.push_back(StrExpr);
6520 FirstUncoveredArg = NewFirstUncoveredArg;
6521 }
6522 }
6523
6524 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6525};
6526
6527enum StringLiteralCheckType {
6528 SLCT_NotALiteral,
6529 SLCT_UncheckedLiteral,
6530 SLCT_CheckedLiteral
6531};
6532
6533} // namespace
6534
6535static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6536 BinaryOperatorKind BinOpKind,
6537 bool AddendIsRight) {
6538 unsigned BitWidth = Offset.getBitWidth();
6539 unsigned AddendBitWidth = Addend.getBitWidth();
6540 // There might be negative interim results.
6541 if (Addend.isUnsigned()) {
6542 Addend = Addend.zext(++AddendBitWidth);
6543 Addend.setIsSigned(true);
6544 }
6545 // Adjust the bit width of the APSInts.
6546 if (AddendBitWidth > BitWidth) {
6547 Offset = Offset.sext(AddendBitWidth);
6548 BitWidth = AddendBitWidth;
6549 } else if (BitWidth > AddendBitWidth) {
6550 Addend = Addend.sext(BitWidth);
6551 }
6552
6553 bool Ov = false;
6554 llvm::APSInt ResOffset = Offset;
6555 if (BinOpKind == BO_Add)
6556 ResOffset = Offset.sadd_ov(Addend, Ov);
6557 else {
6558 assert(AddendIsRight && BinOpKind == BO_Sub &&((AddendIsRight && BinOpKind == BO_Sub && "operator must be add or sub with addend on the right"
) ? static_cast<void> (0) : __assert_fail ("AddendIsRight && BinOpKind == BO_Sub && \"operator must be add or sub with addend on the right\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6559, __PRETTY_FUNCTION__))
6559 "operator must be add or sub with addend on the right")((AddendIsRight && BinOpKind == BO_Sub && "operator must be add or sub with addend on the right"
) ? static_cast<void> (0) : __assert_fail ("AddendIsRight && BinOpKind == BO_Sub && \"operator must be add or sub with addend on the right\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6559, __PRETTY_FUNCTION__))
;
6560 ResOffset = Offset.ssub_ov(Addend, Ov);
6561 }
6562
6563 // We add an offset to a pointer here so we should support an offset as big as
6564 // possible.
6565 if (Ov) {
6566 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&((BitWidth <= std::numeric_limits<unsigned>::max() /
2 && "index (intermediate) result too big") ? static_cast
<void> (0) : __assert_fail ("BitWidth <= std::numeric_limits<unsigned>::max() / 2 && \"index (intermediate) result too big\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6567, __PRETTY_FUNCTION__))
6567 "index (intermediate) result too big")((BitWidth <= std::numeric_limits<unsigned>::max() /
2 && "index (intermediate) result too big") ? static_cast
<void> (0) : __assert_fail ("BitWidth <= std::numeric_limits<unsigned>::max() / 2 && \"index (intermediate) result too big\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6567, __PRETTY_FUNCTION__))
;
6568 Offset = Offset.sext(2 * BitWidth);
6569 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6570 return;
6571 }
6572
6573 Offset = ResOffset;
6574}
6575
6576namespace {
6577
6578// This is a wrapper class around StringLiteral to support offsetted string
6579// literals as format strings. It takes the offset into account when returning
6580// the string and its length or the source locations to display notes correctly.
6581class FormatStringLiteral {
6582 const StringLiteral *FExpr;
6583 int64_t Offset;
6584
6585 public:
6586 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6587 : FExpr(fexpr), Offset(Offset) {}
6588
6589 StringRef getString() const {
6590 return FExpr->getString().drop_front(Offset);
6591 }
6592
6593 unsigned getByteLength() const {
6594 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6595 }
6596
6597 unsigned getLength() const { return FExpr->getLength() - Offset; }
6598 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6599
6600 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6601
6602 QualType getType() const { return FExpr->getType(); }
6603
6604 bool isAscii() const { return FExpr->isAscii(); }
6605 bool isWide() const { return FExpr->isWide(); }
6606 bool isUTF8() const { return FExpr->isUTF8(); }
6607 bool isUTF16() const { return FExpr->isUTF16(); }
6608 bool isUTF32() const { return FExpr->isUTF32(); }
6609 bool isPascal() const { return FExpr->isPascal(); }
6610
6611 SourceLocation getLocationOfByte(
6612 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6613 const TargetInfo &Target, unsigned *StartToken = nullptr,
6614 unsigned *StartTokenByteOffset = nullptr) const {
6615 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6616 StartToken, StartTokenByteOffset);
6617 }
6618
6619 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
6620 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6621 }
6622
6623 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return FExpr->getEndLoc(); }
6624};
6625
6626} // namespace
6627
6628static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6629 const Expr *OrigFormatExpr,
6630 ArrayRef<const Expr *> Args,
6631 bool HasVAListArg, unsigned format_idx,
6632 unsigned firstDataArg,
6633 Sema::FormatStringType Type,
6634 bool inFunctionCall,
6635 Sema::VariadicCallType CallType,
6636 llvm::SmallBitVector &CheckedVarArgs,
6637 UncoveredArgHandler &UncoveredArg,
6638 bool IgnoreStringsWithoutSpecifiers);
6639
6640// Determine if an expression is a string literal or constant string.
6641// If this function returns false on the arguments to a function expecting a
6642// format string, we will usually need to emit a warning.
6643// True string literals are then checked by CheckFormatString.
6644static StringLiteralCheckType
6645checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6646 bool HasVAListArg, unsigned format_idx,
6647 unsigned firstDataArg, Sema::FormatStringType Type,
6648 Sema::VariadicCallType CallType, bool InFunctionCall,
6649 llvm::SmallBitVector &CheckedVarArgs,
6650 UncoveredArgHandler &UncoveredArg,
6651 llvm::APSInt Offset,
6652 bool IgnoreStringsWithoutSpecifiers = false) {
6653 if (S.isConstantEvaluated())
6654 return SLCT_NotALiteral;
6655 tryAgain:
6656 assert(Offset.isSigned() && "invalid offset")((Offset.isSigned() && "invalid offset") ? static_cast
<void> (0) : __assert_fail ("Offset.isSigned() && \"invalid offset\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 6656, __PRETTY_FUNCTION__))
;
6657
6658 if (E->isTypeDependent() || E->isValueDependent())
6659 return SLCT_NotALiteral;
6660
6661 E = E->IgnoreParenCasts();
6662
6663 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6664 // Technically -Wformat-nonliteral does not warn about this case.
6665 // The behavior of printf and friends in this case is implementation
6666 // dependent. Ideally if the format string cannot be null then
6667 // it should have a 'nonnull' attribute in the function prototype.
6668 return SLCT_UncheckedLiteral;
6669
6670 switch (E->getStmtClass()) {
6671 case Stmt::BinaryConditionalOperatorClass:
6672 case Stmt::ConditionalOperatorClass: {
6673 // The expression is a literal if both sub-expressions were, and it was
6674 // completely checked only if both sub-expressions were checked.
6675 const AbstractConditionalOperator *C =
6676 cast<AbstractConditionalOperator>(E);
6677
6678 // Determine whether it is necessary to check both sub-expressions, for
6679 // example, because the condition expression is a constant that can be
6680 // evaluated at compile time.
6681 bool CheckLeft = true, CheckRight = true;
6682
6683 bool Cond;
6684 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6685 S.isConstantEvaluated())) {
6686 if (Cond)
6687 CheckRight = false;
6688 else
6689 CheckLeft = false;
6690 }
6691
6692 // We need to maintain the offsets for the right and the left hand side
6693 // separately to check if every possible indexed expression is a valid
6694 // string literal. They might have different offsets for different string
6695 // literals in the end.
6696 StringLiteralCheckType Left;
6697 if (!CheckLeft)
6698 Left = SLCT_UncheckedLiteral;
6699 else {
6700 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6701 HasVAListArg, format_idx, firstDataArg,
6702 Type, CallType, InFunctionCall,
6703 CheckedVarArgs, UncoveredArg, Offset,
6704 IgnoreStringsWithoutSpecifiers);
6705 if (Left == SLCT_NotALiteral || !CheckRight) {
6706 return Left;
6707 }
6708 }
6709
6710 StringLiteralCheckType Right = checkFormatStringExpr(
6711 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6712 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6713 IgnoreStringsWithoutSpecifiers);
6714
6715 return (CheckLeft && Left < Right) ? Left : Right;
6716 }
6717
6718 case Stmt::ImplicitCastExprClass:
6719 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6720 goto tryAgain;
6721
6722 case Stmt::OpaqueValueExprClass:
6723 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6724 E = src;
6725 goto tryAgain;
6726 }
6727 return SLCT_NotALiteral;
6728
6729 case Stmt::PredefinedExprClass:
6730 // While __func__, etc., are technically not string literals, they
6731 // cannot contain format specifiers and thus are not a security
6732 // liability.
6733 return SLCT_UncheckedLiteral;
6734
6735 case Stmt::DeclRefExprClass: {
6736 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6737
6738 // As an exception, do not flag errors for variables binding to
6739 // const string literals.
6740 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6741 bool isConstant = false;
6742 QualType T = DR->getType();
6743
6744 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6745 isConstant = AT->getElementType().isConstant(S.Context);
6746 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6747 isConstant = T.isConstant(S.Context) &&
6748 PT->getPointeeType().isConstant(S.Context);
6749 } else if (T->isObjCObjectPointerType()) {
6750 // In ObjC, there is usually no "const ObjectPointer" type,
6751 // so don't check if the pointee type is constant.
6752 isConstant = T.isConstant(S.Context);
6753 }
6754
6755 if (isConstant) {
6756 if (const Expr *Init = VD->getAnyInitializer()) {
6757 // Look through initializers like const char c[] = { "foo" }
6758 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6759 if (InitList->isStringLiteralInit())
6760 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6761 }
6762 return checkFormatStringExpr(S, Init, Args,
6763 HasVAListArg, format_idx,
6764 firstDataArg, Type, CallType,
6765 /*InFunctionCall*/ false, CheckedVarArgs,
6766 UncoveredArg, Offset);
6767 }
6768 }
6769
6770 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6771 // special check to see if the format string is a function parameter
6772 // of the function calling the printf function. If the function
6773 // has an attribute indicating it is a printf-like function, then we
6774 // should suppress warnings concerning non-literals being used in a call
6775 // to a vprintf function. For example:
6776 //
6777 // void
6778 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6779 // va_list ap;
6780 // va_start(ap, fmt);
6781 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6782 // ...
6783 // }
6784 if (HasVAListArg) {
6785 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6786 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6787 int PVIndex = PV->getFunctionScopeIndex() + 1;
6788 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6789 // adjust for implicit parameter
6790 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6791 if (MD->isInstance())
6792 ++PVIndex;
6793 // We also check if the formats are compatible.
6794 // We can't pass a 'scanf' string to a 'printf' function.
6795 if (PVIndex == PVFormat->getFormatIdx() &&
6796 Type == S.GetFormatStringType(PVFormat))
6797 return SLCT_UncheckedLiteral;
6798 }
6799 }
6800 }
6801 }
6802 }
6803
6804 return SLCT_NotALiteral;
6805 }
6806
6807 case Stmt::CallExprClass:
6808 case Stmt::CXXMemberCallExprClass: {
6809 const CallExpr *CE = cast<CallExpr>(E);
6810 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6811 bool IsFirst = true;
6812 StringLiteralCheckType CommonResult;
6813 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6814 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6815 StringLiteralCheckType Result = checkFormatStringExpr(
6816 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6817 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6818 IgnoreStringsWithoutSpecifiers);
6819 if (IsFirst) {
6820 CommonResult = Result;
6821 IsFirst = false;
6822 }
6823 }
6824 if (!IsFirst)
6825 return CommonResult;
6826
6827 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6828 unsigned BuiltinID = FD->getBuiltinID();
6829 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6830 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6831 const Expr *Arg = CE->getArg(0);
6832 return checkFormatStringExpr(S, Arg, Args,
6833 HasVAListArg, format_idx,
6834 firstDataArg, Type, CallType,
6835 InFunctionCall, CheckedVarArgs,
6836 UncoveredArg, Offset,
6837 IgnoreStringsWithoutSpecifiers);
6838 }
6839 }
6840 }
6841
6842 return SLCT_NotALiteral;
6843 }
6844 case Stmt::ObjCMessageExprClass: {
6845 const auto *ME = cast<ObjCMessageExpr>(E);
6846 if (const auto *MD = ME->getMethodDecl()) {
6847 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6848 // As a special case heuristic, if we're using the method -[NSBundle
6849 // localizedStringForKey:value:table:], ignore any key strings that lack
6850 // format specifiers. The idea is that if the key doesn't have any
6851 // format specifiers then its probably just a key to map to the
6852 // localized strings. If it does have format specifiers though, then its
6853 // likely that the text of the key is the format string in the
6854 // programmer's language, and should be checked.
6855 const ObjCInterfaceDecl *IFace;
6856 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6857 IFace->getIdentifier()->isStr("NSBundle") &&
6858 MD->getSelector().isKeywordSelector(
6859 {"localizedStringForKey", "value", "table"})) {
6860 IgnoreStringsWithoutSpecifiers = true;
6861 }
6862
6863 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6864 return checkFormatStringExpr(
6865 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6866 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6867 IgnoreStringsWithoutSpecifiers);
6868 }
6869 }
6870
6871 return SLCT_NotALiteral;
6872 }
6873 case Stmt::ObjCStringLiteralClass:
6874 case Stmt::StringLiteralClass: {
6875 const StringLiteral *StrE = nullptr;
6876
6877 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6878 StrE = ObjCFExpr->getString();
6879 else
6880 StrE = cast<StringLiteral>(E);
6881
6882 if (StrE) {
6883 if (Offset.isNegative() || Offset > StrE->getLength()) {
6884 // TODO: It would be better to have an explicit warning for out of
6885 // bounds literals.
6886 return SLCT_NotALiteral;
6887 }
6888 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6889 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6890 firstDataArg, Type, InFunctionCall, CallType,
6891 CheckedVarArgs, UncoveredArg,
6892 IgnoreStringsWithoutSpecifiers);
6893 return SLCT_CheckedLiteral;
6894 }
6895
6896 return SLCT_NotALiteral;
6897 }
6898 case Stmt::BinaryOperatorClass: {
6899 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6900
6901 // A string literal + an int offset is still a string literal.
6902 if (BinOp->isAdditiveOp()) {
6903 Expr::EvalResult LResult, RResult;
6904
6905 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6906 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6907 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6908 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6909
6910 if (LIsInt != RIsInt) {
6911 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6912
6913 if (LIsInt) {
6914 if (BinOpKind == BO_Add) {
6915 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6916 E = BinOp->getRHS();
6917 goto tryAgain;
6918 }
6919 } else {
6920 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6921 E = BinOp->getLHS();
6922 goto tryAgain;
6923 }
6924 }
6925 }
6926
6927 return SLCT_NotALiteral;
6928 }
6929 case Stmt::UnaryOperatorClass: {
6930 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6931 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6932 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6933 Expr::EvalResult IndexResult;
6934 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6935 Expr::SE_NoSideEffects,
6936 S.isConstantEvaluated())) {
6937 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6938 /*RHS is int*/ true);
6939 E = ASE->getBase();
6940 goto tryAgain;
6941 }
6942 }
6943
6944 return SLCT_NotALiteral;
6945 }
6946
6947 default:
6948 return SLCT_NotALiteral;
6949 }
6950}
6951
6952Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6953 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6954 .Case("scanf", FST_Scanf)
6955 .Cases("printf", "printf0", FST_Printf)
6956 .Cases("NSString", "CFString", FST_NSString)
6957 .Case("strftime", FST_Strftime)
6958 .Case("strfmon", FST_Strfmon)
6959 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6960 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6961 .Case("os_trace", FST_OSLog)
6962 .Case("os_log", FST_OSLog)
6963 .Default(FST_Unknown);
6964}
6965
6966/// CheckFormatArguments - Check calls to printf and scanf (and similar
6967/// functions) for correct use of format strings.
6968/// Returns true if a format string has been fully checked.
6969bool Sema::CheckFormatArguments(const FormatAttr *Format,
6970 ArrayRef<const Expr *> Args,
6971 bool IsCXXMember,
6972 VariadicCallType CallType,
6973 SourceLocation Loc, SourceRange Range,
6974 llvm::SmallBitVector &CheckedVarArgs) {
6975 FormatStringInfo FSI;
6976 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6977 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6978 FSI.FirstDataArg, GetFormatStringType(Format),
6979 CallType, Loc, Range, CheckedVarArgs);
6980 return false;
6981}
6982
6983bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6984 bool HasVAListArg, unsigned format_idx,
6985 unsigned firstDataArg, FormatStringType Type,
6986 VariadicCallType CallType,
6987 SourceLocation Loc, SourceRange Range,
6988 llvm::SmallBitVector &CheckedVarArgs) {
6989 // CHECK: printf/scanf-like function is called with no format string.
6990 if (format_idx >= Args.size()) {
6991 Diag(Loc, diag::warn_missing_format_string) << Range;
6992 return false;
6993 }
6994
6995 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6996
6997 // CHECK: format string is not a string literal.
6998 //
6999 // Dynamically generated format strings are difficult to
7000 // automatically vet at compile time. Requiring that format strings
7001 // are string literals: (1) permits the checking of format strings by
7002 // the compiler and thereby (2) can practically remove the source of
7003 // many format string exploits.
7004
7005 // Format string can be either ObjC string (e.g. @"%d") or
7006 // C string (e.g. "%d")
7007 // ObjC string uses the same format specifiers as C string, so we can use
7008 // the same format string checking logic for both ObjC and C strings.
7009 UncoveredArgHandler UncoveredArg;
7010 StringLiteralCheckType CT =
7011 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7012 format_idx, firstDataArg, Type, CallType,
7013 /*IsFunctionCall*/ true, CheckedVarArgs,
7014 UncoveredArg,
7015 /*no string offset*/ llvm::APSInt(64, false) = 0);
7016
7017 // Generate a diagnostic where an uncovered argument is detected.
7018 if (UncoveredArg.hasUncoveredArg()) {
7019 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7020 assert(ArgIdx < Args.size() && "ArgIdx outside bounds")((ArgIdx < Args.size() && "ArgIdx outside bounds")
? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"ArgIdx outside bounds\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 7020, __PRETTY_FUNCTION__))
;
7021 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7022 }
7023
7024 if (CT != SLCT_NotALiteral)
7025 // Literal format string found, check done!
7026 return CT == SLCT_CheckedLiteral;
7027
7028 // Strftime is particular as it always uses a single 'time' argument,
7029 // so it is safe to pass a non-literal string.
7030 if (Type == FST_Strftime)
7031 return false;
7032
7033 // Do not emit diag when the string param is a macro expansion and the
7034 // format is either NSString or CFString. This is a hack to prevent
7035 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7036 // which are usually used in place of NS and CF string literals.
7037 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7038 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7039 return false;
7040
7041 // If there are no arguments specified, warn with -Wformat-security, otherwise
7042 // warn only with -Wformat-nonliteral.
7043 if (Args.size() == firstDataArg) {
7044 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7045 << OrigFormatExpr->getSourceRange();
7046 switch (Type) {
7047 default:
7048 break;
7049 case FST_Kprintf:
7050 case FST_FreeBSDKPrintf:
7051 case FST_Printf:
7052 Diag(FormatLoc, diag::note_format_security_fixit)
7053 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7054 break;
7055 case FST_NSString:
7056 Diag(FormatLoc, diag::note_format_security_fixit)
7057 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7058 break;
7059 }
7060 } else {
7061 Diag(FormatLoc, diag::warn_format_nonliteral)
7062 << OrigFormatExpr->getSourceRange();
7063 }
7064 return false;
7065}
7066
7067namespace {
7068
7069class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7070protected:
7071 Sema &S;
7072 const FormatStringLiteral *FExpr;
7073 const Expr *OrigFormatExpr;
7074 const Sema::FormatStringType FSType;
7075 const unsigned FirstDataArg;
7076 const unsigned NumDataArgs;
7077 const char *Beg; // Start of format string.
7078 const bool HasVAListArg;
7079 ArrayRef<const Expr *> Args;
7080 unsigned FormatIdx;
7081 llvm::SmallBitVector CoveredArgs;
7082 bool usesPositionalArgs = false;
7083 bool atFirstArg = true;
7084 bool inFunctionCall;
7085 Sema::VariadicCallType CallType;
7086 llvm::SmallBitVector &CheckedVarArgs;
7087 UncoveredArgHandler &UncoveredArg;
7088
7089public:
7090 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7091 const Expr *origFormatExpr,
7092 const Sema::FormatStringType type, unsigned firstDataArg,
7093 unsigned numDataArgs, const char *beg, bool hasVAListArg,
7094 ArrayRef<const Expr *> Args, unsigned formatIdx,
7095 bool inFunctionCall, Sema::VariadicCallType callType,
7096 llvm::SmallBitVector &CheckedVarArgs,
7097 UncoveredArgHandler &UncoveredArg)
7098 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7099 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7100 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7101 inFunctionCall(inFunctionCall), CallType(callType),
7102 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7103 CoveredArgs.resize(numDataArgs);
7104 CoveredArgs.reset();
7105 }
7106
7107 void DoneProcessing();
7108
7109 void HandleIncompleteSpecifier(const char *startSpecifier,
7110 unsigned specifierLen) override;
7111
7112 void HandleInvalidLengthModifier(
7113 const analyze_format_string::FormatSpecifier &FS,
7114 const analyze_format_string::ConversionSpecifier &CS,
7115 const char *startSpecifier, unsigned specifierLen,
7116 unsigned DiagID);
7117
7118 void HandleNonStandardLengthModifier(
7119 const analyze_format_string::FormatSpecifier &FS,
7120 const char *startSpecifier, unsigned specifierLen);
7121
7122 void HandleNonStandardConversionSpecifier(
7123 const analyze_format_string::ConversionSpecifier &CS,
7124 const char *startSpecifier, unsigned specifierLen);
7125
7126 void HandlePosition(const char *startPos, unsigned posLen) override;
7127
7128 void HandleInvalidPosition(const char *startSpecifier,
7129 unsigned specifierLen,
7130 analyze_format_string::PositionContext p) override;
7131
7132 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7133
7134 void HandleNullChar(const char *nullCharacter) override;
7135
7136 template <typename Range>
7137 static void
7138 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7139 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7140 bool IsStringLocation, Range StringRange,
7141 ArrayRef<FixItHint> Fixit = None);
7142
7143protected:
7144 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7145 const char *startSpec,
7146 unsigned specifierLen,
7147 const char *csStart, unsigned csLen);
7148
7149 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7150 const char *startSpec,
7151 unsigned specifierLen);
7152
7153 SourceRange getFormatStringRange();
7154 CharSourceRange getSpecifierRange(const char *startSpecifier,
7155 unsigned specifierLen);
7156 SourceLocation getLocationOfByte(const char *x);
7157
7158 const Expr *getDataArg(unsigned i) const;
7159
7160 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7161 const analyze_format_string::ConversionSpecifier &CS,
7162 const char *startSpecifier, unsigned specifierLen,
7163 unsigned argIndex);
7164
7165 template <typename Range>
7166 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7167 bool IsStringLocation, Range StringRange,
7168 ArrayRef<FixItHint> Fixit = None);
7169};
7170
7171} // namespace
7172
7173SourceRange CheckFormatHandler::getFormatStringRange() {
7174 return OrigFormatExpr->getSourceRange();
7175}
7176
7177CharSourceRange CheckFormatHandler::
7178getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7179 SourceLocation Start = getLocationOfByte(startSpecifier);
7180 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7181
7182 // Advance the end SourceLocation by one due to half-open ranges.
7183 End = End.getLocWithOffset(1);
7184
7185 return CharSourceRange::getCharRange(Start, End);
7186}
7187
7188SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7189 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7190 S.getLangOpts(), S.Context.getTargetInfo());
7191}
7192
7193void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7194 unsigned specifierLen){
7195 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7196 getLocationOfByte(startSpecifier),
7197 /*IsStringLocation*/true,
7198 getSpecifierRange(startSpecifier, specifierLen));
7199}
7200
7201void CheckFormatHandler::HandleInvalidLengthModifier(
7202 const analyze_format_string::FormatSpecifier &FS,
7203 const analyze_format_string::ConversionSpecifier &CS,
7204 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7205 using namespace analyze_format_string;
7206
7207 const LengthModifier &LM = FS.getLengthModifier();
7208 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7209
7210 // See if we know how to fix this length modifier.
7211 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7212 if (FixedLM) {
7213 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7214 getLocationOfByte(LM.getStart()),
7215 /*IsStringLocation*/true,
7216 getSpecifierRange(startSpecifier, specifierLen));
7217
7218 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7219 << FixedLM->toString()
7220 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7221
7222 } else {
7223 FixItHint Hint;
7224 if (DiagID == diag::warn_format_nonsensical_length)
7225 Hint = FixItHint::CreateRemoval(LMRange);
7226
7227 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7228 getLocationOfByte(LM.getStart()),
7229 /*IsStringLocation*/true,
7230 getSpecifierRange(startSpecifier, specifierLen),
7231 Hint);
7232 }
7233}
7234
7235void CheckFormatHandler::HandleNonStandardLengthModifier(
7236 const analyze_format_string::FormatSpecifier &FS,
7237 const char *startSpecifier, unsigned specifierLen) {
7238 using namespace analyze_format_string;
7239
7240 const LengthModifier &LM = FS.getLengthModifier();
7241 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7242
7243 // See if we know how to fix this length modifier.
7244 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7245 if (FixedLM) {
7246 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7247 << LM.toString() << 0,
7248 getLocationOfByte(LM.getStart()),
7249 /*IsStringLocation*/true,
7250 getSpecifierRange(startSpecifier, specifierLen));
7251
7252 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7253 << FixedLM->toString()
7254 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7255
7256 } else {
7257 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7258 << LM.toString() << 0,
7259 getLocationOfByte(LM.getStart()),
7260 /*IsStringLocation*/true,
7261 getSpecifierRange(startSpecifier, specifierLen));
7262 }
7263}
7264
7265void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7266 const analyze_format_string::ConversionSpecifier &CS,
7267 const char *startSpecifier, unsigned specifierLen) {
7268 using namespace analyze_format_string;
7269
7270 // See if we know how to fix this conversion specifier.
7271 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7272 if (FixedCS) {
7273 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7274 << CS.toString() << /*conversion specifier*/1,
7275 getLocationOfByte(CS.getStart()),
7276 /*IsStringLocation*/true,
7277 getSpecifierRange(startSpecifier, specifierLen));
7278
7279 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7280 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7281 << FixedCS->toString()
7282 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7283 } else {
7284 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7285 << CS.toString() << /*conversion specifier*/1,
7286 getLocationOfByte(CS.getStart()),
7287 /*IsStringLocation*/true,
7288 getSpecifierRange(startSpecifier, specifierLen));
7289 }
7290}
7291
7292void CheckFormatHandler::HandlePosition(const char *startPos,
7293 unsigned posLen) {
7294 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7295 getLocationOfByte(startPos),
7296 /*IsStringLocation*/true,
7297 getSpecifierRange(startPos, posLen));
7298}
7299
7300void
7301CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7302 analyze_format_string::PositionContext p) {
7303 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7304 << (unsigned) p,
7305 getLocationOfByte(startPos), /*IsStringLocation*/true,
7306 getSpecifierRange(startPos, posLen));
7307}
7308
7309void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7310 unsigned posLen) {
7311 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7312 getLocationOfByte(startPos),
7313 /*IsStringLocation*/true,
7314 getSpecifierRange(startPos, posLen));
7315}
7316
7317void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7318 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7319 // The presence of a null character is likely an error.
7320 EmitFormatDiagnostic(
7321 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7322 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7323 getFormatStringRange());
7324 }
7325}
7326
7327// Note that this may return NULL if there was an error parsing or building
7328// one of the argument expressions.
7329const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7330 return Args[FirstDataArg + i];
7331}
7332
7333void CheckFormatHandler::DoneProcessing() {
7334 // Does the number of data arguments exceed the number of
7335 // format conversions in the format string?
7336 if (!HasVAListArg) {
7337 // Find any arguments that weren't covered.
7338 CoveredArgs.flip();
7339 signed notCoveredArg = CoveredArgs.find_first();
7340 if (notCoveredArg >= 0) {
7341 assert((unsigned)notCoveredArg < NumDataArgs)(((unsigned)notCoveredArg < NumDataArgs) ? static_cast<
void> (0) : __assert_fail ("(unsigned)notCoveredArg < NumDataArgs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 7341, __PRETTY_FUNCTION__))
;
7342 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7343 } else {
7344 UncoveredArg.setAllCovered();
7345 }
7346 }
7347}
7348
7349void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7350 const Expr *ArgExpr) {
7351 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&((hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
"Invalid state") ? static_cast<void> (0) : __assert_fail
("hasUncoveredArg() && DiagnosticExprs.size() > 0 && \"Invalid state\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 7352, __PRETTY_FUNCTION__))
7352 "Invalid state")((hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
"Invalid state") ? static_cast<void> (0) : __assert_fail
("hasUncoveredArg() && DiagnosticExprs.size() > 0 && \"Invalid state\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 7352, __PRETTY_FUNCTION__))
;
7353
7354 if (!ArgExpr)
7355 return;
7356
7357 SourceLocation Loc = ArgExpr->getBeginLoc();
7358
7359 if (S.getSourceManager().isInSystemMacro(Loc))
7360 return;
7361
7362 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7363 for (auto E : DiagnosticExprs)
7364 PDiag << E->getSourceRange();
7365
7366 CheckFormatHandler::EmitFormatDiagnostic(
7367 S, IsFunctionCall, DiagnosticExprs[0],
7368 PDiag, Loc, /*IsStringLocation*/false,
7369 DiagnosticExprs[0]->getSourceRange());
7370}
7371
7372bool
7373CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7374 SourceLocation Loc,
7375 const char *startSpec,
7376 unsigned specifierLen,
7377 const char *csStart,
7378 unsigned csLen) {
7379 bool keepGoing = true;
7380 if (argIndex < NumDataArgs) {
7381 // Consider the argument coverered, even though the specifier doesn't
7382 // make sense.
7383 CoveredArgs.set(argIndex);
7384 }
7385 else {
7386 // If argIndex exceeds the number of data arguments we
7387 // don't issue a warning because that is just a cascade of warnings (and
7388 // they may have intended '%%' anyway). We don't want to continue processing
7389 // the format string after this point, however, as we will like just get
7390 // gibberish when trying to match arguments.
7391 keepGoing = false;
7392 }
7393
7394 StringRef Specifier(csStart, csLen);
7395
7396 // If the specifier in non-printable, it could be the first byte of a UTF-8
7397 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7398 // hex value.
7399 std::string CodePointStr;
7400 if (!llvm::sys::locale::isPrint(*csStart)) {
7401 llvm::UTF32 CodePoint;
7402 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7403 const llvm::UTF8 *E =
7404 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7405 llvm::ConversionResult Result =
7406 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7407
7408 if (Result != llvm::conversionOK) {
7409 unsigned char FirstChar = *csStart;
7410 CodePoint = (llvm::UTF32)FirstChar;
7411 }
7412
7413 llvm::raw_string_ostream OS(CodePointStr);
7414 if (CodePoint < 256)
7415 OS << "\\x" << llvm::format("%02x", CodePoint);
7416 else if (CodePoint <= 0xFFFF)
7417 OS << "\\u" << llvm::format("%04x", CodePoint);
7418 else
7419 OS << "\\U" << llvm::format("%08x", CodePoint);
7420 OS.flush();
7421 Specifier = CodePointStr;
7422 }
7423
7424 EmitFormatDiagnostic(
7425 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7426 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7427
7428 return keepGoing;
7429}
7430
7431void
7432CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7433 const char *startSpec,
7434 unsigned specifierLen) {
7435 EmitFormatDiagnostic(
7436 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7437 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7438}
7439
7440bool
7441CheckFormatHandler::CheckNumArgs(
7442 const analyze_format_string::FormatSpecifier &FS,
7443 const analyze_format_string::ConversionSpecifier &CS,
7444 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7445
7446 if (argIndex >= NumDataArgs) {
7447 PartialDiagnostic PDiag = FS.usesPositionalArg()
7448 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7449 << (argIndex+1) << NumDataArgs)
7450 : S.PDiag(diag::warn_printf_insufficient_data_args);
7451 EmitFormatDiagnostic(
7452 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7453 getSpecifierRange(startSpecifier, specifierLen));
7454
7455 // Since more arguments than conversion tokens are given, by extension
7456 // all arguments are covered, so mark this as so.
7457 UncoveredArg.setAllCovered();
7458 return false;
7459 }
7460 return true;
7461}
7462
7463template<typename Range>
7464void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7465 SourceLocation Loc,
7466 bool IsStringLocation,
7467 Range StringRange,
7468 ArrayRef<FixItHint> FixIt) {
7469 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7470 Loc, IsStringLocation, StringRange, FixIt);
7471}
7472
7473/// If the format string is not within the function call, emit a note
7474/// so that the function call and string are in diagnostic messages.
7475///
7476/// \param InFunctionCall if true, the format string is within the function
7477/// call and only one diagnostic message will be produced. Otherwise, an
7478/// extra note will be emitted pointing to location of the format string.
7479///
7480/// \param ArgumentExpr the expression that is passed as the format string
7481/// argument in the function call. Used for getting locations when two
7482/// diagnostics are emitted.
7483///
7484/// \param PDiag the callee should already have provided any strings for the
7485/// diagnostic message. This function only adds locations and fixits
7486/// to diagnostics.
7487///
7488/// \param Loc primary location for diagnostic. If two diagnostics are
7489/// required, one will be at Loc and a new SourceLocation will be created for
7490/// the other one.
7491///
7492/// \param IsStringLocation if true, Loc points to the format string should be
7493/// used for the note. Otherwise, Loc points to the argument list and will
7494/// be used with PDiag.
7495///
7496/// \param StringRange some or all of the string to highlight. This is
7497/// templated so it can accept either a CharSourceRange or a SourceRange.
7498///
7499/// \param FixIt optional fix it hint for the format string.
7500template <typename Range>
7501void CheckFormatHandler::EmitFormatDiagnostic(
7502 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7503 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7504 Range StringRange, ArrayRef<FixItHint> FixIt) {
7505 if (InFunctionCall) {
7506 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7507 D << StringRange;
7508 D << FixIt;
7509 } else {
7510 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7511 << ArgumentExpr->getSourceRange();
7512
7513 const Sema::SemaDiagnosticBuilder &Note =
7514 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7515 diag::note_format_string_defined);
7516
7517 Note << StringRange;
7518 Note << FixIt;
7519 }
7520}
7521
7522//===--- CHECK: Printf format string checking ------------------------------===//
7523
7524namespace {
7525
7526class CheckPrintfHandler : public CheckFormatHandler {
7527public:
7528 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7529 const Expr *origFormatExpr,
7530 const Sema::FormatStringType type, unsigned firstDataArg,
7531 unsigned numDataArgs, bool isObjC, const char *beg,
7532 bool hasVAListArg, ArrayRef<const Expr *> Args,
7533 unsigned formatIdx, bool inFunctionCall,
7534 Sema::VariadicCallType CallType,
7535 llvm::SmallBitVector &CheckedVarArgs,
7536 UncoveredArgHandler &UncoveredArg)
7537 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7538 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7539 inFunctionCall, CallType, CheckedVarArgs,
7540 UncoveredArg) {}
7541
7542 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7543
7544 /// Returns true if '%@' specifiers are allowed in the format string.
7545 bool allowsObjCArg() const {
7546 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7547 FSType == Sema::FST_OSTrace;
7548 }
7549
7550 bool HandleInvalidPrintfConversionSpecifier(
7551 const analyze_printf::PrintfSpecifier &FS,
7552 const char *startSpecifier,
7553 unsigned specifierLen) override;
7554
7555 void handleInvalidMaskType(StringRef MaskType) override;
7556
7557 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7558 const char *startSpecifier,
7559 unsigned specifierLen) override;
7560 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7561 const char *StartSpecifier,
7562 unsigned SpecifierLen,
7563 const Expr *E);
7564
7565 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7566 const char *startSpecifier, unsigned specifierLen);
7567 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7568 const analyze_printf::OptionalAmount &Amt,
7569 unsigned type,
7570 const char *startSpecifier, unsigned specifierLen);
7571 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7572 const analyze_printf::OptionalFlag &flag,
7573 const char *startSpecifier, unsigned specifierLen);
7574 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7575 const analyze_printf::OptionalFlag &ignoredFlag,
7576 const analyze_printf::OptionalFlag &flag,
7577 const char *startSpecifier, unsigned specifierLen);
7578 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7579 const Expr *E);
7580
7581 void HandleEmptyObjCModifierFlag(const char *startFlag,
7582 unsigned flagLen) override;
7583
7584 void HandleInvalidObjCModifierFlag(const char *startFlag,
7585 unsigned flagLen) override;
7586
7587 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7588 const char *flagsEnd,
7589 const char *conversionPosition)
7590 override;
7591};
7592
7593} // namespace
7594
7595bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7596 const analyze_printf::PrintfSpecifier &FS,
7597 const char *startSpecifier,
7598 unsigned specifierLen) {
7599 const analyze_printf::PrintfConversionSpecifier &CS =
7600 FS.getConversionSpecifier();
7601
7602 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7603 getLocationOfByte(CS.getStart()),
7604 startSpecifier, specifierLen,
7605 CS.getStart(), CS.getLength());
7606}
7607
7608void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7609 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7610}
7611
7612bool CheckPrintfHandler::HandleAmount(
7613 const analyze_format_string::OptionalAmount &Amt,
7614 unsigned k, const char *startSpecifier,
7615 unsigned specifierLen) {
7616 if (Amt.hasDataArgument()) {
7617 if (!HasVAListArg) {
7618 unsigned argIndex = Amt.getArgIndex();
7619 if (argIndex >= NumDataArgs) {
7620 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7621 << k,
7622 getLocationOfByte(Amt.getStart()),
7623 /*IsStringLocation*/true,
7624 getSpecifierRange(startSpecifier, specifierLen));
7625 // Don't do any more checking. We will just emit
7626 // spurious errors.
7627 return false;
7628 }
7629
7630 // Type check the data argument. It should be an 'int'.
7631 // Although not in conformance with C99, we also allow the argument to be
7632 // an 'unsigned int' as that is a reasonably safe case. GCC also
7633 // doesn't emit a warning for that case.
7634 CoveredArgs.set(argIndex);
7635 const Expr *Arg = getDataArg(argIndex);
7636 if (!Arg)
7637 return false;
7638
7639 QualType T = Arg->getType();
7640
7641 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7642 assert(AT.isValid())((AT.isValid()) ? static_cast<void> (0) : __assert_fail
("AT.isValid()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 7642, __PRETTY_FUNCTION__))
;
7643
7644 if (!AT.matchesType(S.Context, T)) {
7645 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7646 << k << AT.getRepresentativeTypeName(S.Context)
7647 << T << Arg->getSourceRange(),
7648 getLocationOfByte(Amt.getStart()),
7649 /*IsStringLocation*/true,
7650 getSpecifierRange(startSpecifier, specifierLen));
7651 // Don't do any more checking. We will just emit
7652 // spurious errors.
7653 return false;
7654 }
7655 }
7656 }
7657 return true;
7658}
7659
7660void CheckPrintfHandler::HandleInvalidAmount(
7661 const analyze_printf::PrintfSpecifier &FS,
7662 const analyze_printf::OptionalAmount &Amt,
7663 unsigned type,
7664 const char *startSpecifier,
7665 unsigned specifierLen) {
7666 const analyze_printf::PrintfConversionSpecifier &CS =
7667 FS.getConversionSpecifier();
7668
7669 FixItHint fixit =
7670 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7671 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7672 Amt.getConstantLength()))
7673 : FixItHint();
7674
7675 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7676 << type << CS.toString(),
7677 getLocationOfByte(Amt.getStart()),
7678 /*IsStringLocation*/true,
7679 getSpecifierRange(startSpecifier, specifierLen),
7680 fixit);
7681}
7682
7683void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7684 const analyze_printf::OptionalFlag &flag,
7685 const char *startSpecifier,
7686 unsigned specifierLen) {
7687 // Warn about pointless flag with a fixit removal.
7688 const analyze_printf::PrintfConversionSpecifier &CS =
7689 FS.getConversionSpecifier();
7690 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7691 << flag.toString() << CS.toString(),
7692 getLocationOfByte(flag.getPosition()),
7693 /*IsStringLocation*/true,
7694 getSpecifierRange(startSpecifier, specifierLen),
7695 FixItHint::CreateRemoval(
7696 getSpecifierRange(flag.getPosition(), 1)));
7697}
7698
7699void CheckPrintfHandler::HandleIgnoredFlag(
7700 const analyze_printf::PrintfSpecifier &FS,
7701 const analyze_printf::OptionalFlag &ignoredFlag,
7702 const analyze_printf::OptionalFlag &flag,
7703 const char *startSpecifier,
7704 unsigned specifierLen) {
7705 // Warn about ignored flag with a fixit removal.
7706 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7707 << ignoredFlag.toString() << flag.toString(),
7708 getLocationOfByte(ignoredFlag.getPosition()),
7709 /*IsStringLocation*/true,
7710 getSpecifierRange(startSpecifier, specifierLen),
7711 FixItHint::CreateRemoval(
7712 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7713}
7714
7715void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7716 unsigned flagLen) {
7717 // Warn about an empty flag.
7718 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7719 getLocationOfByte(startFlag),
7720 /*IsStringLocation*/true,
7721 getSpecifierRange(startFlag, flagLen));
7722}
7723
7724void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7725 unsigned flagLen) {
7726 // Warn about an invalid flag.
7727 auto Range = getSpecifierRange(startFlag, flagLen);
7728 StringRef flag(startFlag, flagLen);
7729 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7730 getLocationOfByte(startFlag),
7731 /*IsStringLocation*/true,
7732 Range, FixItHint::CreateRemoval(Range));
7733}
7734
7735void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7736 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7737 // Warn about using '[...]' without a '@' conversion.
7738 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7739 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7740 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7741 getLocationOfByte(conversionPosition),
7742 /*IsStringLocation*/true,
7743 Range, FixItHint::CreateRemoval(Range));
7744}
7745
7746// Determines if the specified is a C++ class or struct containing
7747// a member with the specified name and kind (e.g. a CXXMethodDecl named
7748// "c_str()").
7749template<typename MemberKind>
7750static llvm::SmallPtrSet<MemberKind*, 1>
7751CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7752 const RecordType *RT = Ty->getAs<RecordType>();
7753 llvm::SmallPtrSet<MemberKind*, 1> Results;
7754
7755 if (!RT)
7756 return Results;
7757 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7758 if (!RD || !RD->getDefinition())
7759 return Results;
7760
7761 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7762 Sema::LookupMemberName);
7763 R.suppressDiagnostics();
7764
7765 // We just need to include all members of the right kind turned up by the
7766 // filter, at this point.
7767 if (S.LookupQualifiedName(R, RT->getDecl()))
7768 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7769 NamedDecl *decl = (*I)->getUnderlyingDecl();
7770 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7771 Results.insert(FK);
7772 }
7773 return Results;
7774}
7775
7776/// Check if we could call '.c_str()' on an object.
7777///
7778/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7779/// allow the call, or if it would be ambiguous).
7780bool Sema::hasCStrMethod(const Expr *E) {
7781 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7782
7783 MethodSet Results =
7784 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7785 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7786 MI != ME; ++MI)
7787 if ((*MI)->getMinRequiredArguments() == 0)
7788 return true;
7789 return false;
7790}
7791
7792// Check if a (w)string was passed when a (w)char* was needed, and offer a
7793// better diagnostic if so. AT is assumed to be valid.
7794// Returns true when a c_str() conversion method is found.
7795bool CheckPrintfHandler::checkForCStrMembers(
7796 const analyze_printf::ArgType &AT, const Expr *E) {
7797 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7798
7799 MethodSet Results =
7800 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7801
7802 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7803 MI != ME; ++MI) {
7804 const CXXMethodDecl *Method = *MI;
7805 if (Method->getMinRequiredArguments() == 0 &&
7806 AT.matchesType(S.Context, Method->getReturnType())) {
7807 // FIXME: Suggest parens if the expression needs them.
7808 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7809 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7810 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7811 return true;
7812 }
7813 }
7814
7815 return false;
7816}
7817
7818bool
7819CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7820 &FS,
7821 const char *startSpecifier,
7822 unsigned specifierLen) {
7823 using namespace analyze_format_string;
7824 using namespace analyze_printf;
7825
7826 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7827
7828 if (FS.consumesDataArgument()) {
7829 if (atFirstArg) {
7830 atFirstArg = false;
7831 usesPositionalArgs = FS.usesPositionalArg();
7832 }
7833 else if (usesPositionalArgs != FS.usesPositionalArg()) {
7834 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7835 startSpecifier, specifierLen);
7836 return false;
7837 }
7838 }
7839
7840 // First check if the field width, precision, and conversion specifier
7841 // have matching data arguments.
7842 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7843 startSpecifier, specifierLen)) {
7844 return false;
7845 }
7846
7847 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7848 startSpecifier, specifierLen)) {
7849 return false;
7850 }
7851
7852 if (!CS.consumesDataArgument()) {
7853 // FIXME: Technically specifying a precision or field width here
7854 // makes no sense. Worth issuing a warning at some point.
7855 return true;
7856 }
7857
7858 // Consume the argument.
7859 unsigned argIndex = FS.getArgIndex();
7860 if (argIndex < NumDataArgs) {
7861 // The check to see if the argIndex is valid will come later.
7862 // We set the bit here because we may exit early from this
7863 // function if we encounter some other error.
7864 CoveredArgs.set(argIndex);
7865 }
7866
7867 // FreeBSD kernel extensions.
7868 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7869 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7870 // We need at least two arguments.
7871 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7872 return false;
7873
7874 // Claim the second argument.
7875 CoveredArgs.set(argIndex + 1);
7876
7877 // Type check the first argument (int for %b, pointer for %D)
7878 const Expr *Ex = getDataArg(argIndex);
7879 const analyze_printf::ArgType &AT =
7880 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7881 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7882 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7883 EmitFormatDiagnostic(
7884 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7885 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7886 << false << Ex->getSourceRange(),
7887 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7888 getSpecifierRange(startSpecifier, specifierLen));
7889
7890 // Type check the second argument (char * for both %b and %D)
7891 Ex = getDataArg(argIndex + 1);
7892 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7893 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7894 EmitFormatDiagnostic(
7895 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7896 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7897 << false << Ex->getSourceRange(),
7898 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7899 getSpecifierRange(startSpecifier, specifierLen));
7900
7901 return true;
7902 }
7903
7904 // Check for using an Objective-C specific conversion specifier
7905 // in a non-ObjC literal.
7906 if (!allowsObjCArg() && CS.isObjCArg()) {
7907 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7908 specifierLen);
7909 }
7910
7911 // %P can only be used with os_log.
7912 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7913 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7914 specifierLen);
7915 }
7916
7917 // %n is not allowed with os_log.
7918 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7919 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7920 getLocationOfByte(CS.getStart()),
7921 /*IsStringLocation*/ false,
7922 getSpecifierRange(startSpecifier, specifierLen));
7923
7924 return true;
7925 }
7926
7927 // Only scalars are allowed for os_trace.
7928 if (FSType == Sema::FST_OSTrace &&
7929 (CS.getKind() == ConversionSpecifier::PArg ||
7930 CS.getKind() == ConversionSpecifier::sArg ||
7931 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7932 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7933 specifierLen);
7934 }
7935
7936 // Check for use of public/private annotation outside of os_log().
7937 if (FSType != Sema::FST_OSLog) {
7938 if (FS.isPublic().isSet()) {
7939 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7940 << "public",
7941 getLocationOfByte(FS.isPublic().getPosition()),
7942 /*IsStringLocation*/ false,
7943 getSpecifierRange(startSpecifier, specifierLen));
7944 }
7945 if (FS.isPrivate().isSet()) {
7946 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7947 << "private",
7948 getLocationOfByte(FS.isPrivate().getPosition()),
7949 /*IsStringLocation*/ false,
7950 getSpecifierRange(startSpecifier, specifierLen));
7951 }
7952 }
7953
7954 // Check for invalid use of field width
7955 if (!FS.hasValidFieldWidth()) {
7956 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7957 startSpecifier, specifierLen);
7958 }
7959
7960 // Check for invalid use of precision
7961 if (!FS.hasValidPrecision()) {
7962 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7963 startSpecifier, specifierLen);
7964 }
7965
7966 // Precision is mandatory for %P specifier.
7967 if (CS.getKind() == ConversionSpecifier::PArg &&
7968 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7969 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7970 getLocationOfByte(startSpecifier),
7971 /*IsStringLocation*/ false,
7972 getSpecifierRange(startSpecifier, specifierLen));
7973 }
7974
7975 // Check each flag does not conflict with any other component.
7976 if (!FS.hasValidThousandsGroupingPrefix())
7977 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7978 if (!FS.hasValidLeadingZeros())
7979 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7980 if (!FS.hasValidPlusPrefix())
7981 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7982 if (!FS.hasValidSpacePrefix())
7983 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7984 if (!FS.hasValidAlternativeForm())
7985 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7986 if (!FS.hasValidLeftJustified())
7987 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7988
7989 // Check that flags are not ignored by another flag
7990 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7991 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7992 startSpecifier, specifierLen);
7993 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7994 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7995 startSpecifier, specifierLen);
7996
7997 // Check the length modifier is valid with the given conversion specifier.
7998 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7999 S.getLangOpts()))
8000 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8001 diag::warn_format_nonsensical_length);
8002 else if (!FS.hasStandardLengthModifier())
8003 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8004 else if (!FS.hasStandardLengthConversionCombination())
8005 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8006 diag::warn_format_non_standard_conversion_spec);
8007
8008 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8009 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8010
8011 // The remaining checks depend on the data arguments.
8012 if (HasVAListArg)
8013 return true;
8014
8015 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8016 return false;
8017
8018 const Expr *Arg = getDataArg(argIndex);
8019 if (!Arg)
8020 return true;
8021
8022 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8023}
8024
8025static bool requiresParensToAddCast(const Expr *E) {
8026 // FIXME: We should have a general way to reason about operator
8027 // precedence and whether parens are actually needed here.
8028 // Take care of a few common cases where they aren't.
8029 const Expr *Inside = E->IgnoreImpCasts();
8030 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8031 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8032
8033 switch (Inside->getStmtClass()) {
8034 case Stmt::ArraySubscriptExprClass:
8035 case Stmt::CallExprClass:
8036 case Stmt::CharacterLiteralClass:
8037 case Stmt::CXXBoolLiteralExprClass:
8038 case Stmt::DeclRefExprClass:
8039 case Stmt::FloatingLiteralClass:
8040 case Stmt::IntegerLiteralClass:
8041 case Stmt::MemberExprClass:
8042 case Stmt::ObjCArrayLiteralClass:
8043 case Stmt::ObjCBoolLiteralExprClass:
8044 case Stmt::ObjCBoxedExprClass:
8045 case Stmt::ObjCDictionaryLiteralClass:
8046 case Stmt::ObjCEncodeExprClass:
8047 case Stmt::ObjCIvarRefExprClass:
8048 case Stmt::ObjCMessageExprClass:
8049 case Stmt::ObjCPropertyRefExprClass:
8050 case Stmt::ObjCStringLiteralClass:
8051 case Stmt::ObjCSubscriptRefExprClass:
8052 case Stmt::ParenExprClass:
8053 case Stmt::StringLiteralClass:
8054 case Stmt::UnaryOperatorClass:
8055 return false;
8056 default:
8057 return true;
8058 }
8059}
8060
8061static std::pair<QualType, StringRef>
8062shouldNotPrintDirectly(const ASTContext &Context,
8063 QualType IntendedTy,
8064 const Expr *E) {
8065 // Use a 'while' to peel off layers of typedefs.
8066 QualType TyTy = IntendedTy;
8067 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8068 StringRef Name = UserTy->getDecl()->getName();
8069 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8070 .Case("CFIndex", Context.getNSIntegerType())
8071 .Case("NSInteger", Context.getNSIntegerType())
8072 .Case("NSUInteger", Context.getNSUIntegerType())
8073 .Case("SInt32", Context.IntTy)
8074 .Case("UInt32", Context.UnsignedIntTy)
8075 .Default(QualType());
8076
8077 if (!CastTy.isNull())
8078 return std::make_pair(CastTy, Name);
8079
8080 TyTy = UserTy->desugar();
8081 }
8082
8083 // Strip parens if necessary.
8084 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8085 return shouldNotPrintDirectly(Context,
8086 PE->getSubExpr()->getType(),
8087 PE->getSubExpr());
8088
8089 // If this is a conditional expression, then its result type is constructed
8090 // via usual arithmetic conversions and thus there might be no necessary
8091 // typedef sugar there. Recurse to operands to check for NSInteger &
8092 // Co. usage condition.
8093 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8094 QualType TrueTy, FalseTy;
8095 StringRef TrueName, FalseName;
8096
8097 std::tie(TrueTy, TrueName) =
8098 shouldNotPrintDirectly(Context,
8099 CO->getTrueExpr()->getType(),
8100 CO->getTrueExpr());
8101 std::tie(FalseTy, FalseName) =
8102 shouldNotPrintDirectly(Context,
8103 CO->getFalseExpr()->getType(),
8104 CO->getFalseExpr());
8105
8106 if (TrueTy == FalseTy)
8107 return std::make_pair(TrueTy, TrueName);
8108 else if (TrueTy.isNull())
8109 return std::make_pair(FalseTy, FalseName);
8110 else if (FalseTy.isNull())
8111 return std::make_pair(TrueTy, TrueName);
8112 }
8113
8114 return std::make_pair(QualType(), StringRef());
8115}
8116
8117/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8118/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8119/// type do not count.
8120static bool
8121isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8122 QualType From = ICE->getSubExpr()->getType();
8123 QualType To = ICE->getType();
8124 // It's an integer promotion if the destination type is the promoted
8125 // source type.
8126 if (ICE->getCastKind() == CK_IntegralCast &&
8127 From->isPromotableIntegerType() &&
8128 S.Context.getPromotedIntegerType(From) == To)
8129 return true;
8130 // Look through vector types, since we do default argument promotion for
8131 // those in OpenCL.
8132 if (const auto *VecTy = From->getAs<ExtVectorType>())
8133 From = VecTy->getElementType();
8134 if (const auto *VecTy = To->getAs<ExtVectorType>())
8135 To = VecTy->getElementType();
8136 // It's a floating promotion if the source type is a lower rank.
8137 return ICE->getCastKind() == CK_FloatingCast &&
8138 S.Context.getFloatingTypeOrder(From, To) < 0;
8139}
8140
8141bool
8142CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8143 const char *StartSpecifier,
8144 unsigned SpecifierLen,
8145 const Expr *E) {
8146 using namespace analyze_format_string;
8147 using namespace analyze_printf;
8148
8149 // Now type check the data expression that matches the
8150 // format specifier.
8151 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8152 if (!AT.isValid())
8153 return true;
8154
8155 QualType ExprTy = E->getType();
8156 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8157 ExprTy = TET->getUnderlyingExpr()->getType();
8158 }
8159
8160 // Diagnose attempts to print a boolean value as a character. Unlike other
8161 // -Wformat diagnostics, this is fine from a type perspective, but it still
8162 // doesn't make sense.
8163 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8164 E->isKnownToHaveBooleanValue()) {
8165 const CharSourceRange &CSR =
8166 getSpecifierRange(StartSpecifier, SpecifierLen);
8167 SmallString<4> FSString;
8168 llvm::raw_svector_ostream os(FSString);
8169 FS.toString(os);
8170 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8171 << FSString,
8172 E->getExprLoc(), false, CSR);
8173 return true;
8174 }
8175
8176 const analyze_printf::ArgType::MatchKind Match =
8177 AT.matchesType(S.Context, ExprTy);
8178 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
8179 if (Match == analyze_printf::ArgType::Match)
8180 return true;
8181
8182 // Look through argument promotions for our error message's reported type.
8183 // This includes the integral and floating promotions, but excludes array
8184 // and function pointer decay (seeing that an argument intended to be a
8185 // string has type 'char [6]' is probably more confusing than 'char *') and
8186 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8187 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8188 if (isArithmeticArgumentPromotion(S, ICE)) {
8189 E = ICE->getSubExpr();
8190 ExprTy = E->getType();
8191
8192 // Check if we didn't match because of an implicit cast from a 'char'
8193 // or 'short' to an 'int'. This is done because printf is a varargs
8194 // function.
8195 if (ICE->getType() == S.Context.IntTy ||
8196 ICE->getType() == S.Context.UnsignedIntTy) {
8197 // All further checking is done on the subexpression
8198 const analyze_printf::ArgType::MatchKind ImplicitMatch =
8199 AT.matchesType(S.Context, ExprTy);
8200 if (ImplicitMatch == analyze_printf::ArgType::Match)
8201 return true;
8202 if (ImplicitMatch == analyze_printf::ArgType::NoMatchPedantic)
8203 Pedantic = true;
8204 }
8205 }
8206 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8207 // Special case for 'a', which has type 'int' in C.
8208 // Note, however, that we do /not/ want to treat multibyte constants like
8209 // 'MooV' as characters! This form is deprecated but still exists.
8210 if (ExprTy == S.Context.IntTy)
8211 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8212 ExprTy = S.Context.CharTy;
8213 }
8214
8215 // Look through enums to their underlying type.
8216 bool IsEnum = false;
8217 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8218 ExprTy = EnumTy->getDecl()->getIntegerType();
8219 IsEnum = true;
8220 }
8221
8222 // %C in an Objective-C context prints a unichar, not a wchar_t.
8223 // If the argument is an integer of some kind, believe the %C and suggest
8224 // a cast instead of changing the conversion specifier.
8225 QualType IntendedTy = ExprTy;
8226 if (isObjCContext() &&
8227 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8228 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8229 !ExprTy->isCharType()) {
8230 // 'unichar' is defined as a typedef of unsigned short, but we should
8231 // prefer using the typedef if it is visible.
8232 IntendedTy = S.Context.UnsignedShortTy;
8233
8234 // While we are here, check if the value is an IntegerLiteral that happens
8235 // to be within the valid range.
8236 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8237 const llvm::APInt &V = IL->getValue();
8238 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8239 return true;
8240 }
8241
8242 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8243 Sema::LookupOrdinaryName);
8244 if (S.LookupName(Result, S.getCurScope())) {
8245 NamedDecl *ND = Result.getFoundDecl();
8246 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8247 if (TD->getUnderlyingType() == IntendedTy)
8248 IntendedTy = S.Context.getTypedefType(TD);
8249 }
8250 }
8251 }
8252
8253 // Special-case some of Darwin's platform-independence types by suggesting
8254 // casts to primitive types that are known to be large enough.
8255 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8256 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8257 QualType CastTy;
8258 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8259 if (!CastTy.isNull()) {
8260 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8261 // (long in ASTContext). Only complain to pedants.
8262 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8263 (AT.isSizeT() || AT.isPtrdiffT()) &&
8264 AT.matchesType(S.Context, CastTy))
8265 Pedantic = true;
8266 IntendedTy = CastTy;
8267 ShouldNotPrintDirectly = true;
8268 }
8269 }
8270
8271 // We may be able to offer a FixItHint if it is a supported type.
8272 PrintfSpecifier fixedFS = FS;
8273 bool Success =
8274 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8275
8276 if (Success) {
8277 // Get the fix string from the fixed format specifier
8278 SmallString<16> buf;
8279 llvm::raw_svector_ostream os(buf);
8280 fixedFS.toString(os);
8281
8282 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8283
8284 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8285 unsigned Diag =
8286 Pedantic
8287 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8288 : diag::warn_format_conversion_argument_type_mismatch;
8289 // In this case, the specifier is wrong and should be changed to match
8290 // the argument.
8291 EmitFormatDiagnostic(S.PDiag(Diag)
8292 << AT.getRepresentativeTypeName(S.Context)
8293 << IntendedTy << IsEnum << E->getSourceRange(),
8294 E->getBeginLoc(),
8295 /*IsStringLocation*/ false, SpecRange,
8296 FixItHint::CreateReplacement(SpecRange, os.str()));
8297 } else {
8298 // The canonical type for formatting this value is different from the
8299 // actual type of the expression. (This occurs, for example, with Darwin's
8300 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8301 // should be printed as 'long' for 64-bit compatibility.)
8302 // Rather than emitting a normal format/argument mismatch, we want to
8303 // add a cast to the recommended type (and correct the format string
8304 // if necessary).
8305 SmallString<16> CastBuf;
8306 llvm::raw_svector_ostream CastFix(CastBuf);
8307 CastFix << "(";
8308 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8309 CastFix << ")";
8310
8311 SmallVector<FixItHint,4> Hints;
8312 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8313 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8314
8315 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8316 // If there's already a cast present, just replace it.
8317 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8318 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8319
8320 } else if (!requiresParensToAddCast(E)) {
8321 // If the expression has high enough precedence,
8322 // just write the C-style cast.
8323 Hints.push_back(
8324 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8325 } else {
8326 // Otherwise, add parens around the expression as well as the cast.
8327 CastFix << "(";
8328 Hints.push_back(
8329 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8330
8331 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8332 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8333 }
8334
8335 if (ShouldNotPrintDirectly) {
8336 // The expression has a type that should not be printed directly.
8337 // We extract the name from the typedef because we don't want to show
8338 // the underlying type in the diagnostic.
8339 StringRef Name;
8340 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8341 Name = TypedefTy->getDecl()->getName();
8342 else
8343 Name = CastTyName;
8344 unsigned Diag = Pedantic
8345 ? diag::warn_format_argument_needs_cast_pedantic
8346 : diag::warn_format_argument_needs_cast;
8347 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8348 << E->getSourceRange(),
8349 E->getBeginLoc(), /*IsStringLocation=*/false,
8350 SpecRange, Hints);
8351 } else {
8352 // In this case, the expression could be printed using a different
8353 // specifier, but we've decided that the specifier is probably correct
8354 // and we should cast instead. Just use the normal warning message.
8355 EmitFormatDiagnostic(
8356 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8357 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8358 << E->getSourceRange(),
8359 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8360 }
8361 }
8362 } else {
8363 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8364 SpecifierLen);
8365 // Since the warning for passing non-POD types to variadic functions
8366 // was deferred until now, we emit a warning for non-POD
8367 // arguments here.
8368 switch (S.isValidVarArgType(ExprTy)) {
8369 case Sema::VAK_Valid:
8370 case Sema::VAK_ValidInCXX11: {
8371 unsigned Diag =
8372 Pedantic
8373 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8374 : diag::warn_format_conversion_argument_type_mismatch;
8375
8376 EmitFormatDiagnostic(
8377 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8378 << IsEnum << CSR << E->getSourceRange(),
8379 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8380 break;
8381 }
8382 case Sema::VAK_Undefined:
8383 case Sema::VAK_MSVCUndefined:
8384 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8385 << S.getLangOpts().CPlusPlus11 << ExprTy
8386 << CallType
8387 << AT.getRepresentativeTypeName(S.Context) << CSR
8388 << E->getSourceRange(),
8389 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8390 checkForCStrMembers(AT, E);
8391 break;
8392
8393 case Sema::VAK_Invalid:
8394 if (ExprTy->isObjCObjectType())
8395 EmitFormatDiagnostic(
8396 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8397 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8398 << AT.getRepresentativeTypeName(S.Context) << CSR
8399 << E->getSourceRange(),
8400 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8401 else
8402 // FIXME: If this is an initializer list, suggest removing the braces
8403 // or inserting a cast to the target type.
8404 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8405 << isa<InitListExpr>(E) << ExprTy << CallType
8406 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8407 break;
8408 }
8409
8410 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&((FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
"format string specifier index out of range") ? static_cast<
void> (0) : __assert_fail ("FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && \"format string specifier index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8411, __PRETTY_FUNCTION__))
8411 "format string specifier index out of range")((FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
"format string specifier index out of range") ? static_cast<
void> (0) : __assert_fail ("FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && \"format string specifier index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8411, __PRETTY_FUNCTION__))
;
8412 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8413 }
8414
8415 return true;
8416}
8417
8418//===--- CHECK: Scanf format string checking ------------------------------===//
8419
8420namespace {
8421
8422class CheckScanfHandler : public CheckFormatHandler {
8423public:
8424 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8425 const Expr *origFormatExpr, Sema::FormatStringType type,
8426 unsigned firstDataArg, unsigned numDataArgs,
8427 const char *beg, bool hasVAListArg,
8428 ArrayRef<const Expr *> Args, unsigned formatIdx,
8429 bool inFunctionCall, Sema::VariadicCallType CallType,
8430 llvm::SmallBitVector &CheckedVarArgs,
8431 UncoveredArgHandler &UncoveredArg)
8432 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8433 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8434 inFunctionCall, CallType, CheckedVarArgs,
8435 UncoveredArg) {}
8436
8437 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8438 const char *startSpecifier,
8439 unsigned specifierLen) override;
8440
8441 bool HandleInvalidScanfConversionSpecifier(
8442 const analyze_scanf::ScanfSpecifier &FS,
8443 const char *startSpecifier,
8444 unsigned specifierLen) override;
8445
8446 void HandleIncompleteScanList(const char *start, const char *end) override;
8447};
8448
8449} // namespace
8450
8451void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8452 const char *end) {
8453 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8454 getLocationOfByte(end), /*IsStringLocation*/true,
8455 getSpecifierRange(start, end - start));
8456}
8457
8458bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8459 const analyze_scanf::ScanfSpecifier &FS,
8460 const char *startSpecifier,
8461 unsigned specifierLen) {
8462 const analyze_scanf::ScanfConversionSpecifier &CS =
8463 FS.getConversionSpecifier();
8464
8465 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8466 getLocationOfByte(CS.getStart()),
8467 startSpecifier, specifierLen,
8468 CS.getStart(), CS.getLength());
8469}
8470
8471bool CheckScanfHandler::HandleScanfSpecifier(
8472 const analyze_scanf::ScanfSpecifier &FS,
8473 const char *startSpecifier,
8474 unsigned specifierLen) {
8475 using namespace analyze_scanf;
8476 using namespace analyze_format_string;
8477
8478 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8479
8480 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8481 // be used to decide if we are using positional arguments consistently.
8482 if (FS.consumesDataArgument()) {
8483 if (atFirstArg) {
8484 atFirstArg = false;
8485 usesPositionalArgs = FS.usesPositionalArg();
8486 }
8487 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8488 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8489 startSpecifier, specifierLen);
8490 return false;
8491 }
8492 }
8493
8494 // Check if the field with is non-zero.
8495 const OptionalAmount &Amt = FS.getFieldWidth();
8496 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8497 if (Amt.getConstantAmount() == 0) {
8498 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8499 Amt.getConstantLength());
8500 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8501 getLocationOfByte(Amt.getStart()),
8502 /*IsStringLocation*/true, R,
8503 FixItHint::CreateRemoval(R));
8504 }
8505 }
8506
8507 if (!FS.consumesDataArgument()) {
8508 // FIXME: Technically specifying a precision or field width here
8509 // makes no sense. Worth issuing a warning at some point.
8510 return true;
8511 }
8512
8513 // Consume the argument.
8514 unsigned argIndex = FS.getArgIndex();
8515 if (argIndex < NumDataArgs) {
8516 // The check to see if the argIndex is valid will come later.
8517 // We set the bit here because we may exit early from this
8518 // function if we encounter some other error.
8519 CoveredArgs.set(argIndex);
8520 }
8521
8522 // Check the length modifier is valid with the given conversion specifier.
8523 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8524 S.getLangOpts()))
8525 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8526 diag::warn_format_nonsensical_length);
8527 else if (!FS.hasStandardLengthModifier())
8528 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8529 else if (!FS.hasStandardLengthConversionCombination())
8530 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8531 diag::warn_format_non_standard_conversion_spec);
8532
8533 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8534 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8535
8536 // The remaining checks depend on the data arguments.
8537 if (HasVAListArg)
8538 return true;
8539
8540 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8541 return false;
8542
8543 // Check that the argument type matches the format specifier.
8544 const Expr *Ex = getDataArg(argIndex);
8545 if (!Ex)
8546 return true;
8547
8548 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8549
8550 if (!AT.isValid()) {
8551 return true;
8552 }
8553
8554 analyze_format_string::ArgType::MatchKind Match =
8555 AT.matchesType(S.Context, Ex->getType());
8556 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8557 if (Match == analyze_format_string::ArgType::Match)
8558 return true;
8559
8560 ScanfSpecifier fixedFS = FS;
8561 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8562 S.getLangOpts(), S.Context);
8563
8564 unsigned Diag =
8565 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8566 : diag::warn_format_conversion_argument_type_mismatch;
8567
8568 if (Success) {
8569 // Get the fix string from the fixed format specifier.
8570 SmallString<128> buf;
8571 llvm::raw_svector_ostream os(buf);
8572 fixedFS.toString(os);
8573
8574 EmitFormatDiagnostic(
8575 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8576 << Ex->getType() << false << Ex->getSourceRange(),
8577 Ex->getBeginLoc(),
8578 /*IsStringLocation*/ false,
8579 getSpecifierRange(startSpecifier, specifierLen),
8580 FixItHint::CreateReplacement(
8581 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8582 } else {
8583 EmitFormatDiagnostic(S.PDiag(Diag)
8584 << AT.getRepresentativeTypeName(S.Context)
8585 << Ex->getType() << false << Ex->getSourceRange(),
8586 Ex->getBeginLoc(),
8587 /*IsStringLocation*/ false,
8588 getSpecifierRange(startSpecifier, specifierLen));
8589 }
8590
8591 return true;
8592}
8593
8594static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8595 const Expr *OrigFormatExpr,
8596 ArrayRef<const Expr *> Args,
8597 bool HasVAListArg, unsigned format_idx,
8598 unsigned firstDataArg,
8599 Sema::FormatStringType Type,
8600 bool inFunctionCall,
8601 Sema::VariadicCallType CallType,
8602 llvm::SmallBitVector &CheckedVarArgs,
8603 UncoveredArgHandler &UncoveredArg,
8604 bool IgnoreStringsWithoutSpecifiers) {
8605 // CHECK: is the format string a wide literal?
8606 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8607 CheckFormatHandler::EmitFormatDiagnostic(
8608 S, inFunctionCall, Args[format_idx],
8609 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8610 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8611 return;
8612 }
8613
8614 // Str - The format string. NOTE: this is NOT null-terminated!
8615 StringRef StrRef = FExpr->getString();
8616 const char *Str = StrRef.data();
8617 // Account for cases where the string literal is truncated in a declaration.
8618 const ConstantArrayType *T =
8619 S.Context.getAsConstantArrayType(FExpr->getType());
8620 assert(T && "String literal not of constant array type!")((T && "String literal not of constant array type!") ?
static_cast<void> (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8620, __PRETTY_FUNCTION__))
;
8621 size_t TypeSize = T->getSize().getZExtValue();
8622 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8623 const unsigned numDataArgs = Args.size() - firstDataArg;
8624
8625 if (IgnoreStringsWithoutSpecifiers &&
8626 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8627 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8628 return;
8629
8630 // Emit a warning if the string literal is truncated and does not contain an
8631 // embedded null character.
8632 if (TypeSize <= StrRef.size() &&
8633 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8634 CheckFormatHandler::EmitFormatDiagnostic(
8635 S, inFunctionCall, Args[format_idx],
8636 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8637 FExpr->getBeginLoc(),
8638 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8639 return;
8640 }
8641
8642 // CHECK: empty format string?
8643 if (StrLen == 0 && numDataArgs > 0) {
8644 CheckFormatHandler::EmitFormatDiagnostic(
8645 S, inFunctionCall, Args[format_idx],
8646 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8647 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8648 return;
8649 }
8650
8651 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8652 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8653 Type == Sema::FST_OSTrace) {
8654 CheckPrintfHandler H(
8655 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8656 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8657 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8658 CheckedVarArgs, UncoveredArg);
8659
8660 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8661 S.getLangOpts(),
8662 S.Context.getTargetInfo(),
8663 Type == Sema::FST_FreeBSDKPrintf))
8664 H.DoneProcessing();
8665 } else if (Type == Sema::FST_Scanf) {
8666 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8667 numDataArgs, Str, HasVAListArg, Args, format_idx,
8668 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8669
8670 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8671 S.getLangOpts(),
8672 S.Context.getTargetInfo()))
8673 H.DoneProcessing();
8674 } // TODO: handle other formats
8675}
8676
8677bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8678 // Str - The format string. NOTE: this is NOT null-terminated!
8679 StringRef StrRef = FExpr->getString();
8680 const char *Str = StrRef.data();
8681 // Account for cases where the string literal is truncated in a declaration.
8682 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8683 assert(T && "String literal not of constant array type!")((T && "String literal not of constant array type!") ?
static_cast<void> (0) : __assert_fail ("T && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8683, __PRETTY_FUNCTION__))
;
8684 size_t TypeSize = T->getSize().getZExtValue();
8685 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8686 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8687 getLangOpts(),
8688 Context.getTargetInfo());
8689}
8690
8691//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8692
8693// Returns the related absolute value function that is larger, of 0 if one
8694// does not exist.
8695static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8696 switch (AbsFunction) {
8697 default:
8698 return 0;
8699
8700 case Builtin::BI__builtin_abs:
8701 return Builtin::BI__builtin_labs;
8702 case Builtin::BI__builtin_labs:
8703 return Builtin::BI__builtin_llabs;
8704 case Builtin::BI__builtin_llabs:
8705 return 0;
8706
8707 case Builtin::BI__builtin_fabsf:
8708 return Builtin::BI__builtin_fabs;
8709 case Builtin::BI__builtin_fabs:
8710 return Builtin::BI__builtin_fabsl;
8711 case Builtin::BI__builtin_fabsl:
8712 return 0;
8713
8714 case Builtin::BI__builtin_cabsf:
8715 return Builtin::BI__builtin_cabs;
8716 case Builtin::BI__builtin_cabs:
8717 return Builtin::BI__builtin_cabsl;
8718 case Builtin::BI__builtin_cabsl:
8719 return 0;
8720
8721 case Builtin::BIabs:
8722 return Builtin::BIlabs;
8723 case Builtin::BIlabs:
8724 return Builtin::BIllabs;
8725 case Builtin::BIllabs:
8726 return 0;
8727
8728 case Builtin::BIfabsf:
8729 return Builtin::BIfabs;
8730 case Builtin::BIfabs:
8731 return Builtin::BIfabsl;
8732 case Builtin::BIfabsl:
8733 return 0;
8734
8735 case Builtin::BIcabsf:
8736 return Builtin::BIcabs;
8737 case Builtin::BIcabs:
8738 return Builtin::BIcabsl;
8739 case Builtin::BIcabsl:
8740 return 0;
8741 }
8742}
8743
8744// Returns the argument type of the absolute value function.
8745static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8746 unsigned AbsType) {
8747 if (AbsType == 0)
8748 return QualType();
8749
8750 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8751 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8752 if (Error != ASTContext::GE_None)
8753 return QualType();
8754
8755 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8756 if (!FT)
8757 return QualType();
8758
8759 if (FT->getNumParams() != 1)
8760 return QualType();
8761
8762 return FT->getParamType(0);
8763}
8764
8765// Returns the best absolute value function, or zero, based on type and
8766// current absolute value function.
8767static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8768 unsigned AbsFunctionKind) {
8769 unsigned BestKind = 0;
8770 uint64_t ArgSize = Context.getTypeSize(ArgType);
8771 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8772 Kind = getLargerAbsoluteValueFunction(Kind)) {
8773 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8774 if (Context.getTypeSize(ParamType) >= ArgSize) {
8775 if (BestKind == 0)
8776 BestKind = Kind;
8777 else if (Context.hasSameType(ParamType, ArgType)) {
8778 BestKind = Kind;
8779 break;
8780 }
8781 }
8782 }
8783 return BestKind;
8784}
8785
8786enum AbsoluteValueKind {
8787 AVK_Integer,
8788 AVK_Floating,
8789 AVK_Complex
8790};
8791
8792static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8793 if (T->isIntegralOrEnumerationType())
8794 return AVK_Integer;
8795 if (T->isRealFloatingType())
8796 return AVK_Floating;
8797 if (T->isAnyComplexType())
8798 return AVK_Complex;
8799
8800 llvm_unreachable("Type not integer, floating, or complex")::llvm::llvm_unreachable_internal("Type not integer, floating, or complex"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8800)
;
8801}
8802
8803// Changes the absolute value function to a different type. Preserves whether
8804// the function is a builtin.
8805static unsigned changeAbsFunction(unsigned AbsKind,
8806 AbsoluteValueKind ValueKind) {
8807 switch (ValueKind) {
8808 case AVK_Integer:
8809 switch (AbsKind) {
8810 default:
8811 return 0;
8812 case Builtin::BI__builtin_fabsf:
8813 case Builtin::BI__builtin_fabs:
8814 case Builtin::BI__builtin_fabsl:
8815 case Builtin::BI__builtin_cabsf:
8816 case Builtin::BI__builtin_cabs:
8817 case Builtin::BI__builtin_cabsl:
8818 return Builtin::BI__builtin_abs;
8819 case Builtin::BIfabsf:
8820 case Builtin::BIfabs:
8821 case Builtin::BIfabsl:
8822 case Builtin::BIcabsf:
8823 case Builtin::BIcabs:
8824 case Builtin::BIcabsl:
8825 return Builtin::BIabs;
8826 }
8827 case AVK_Floating:
8828 switch (AbsKind) {
8829 default:
8830 return 0;
8831 case Builtin::BI__builtin_abs:
8832 case Builtin::BI__builtin_labs:
8833 case Builtin::BI__builtin_llabs:
8834 case Builtin::BI__builtin_cabsf:
8835 case Builtin::BI__builtin_cabs:
8836 case Builtin::BI__builtin_cabsl:
8837 return Builtin::BI__builtin_fabsf;
8838 case Builtin::BIabs:
8839 case Builtin::BIlabs:
8840 case Builtin::BIllabs:
8841 case Builtin::BIcabsf:
8842 case Builtin::BIcabs:
8843 case Builtin::BIcabsl:
8844 return Builtin::BIfabsf;
8845 }
8846 case AVK_Complex:
8847 switch (AbsKind) {
8848 default:
8849 return 0;
8850 case Builtin::BI__builtin_abs:
8851 case Builtin::BI__builtin_labs:
8852 case Builtin::BI__builtin_llabs:
8853 case Builtin::BI__builtin_fabsf:
8854 case Builtin::BI__builtin_fabs:
8855 case Builtin::BI__builtin_fabsl:
8856 return Builtin::BI__builtin_cabsf;
8857 case Builtin::BIabs:
8858 case Builtin::BIlabs:
8859 case Builtin::BIllabs:
8860 case Builtin::BIfabsf:
8861 case Builtin::BIfabs:
8862 case Builtin::BIfabsl:
8863 return Builtin::BIcabsf;
8864 }
8865 }
8866 llvm_unreachable("Unable to convert function")::llvm::llvm_unreachable_internal("Unable to convert function"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8866)
;
8867}
8868
8869static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8870 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8871 if (!FnInfo)
8872 return 0;
8873
8874 switch (FDecl->getBuiltinID()) {
8875 default:
8876 return 0;
8877 case Builtin::BI__builtin_abs:
8878 case Builtin::BI__builtin_fabs:
8879 case Builtin::BI__builtin_fabsf:
8880 case Builtin::BI__builtin_fabsl:
8881 case Builtin::BI__builtin_labs:
8882 case Builtin::BI__builtin_llabs:
8883 case Builtin::BI__builtin_cabs:
8884 case Builtin::BI__builtin_cabsf:
8885 case Builtin::BI__builtin_cabsl:
8886 case Builtin::BIabs:
8887 case Builtin::BIlabs:
8888 case Builtin::BIllabs:
8889 case Builtin::BIfabs:
8890 case Builtin::BIfabsf:
8891 case Builtin::BIfabsl:
8892 case Builtin::BIcabs:
8893 case Builtin::BIcabsf:
8894 case Builtin::BIcabsl:
8895 return FDecl->getBuiltinID();
8896 }
8897 llvm_unreachable("Unknown Builtin type")::llvm::llvm_unreachable_internal("Unknown Builtin type", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8897)
;
8898}
8899
8900// If the replacement is valid, emit a note with replacement function.
8901// Additionally, suggest including the proper header if not already included.
8902static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8903 unsigned AbsKind, QualType ArgType) {
8904 bool EmitHeaderHint = true;
8905 const char *HeaderName = nullptr;
8906 const char *FunctionName = nullptr;
8907 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8908 FunctionName = "std::abs";
8909 if (ArgType->isIntegralOrEnumerationType()) {
8910 HeaderName = "cstdlib";
8911 } else if (ArgType->isRealFloatingType()) {
8912 HeaderName = "cmath";
8913 } else {
8914 llvm_unreachable("Invalid Type")::llvm::llvm_unreachable_internal("Invalid Type", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 8914)
;
8915 }
8916
8917 // Lookup all std::abs
8918 if (NamespaceDecl *Std = S.getStdNamespace()) {
8919 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8920 R.suppressDiagnostics();
8921 S.LookupQualifiedName(R, Std);
8922
8923 for (const auto *I : R) {
8924 const FunctionDecl *FDecl = nullptr;
8925 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8926 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8927 } else {
8928 FDecl = dyn_cast<FunctionDecl>(I);
8929 }
8930 if (!FDecl)
8931 continue;
8932
8933 // Found std::abs(), check that they are the right ones.
8934 if (FDecl->getNumParams() != 1)
8935 continue;
8936
8937 // Check that the parameter type can handle the argument.
8938 QualType ParamType = FDecl->getParamDecl(0)->getType();
8939 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8940 S.Context.getTypeSize(ArgType) <=
8941 S.Context.getTypeSize(ParamType)) {
8942 // Found a function, don't need the header hint.
8943 EmitHeaderHint = false;
8944 break;
8945 }
8946 }
8947 }
8948 } else {
8949 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8950 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8951
8952 if (HeaderName) {
8953 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8954 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8955 R.suppressDiagnostics();
8956 S.LookupName(R, S.getCurScope());
8957
8958 if (R.isSingleResult()) {
8959 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8960 if (FD && FD->getBuiltinID() == AbsKind) {
8961 EmitHeaderHint = false;
8962 } else {
8963 return;
8964 }
8965 } else if (!R.empty()) {
8966 return;
8967 }
8968 }
8969 }
8970
8971 S.Diag(Loc, diag::note_replace_abs_function)
8972 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8973
8974 if (!HeaderName)
8975 return;
8976
8977 if (!EmitHeaderHint)
8978 return;
8979
8980 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8981 << FunctionName;
8982}
8983
8984template <std::size_t StrLen>
8985static bool IsStdFunction(const FunctionDecl *FDecl,
8986 const char (&Str)[StrLen]) {
8987 if (!FDecl)
8988 return false;
8989 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8990 return false;
8991 if (!FDecl->isInStdNamespace())
8992 return false;
8993
8994 return true;
8995}
8996
8997// Warn when using the wrong abs() function.
8998void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8999 const FunctionDecl *FDecl) {
9000 if (Call->getNumArgs() != 1)
9001 return;
9002
9003 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9004 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9005 if (AbsKind == 0 && !IsStdAbs)
9006 return;
9007
9008 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9009 QualType ParamType = Call->getArg(0)->getType();
9010
9011 // Unsigned types cannot be negative. Suggest removing the absolute value
9012 // function call.
9013 if (ArgType->isUnsignedIntegerType()) {
9014 const char *FunctionName =
9015 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9016 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9017 Diag(Call->getExprLoc(), diag::note_remove_abs)
9018 << FunctionName
9019 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9020 return;
9021 }
9022
9023 // Taking the absolute value of a pointer is very suspicious, they probably
9024 // wanted to index into an array, dereference a pointer, call a function, etc.
9025 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9026 unsigned DiagType = 0;
9027 if (ArgType->isFunctionType())
9028 DiagType = 1;
9029 else if (ArgType->isArrayType())
9030 DiagType = 2;
9031
9032 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9033 return;
9034 }
9035
9036 // std::abs has overloads which prevent most of the absolute value problems
9037 // from occurring.
9038 if (IsStdAbs)
9039 return;
9040
9041 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9042 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9043
9044 // The argument and parameter are the same kind. Check if they are the right
9045 // size.
9046 if (ArgValueKind == ParamValueKind) {
9047 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9048 return;
9049
9050 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9051 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9052 << FDecl << ArgType << ParamType;
9053
9054 if (NewAbsKind == 0)
9055 return;
9056
9057 emitReplacement(*this, Call->getExprLoc(),
9058 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9059 return;
9060 }
9061
9062 // ArgValueKind != ParamValueKind
9063 // The wrong type of absolute value function was used. Attempt to find the
9064 // proper one.
9065 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9066 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9067 if (NewAbsKind == 0)
9068 return;
9069
9070 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9071 << FDecl << ParamValueKind << ArgValueKind;
9072
9073 emitReplacement(*this, Call->getExprLoc(),
9074 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9075}
9076
9077//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9078void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9079 const FunctionDecl *FDecl) {
9080 if (!Call || !FDecl) return;
9081
9082 // Ignore template specializations and macros.
9083 if (inTemplateInstantiation()) return;
9084 if (Call->getExprLoc().isMacroID()) return;
9085
9086 // Only care about the one template argument, two function parameter std::max
9087 if (Call->getNumArgs() != 2) return;
9088 if (!IsStdFunction(FDecl, "max")) return;
9089 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9090 if (!ArgList) return;
9091 if (ArgList->size() != 1) return;
9092
9093 // Check that template type argument is unsigned integer.
9094 const auto& TA = ArgList->get(0);
9095 if (TA.getKind() != TemplateArgument::Type) return;
9096 QualType ArgType = TA.getAsType();
9097 if (!ArgType->isUnsignedIntegerType()) return;
9098
9099 // See if either argument is a literal zero.
9100 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9101 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9102 if (!MTE) return false;
9103 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
9104 if (!Num) return false;
9105 if (Num->getValue() != 0) return false;
9106 return true;
9107 };
9108
9109 const Expr *FirstArg = Call->getArg(0);
9110 const Expr *SecondArg = Call->getArg(1);
9111 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9112 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9113
9114 // Only warn when exactly one argument is zero.
9115 if (IsFirstArgZero == IsSecondArgZero) return;
9116
9117 SourceRange FirstRange = FirstArg->getSourceRange();
9118 SourceRange SecondRange = SecondArg->getSourceRange();
9119
9120 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9121
9122 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9123 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9124
9125 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9126 SourceRange RemovalRange;
9127 if (IsFirstArgZero) {
9128 RemovalRange = SourceRange(FirstRange.getBegin(),
9129 SecondRange.getBegin().getLocWithOffset(-1));
9130 } else {
9131 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9132 SecondRange.getEnd());
9133 }
9134
9135 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9136 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9137 << FixItHint::CreateRemoval(RemovalRange);
9138}
9139
9140//===--- CHECK: Standard memory functions ---------------------------------===//
9141
9142/// Takes the expression passed to the size_t parameter of functions
9143/// such as memcmp, strncat, etc and warns if it's a comparison.
9144///
9145/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9146static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9147 IdentifierInfo *FnName,
9148 SourceLocation FnLoc,
9149 SourceLocation RParenLoc) {
9150 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9151 if (!Size)
9152 return false;
9153
9154 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9155 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9156 return false;
9157
9158 SourceRange SizeRange = Size->getSourceRange();
9159 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9160 << SizeRange << FnName;
9161 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9162 << FnName
9163 << FixItHint::CreateInsertion(
9164 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9165 << FixItHint::CreateRemoval(RParenLoc);
9166 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9167 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9168 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9169 ")");
9170
9171 return true;
9172}
9173
9174/// Determine whether the given type is or contains a dynamic class type
9175/// (e.g., whether it has a vtable).
9176static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9177 bool &IsContained) {
9178 // Look through array types while ignoring qualifiers.
9179 const Type *Ty = T->getBaseElementTypeUnsafe();
9180 IsContained = false;
9181
9182 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9183 RD = RD ? RD->getDefinition() : nullptr;
9184 if (!RD || RD->isInvalidDecl())
9185 return nullptr;
9186
9187 if (RD->isDynamicClass())
9188 return RD;
9189
9190 // Check all the fields. If any bases were dynamic, the class is dynamic.
9191 // It's impossible for a class to transitively contain itself by value, so
9192 // infinite recursion is impossible.
9193 for (auto *FD : RD->fields()) {
9194 bool SubContained;
9195 if (const CXXRecordDecl *ContainedRD =
9196 getContainedDynamicClass(FD->getType(), SubContained)) {
9197 IsContained = true;
9198 return ContainedRD;
9199 }
9200 }
9201
9202 return nullptr;
9203}
9204
9205static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9206 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9207 if (Unary->getKind() == UETT_SizeOf)
9208 return Unary;
9209 return nullptr;
9210}
9211
9212/// If E is a sizeof expression, returns its argument expression,
9213/// otherwise returns NULL.
9214static const Expr *getSizeOfExprArg(const Expr *E) {
9215 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9216 if (!SizeOf->isArgumentType())
9217 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9218 return nullptr;
9219}
9220
9221/// If E is a sizeof expression, returns its argument type.
9222static QualType getSizeOfArgType(const Expr *E) {
9223 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9224 return SizeOf->getTypeOfArgument();
9225 return QualType();
9226}
9227
9228namespace {
9229
9230struct SearchNonTrivialToInitializeField
9231 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9232 using Super =
9233 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9234
9235 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9236
9237 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9238 SourceLocation SL) {
9239 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9240 asDerived().visitArray(PDIK, AT, SL);
9241 return;
9242 }
9243
9244 Super::visitWithKind(PDIK, FT, SL);
9245 }
9246
9247 void visitARCStrong(QualType FT, SourceLocation SL) {
9248 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9249 }
9250 void visitARCWeak(QualType FT, SourceLocation SL) {
9251 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9252 }
9253 void visitStruct(QualType FT, SourceLocation SL) {
9254 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9255 visit(FD->getType(), FD->getLocation());
9256 }
9257 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9258 const ArrayType *AT, SourceLocation SL) {
9259 visit(getContext().getBaseElementType(AT), SL);
9260 }
9261 void visitTrivial(QualType FT, SourceLocation SL) {}
9262
9263 static void diag(QualType RT, const Expr *E, Sema &S) {
9264 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9265 }
9266
9267 ASTContext &getContext() { return S.getASTContext(); }
9268
9269 const Expr *E;
9270 Sema &S;
9271};
9272
9273struct SearchNonTrivialToCopyField
9274 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9275 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9276
9277 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9278
9279 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9280 SourceLocation SL) {
9281 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9282 asDerived().visitArray(PCK, AT, SL);
9283 return;
9284 }
9285
9286 Super::visitWithKind(PCK, FT, SL);
9287 }
9288
9289 void visitARCStrong(QualType FT, SourceLocation SL) {
9290 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9291 }
9292 void visitARCWeak(QualType FT, SourceLocation SL) {
9293 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9294 }
9295 void visitStruct(QualType FT, SourceLocation SL) {
9296 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9297 visit(FD->getType(), FD->getLocation());
9298 }
9299 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9300 SourceLocation SL) {
9301 visit(getContext().getBaseElementType(AT), SL);
9302 }
9303 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9304 SourceLocation SL) {}
9305 void visitTrivial(QualType FT, SourceLocation SL) {}
9306 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9307
9308 static void diag(QualType RT, const Expr *E, Sema &S) {
9309 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9310 }
9311
9312 ASTContext &getContext() { return S.getASTContext(); }
9313
9314 const Expr *E;
9315 Sema &S;
9316};
9317
9318}
9319
9320/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9321static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9322 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9323
9324 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9325 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9326 return false;
9327
9328 return doesExprLikelyComputeSize(BO->getLHS()) ||
9329 doesExprLikelyComputeSize(BO->getRHS());
9330 }
9331
9332 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9333}
9334
9335/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9336///
9337/// \code
9338/// #define MACRO 0
9339/// foo(MACRO);
9340/// foo(0);
9341/// \endcode
9342///
9343/// This should return true for the first call to foo, but not for the second
9344/// (regardless of whether foo is a macro or function).
9345static bool isArgumentExpandedFromMacro(SourceManager &SM,
9346 SourceLocation CallLoc,
9347 SourceLocation ArgLoc) {
9348 if (!CallLoc.isMacroID())
9349 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9350
9351 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9352 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9353}
9354
9355/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9356/// last two arguments transposed.
9357static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9358 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9359 return;
9360
9361 const Expr *SizeArg =
9362 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9363
9364 auto isLiteralZero = [](const Expr *E) {
9365 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9366 };
9367
9368 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9369 SourceLocation CallLoc = Call->getRParenLoc();
9370 SourceManager &SM = S.getSourceManager();
9371 if (isLiteralZero(SizeArg) &&
9372 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9373
9374 SourceLocation DiagLoc = SizeArg->getExprLoc();
9375
9376 // Some platforms #define bzero to __builtin_memset. See if this is the
9377 // case, and if so, emit a better diagnostic.
9378 if (BId == Builtin::BIbzero ||
9379 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9380 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9381 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9382 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9383 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9384 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9385 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9386 }
9387 return;
9388 }
9389
9390 // If the second argument to a memset is a sizeof expression and the third
9391 // isn't, this is also likely an error. This should catch
9392 // 'memset(buf, sizeof(buf), 0xff)'.
9393 if (BId == Builtin::BImemset &&
9394 doesExprLikelyComputeSize(Call->getArg(1)) &&
9395 !doesExprLikelyComputeSize(Call->getArg(2))) {
9396 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9397 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9398 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9399 return;
9400 }
9401}
9402
9403/// Check for dangerous or invalid arguments to memset().
9404///
9405/// This issues warnings on known problematic, dangerous or unspecified
9406/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9407/// function calls.
9408///
9409/// \param Call The call expression to diagnose.
9410void Sema::CheckMemaccessArguments(const CallExpr *Call,
9411 unsigned BId,
9412 IdentifierInfo *FnName) {
9413 assert(BId != 0)((BId != 0) ? static_cast<void> (0) : __assert_fail ("BId != 0"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 9413, __PRETTY_FUNCTION__))
;
9414
9415 // It is possible to have a non-standard definition of memset. Validate
9416 // we have enough arguments, and if not, abort further checking.
9417 unsigned ExpectedNumArgs =
9418 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9419 if (Call->getNumArgs() < ExpectedNumArgs)
9420 return;
9421
9422 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9423 BId == Builtin::BIstrndup ? 1 : 2);
9424 unsigned LenArg =
9425 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9426 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9427
9428 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9429 Call->getBeginLoc(), Call->getRParenLoc()))
9430 return;
9431
9432 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9433 CheckMemaccessSize(*this, BId, Call);
9434
9435 // We have special checking when the length is a sizeof expression.
9436 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9437 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9438 llvm::FoldingSetNodeID SizeOfArgID;
9439
9440 // Although widely used, 'bzero' is not a standard function. Be more strict
9441 // with the argument types before allowing diagnostics and only allow the
9442 // form bzero(ptr, sizeof(...)).
9443 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9444 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9445 return;
9446
9447 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9448 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9449 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9450
9451 QualType DestTy = Dest->getType();
9452 QualType PointeeTy;
9453 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9454 PointeeTy = DestPtrTy->getPointeeType();
9455
9456 // Never warn about void type pointers. This can be used to suppress
9457 // false positives.
9458 if (PointeeTy->isVoidType())
9459 continue;
9460
9461 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9462 // actually comparing the expressions for equality. Because computing the
9463 // expression IDs can be expensive, we only do this if the diagnostic is
9464 // enabled.
9465 if (SizeOfArg &&
9466 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9467 SizeOfArg->getExprLoc())) {
9468 // We only compute IDs for expressions if the warning is enabled, and
9469 // cache the sizeof arg's ID.
9470 if (SizeOfArgID == llvm::FoldingSetNodeID())
9471 SizeOfArg->Profile(SizeOfArgID, Context, true);
9472 llvm::FoldingSetNodeID DestID;
9473 Dest->Profile(DestID, Context, true);
9474 if (DestID == SizeOfArgID) {
9475 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9476 // over sizeof(src) as well.
9477 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9478 StringRef ReadableName = FnName->getName();
9479
9480 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9481 if (UnaryOp->getOpcode() == UO_AddrOf)
9482 ActionIdx = 1; // If its an address-of operator, just remove it.
9483 if (!PointeeTy->isIncompleteType() &&
9484 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9485 ActionIdx = 2; // If the pointee's size is sizeof(char),
9486 // suggest an explicit length.
9487
9488 // If the function is defined as a builtin macro, do not show macro
9489 // expansion.
9490 SourceLocation SL = SizeOfArg->getExprLoc();
9491 SourceRange DSR = Dest->getSourceRange();
9492 SourceRange SSR = SizeOfArg->getSourceRange();
9493 SourceManager &SM = getSourceManager();
9494
9495 if (SM.isMacroArgExpansion(SL)) {
9496 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9497 SL = SM.getSpellingLoc(SL);
9498 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9499 SM.getSpellingLoc(DSR.getEnd()));
9500 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9501 SM.getSpellingLoc(SSR.getEnd()));
9502 }
9503
9504 DiagRuntimeBehavior(SL, SizeOfArg,
9505 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9506 << ReadableName
9507 << PointeeTy
9508 << DestTy
9509 << DSR
9510 << SSR);
9511 DiagRuntimeBehavior(SL, SizeOfArg,
9512 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9513 << ActionIdx
9514 << SSR);
9515
9516 break;
9517 }
9518 }
9519
9520 // Also check for cases where the sizeof argument is the exact same
9521 // type as the memory argument, and where it points to a user-defined
9522 // record type.
9523 if (SizeOfArgTy != QualType()) {
9524 if (PointeeTy->isRecordType() &&
9525 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9526 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9527 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9528 << FnName << SizeOfArgTy << ArgIdx
9529 << PointeeTy << Dest->getSourceRange()
9530 << LenExpr->getSourceRange());
9531 break;
9532 }
9533 }
9534 } else if (DestTy->isArrayType()) {
9535 PointeeTy = DestTy;
9536 }
9537
9538 if (PointeeTy == QualType())
9539 continue;
9540
9541 // Always complain about dynamic classes.
9542 bool IsContained;
9543 if (const CXXRecordDecl *ContainedRD =
9544 getContainedDynamicClass(PointeeTy, IsContained)) {
9545
9546 unsigned OperationType = 0;
9547 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9548 // "overwritten" if we're warning about the destination for any call
9549 // but memcmp; otherwise a verb appropriate to the call.
9550 if (ArgIdx != 0 || IsCmp) {
9551 if (BId == Builtin::BImemcpy)
9552 OperationType = 1;
9553 else if(BId == Builtin::BImemmove)
9554 OperationType = 2;
9555 else if (IsCmp)
9556 OperationType = 3;
9557 }
9558
9559 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9560 PDiag(diag::warn_dyn_class_memaccess)
9561 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9562 << IsContained << ContainedRD << OperationType
9563 << Call->getCallee()->getSourceRange());
9564 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9565 BId != Builtin::BImemset)
9566 DiagRuntimeBehavior(
9567 Dest->getExprLoc(), Dest,
9568 PDiag(diag::warn_arc_object_memaccess)
9569 << ArgIdx << FnName << PointeeTy
9570 << Call->getCallee()->getSourceRange());
9571 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9572 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9573 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9574 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9575 PDiag(diag::warn_cstruct_memaccess)
9576 << ArgIdx << FnName << PointeeTy << 0);
9577 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9578 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9579 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9580 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9581 PDiag(diag::warn_cstruct_memaccess)
9582 << ArgIdx << FnName << PointeeTy << 1);
9583 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9584 } else {
9585 continue;
9586 }
9587 } else
9588 continue;
9589
9590 DiagRuntimeBehavior(
9591 Dest->getExprLoc(), Dest,
9592 PDiag(diag::note_bad_memaccess_silence)
9593 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9594 break;
9595 }
9596}
9597
9598// A little helper routine: ignore addition and subtraction of integer literals.
9599// This intentionally does not ignore all integer constant expressions because
9600// we don't want to remove sizeof().
9601static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9602 Ex = Ex->IgnoreParenCasts();
9603
9604 while (true) {
9605 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9606 if (!BO || !BO->isAdditiveOp())
9607 break;
9608
9609 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9610 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9611
9612 if (isa<IntegerLiteral>(RHS))
9613 Ex = LHS;
9614 else if (isa<IntegerLiteral>(LHS))
9615 Ex = RHS;
9616 else
9617 break;
9618 }
9619
9620 return Ex;
9621}
9622
9623static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9624 ASTContext &Context) {
9625 // Only handle constant-sized or VLAs, but not flexible members.
9626 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9627 // Only issue the FIXIT for arrays of size > 1.
9628 if (CAT->getSize().getSExtValue() <= 1)
9629 return false;
9630 } else if (!Ty->isVariableArrayType()) {
9631 return false;
9632 }
9633 return true;
9634}
9635
9636// Warn if the user has made the 'size' argument to strlcpy or strlcat
9637// be the size of the source, instead of the destination.
9638void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9639 IdentifierInfo *FnName) {
9640
9641 // Don't crash if the user has the wrong number of arguments
9642 unsigned NumArgs = Call->getNumArgs();
9643 if ((NumArgs != 3) && (NumArgs != 4))
9644 return;
9645
9646 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9647 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9648 const Expr *CompareWithSrc = nullptr;
9649
9650 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9651 Call->getBeginLoc(), Call->getRParenLoc()))
9652 return;
9653
9654 // Look for 'strlcpy(dst, x, sizeof(x))'
9655 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9656 CompareWithSrc = Ex;
9657 else {
9658 // Look for 'strlcpy(dst, x, strlen(x))'
9659 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9660 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9661 SizeCall->getNumArgs() == 1)
9662 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9663 }
9664 }
9665
9666 if (!CompareWithSrc)
9667 return;
9668
9669 // Determine if the argument to sizeof/strlen is equal to the source
9670 // argument. In principle there's all kinds of things you could do
9671 // here, for instance creating an == expression and evaluating it with
9672 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9673 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9674 if (!SrcArgDRE)
9675 return;
9676
9677 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9678 if (!CompareWithSrcDRE ||
9679 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9680 return;
9681
9682 const Expr *OriginalSizeArg = Call->getArg(2);
9683 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9684 << OriginalSizeArg->getSourceRange() << FnName;
9685
9686 // Output a FIXIT hint if the destination is an array (rather than a
9687 // pointer to an array). This could be enhanced to handle some
9688 // pointers if we know the actual size, like if DstArg is 'array+2'
9689 // we could say 'sizeof(array)-2'.
9690 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9691 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9692 return;
9693
9694 SmallString<128> sizeString;
9695 llvm::raw_svector_ostream OS(sizeString);
9696 OS << "sizeof(";
9697 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9698 OS << ")";
9699
9700 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9701 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9702 OS.str());
9703}
9704
9705/// Check if two expressions refer to the same declaration.
9706static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9707 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9708 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9709 return D1->getDecl() == D2->getDecl();
9710 return false;
9711}
9712
9713static const Expr *getStrlenExprArg(const Expr *E) {
9714 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9715 const FunctionDecl *FD = CE->getDirectCallee();
9716 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9717 return nullptr;
9718 return CE->getArg(0)->IgnoreParenCasts();
9719 }
9720 return nullptr;
9721}
9722
9723// Warn on anti-patterns as the 'size' argument to strncat.
9724// The correct size argument should look like following:
9725// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9726void Sema::CheckStrncatArguments(const CallExpr *CE,
9727 IdentifierInfo *FnName) {
9728 // Don't crash if the user has the wrong number of arguments.
9729 if (CE->getNumArgs() < 3)
9730 return;
9731 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9732 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9733 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9734
9735 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9736 CE->getRParenLoc()))
9737 return;
9738
9739 // Identify common expressions, which are wrongly used as the size argument
9740 // to strncat and may lead to buffer overflows.
9741 unsigned PatternType = 0;
9742 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9743 // - sizeof(dst)
9744 if (referToTheSameDecl(SizeOfArg, DstArg))
9745 PatternType = 1;
9746 // - sizeof(src)
9747 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9748 PatternType = 2;
9749 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9750 if (BE->getOpcode() == BO_Sub) {
9751 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9752 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9753 // - sizeof(dst) - strlen(dst)
9754 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9755 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9756 PatternType = 1;
9757 // - sizeof(src) - (anything)
9758 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9759 PatternType = 2;
9760 }
9761 }
9762
9763 if (PatternType == 0)
9764 return;
9765
9766 // Generate the diagnostic.
9767 SourceLocation SL = LenArg->getBeginLoc();
9768 SourceRange SR = LenArg->getSourceRange();
9769 SourceManager &SM = getSourceManager();
9770
9771 // If the function is defined as a builtin macro, do not show macro expansion.
9772 if (SM.isMacroArgExpansion(SL)) {
9773 SL = SM.getSpellingLoc(SL);
9774 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9775 SM.getSpellingLoc(SR.getEnd()));
9776 }
9777
9778 // Check if the destination is an array (rather than a pointer to an array).
9779 QualType DstTy = DstArg->getType();
9780 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9781 Context);
9782 if (!isKnownSizeArray) {
9783 if (PatternType == 1)
9784 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9785 else
9786 Diag(SL, diag::warn_strncat_src_size) << SR;
9787 return;
9788 }
9789
9790 if (PatternType == 1)
9791 Diag(SL, diag::warn_strncat_large_size) << SR;
9792 else
9793 Diag(SL, diag::warn_strncat_src_size) << SR;
9794
9795 SmallString<128> sizeString;
9796 llvm::raw_svector_ostream OS(sizeString);
9797 OS << "sizeof(";
9798 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9799 OS << ") - ";
9800 OS << "strlen(";
9801 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9802 OS << ") - 1";
9803
9804 Diag(SL, diag::note_strncat_wrong_size)
9805 << FixItHint::CreateReplacement(SR, OS.str());
9806}
9807
9808void
9809Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9810 SourceLocation ReturnLoc,
9811 bool isObjCMethod,
9812 const AttrVec *Attrs,
9813 const FunctionDecl *FD) {
9814 // Check if the return value is null but should not be.
9815 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9816 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9817 CheckNonNullExpr(*this, RetValExp))
9818 Diag(ReturnLoc, diag::warn_null_ret)
9819 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9820
9821 // C++11 [basic.stc.dynamic.allocation]p4:
9822 // If an allocation function declared with a non-throwing
9823 // exception-specification fails to allocate storage, it shall return
9824 // a null pointer. Any other allocation function that fails to allocate
9825 // storage shall indicate failure only by throwing an exception [...]
9826 if (FD) {
9827 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9828 if (Op == OO_New || Op == OO_Array_New) {
9829 const FunctionProtoType *Proto
9830 = FD->getType()->castAs<FunctionProtoType>();
9831 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9832 CheckNonNullExpr(*this, RetValExp))
9833 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9834 << FD << getLangOpts().CPlusPlus11;
9835 }
9836 }
9837}
9838
9839//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9840
9841/// Check for comparisons of floating point operands using != and ==.
9842/// Issue a warning if these are no self-comparisons, as they are not likely
9843/// to do what the programmer intended.
9844void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9845 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9846 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9847
9848 // Special case: check for x == x (which is OK).
9849 // Do not emit warnings for such cases.
9850 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9851 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9852 if (DRL->getDecl() == DRR->getDecl())
9853 return;
9854
9855 // Special case: check for comparisons against literals that can be exactly
9856 // represented by APFloat. In such cases, do not emit a warning. This
9857 // is a heuristic: often comparison against such literals are used to
9858 // detect if a value in a variable has not changed. This clearly can
9859 // lead to false negatives.
9860 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9861 if (FLL->isExact())
9862 return;
9863 } else
9864 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9865 if (FLR->isExact())
9866 return;
9867
9868 // Check for comparisons with builtin types.
9869 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9870 if (CL->getBuiltinCallee())
9871 return;
9872
9873 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9874 if (CR->getBuiltinCallee())
9875 return;
9876
9877 // Emit the diagnostic.
9878 Diag(Loc, diag::warn_floatingpoint_eq)
9879 << LHS->getSourceRange() << RHS->getSourceRange();
9880}
9881
9882//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9883//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9884
9885namespace {
9886
9887/// Structure recording the 'active' range of an integer-valued
9888/// expression.
9889struct IntRange {
9890 /// The number of bits active in the int.
9891 unsigned Width;
9892
9893 /// True if the int is known not to have negative values.
9894 bool NonNegative;
9895
9896 IntRange(unsigned Width, bool NonNegative)
9897 : Width(Width), NonNegative(NonNegative) {}
9898
9899 /// Returns the range of the bool type.
9900 static IntRange forBoolType() {
9901 return IntRange(1, true);
9902 }
9903
9904 /// Returns the range of an opaque value of the given integral type.
9905 static IntRange forValueOfType(ASTContext &C, QualType T) {
9906 return forValueOfCanonicalType(C,
9907 T->getCanonicalTypeInternal().getTypePtr());
9908 }
9909
9910 /// Returns the range of an opaque value of a canonical integral type.
9911 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9912 assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> (
0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 9912, __PRETTY_FUNCTION__))
;
9913
9914 if (const VectorType *VT = dyn_cast<VectorType>(T))
9915 T = VT->getElementType().getTypePtr();
9916 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9917 T = CT->getElementType().getTypePtr();
9918 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9919 T = AT->getValueType().getTypePtr();
9920
9921 if (!C.getLangOpts().CPlusPlus) {
9922 // For enum types in C code, use the underlying datatype.
9923 if (const EnumType *ET = dyn_cast<EnumType>(T))
9924 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9925 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9926 // For enum types in C++, use the known bit width of the enumerators.
9927 EnumDecl *Enum = ET->getDecl();
9928 // In C++11, enums can have a fixed underlying type. Use this type to
9929 // compute the range.
9930 if (Enum->isFixed()) {
9931 return IntRange(C.getIntWidth(QualType(T, 0)),
9932 !ET->isSignedIntegerOrEnumerationType());
9933 }
9934
9935 unsigned NumPositive = Enum->getNumPositiveBits();
9936 unsigned NumNegative = Enum->getNumNegativeBits();
9937
9938 if (NumNegative == 0)
9939 return IntRange(NumPositive, true/*NonNegative*/);
9940 else
9941 return IntRange(std::max(NumPositive + 1, NumNegative),
9942 false/*NonNegative*/);
9943 }
9944
9945 const BuiltinType *BT = cast<BuiltinType>(T);
9946 assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail
("BT->isInteger()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 9946, __PRETTY_FUNCTION__))
;
9947
9948 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9949 }
9950
9951 /// Returns the "target" range of a canonical integral type, i.e.
9952 /// the range of values expressible in the type.
9953 ///
9954 /// This matches forValueOfCanonicalType except that enums have the
9955 /// full range of their type, not the range of their enumerators.
9956 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9957 assert(T->isCanonicalUnqualified())((T->isCanonicalUnqualified()) ? static_cast<void> (
0) : __assert_fail ("T->isCanonicalUnqualified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 9957, __PRETTY_FUNCTION__))
;
9958
9959 if (const VectorType *VT = dyn_cast<VectorType>(T))
9960 T = VT->getElementType().getTypePtr();
9961 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9962 T = CT->getElementType().getTypePtr();
9963 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9964 T = AT->getValueType().getTypePtr();
9965 if (const EnumType *ET = dyn_cast<EnumType>(T))
9966 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9967
9968 const BuiltinType *BT = cast<BuiltinType>(T);
9969 assert(BT->isInteger())((BT->isInteger()) ? static_cast<void> (0) : __assert_fail
("BT->isInteger()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 9969, __PRETTY_FUNCTION__))
;
9970
9971 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9972 }
9973
9974 /// Returns the supremum of two ranges: i.e. their conservative merge.
9975 static IntRange join(IntRange L, IntRange R) {
9976 return IntRange(std::max(L.Width, R.Width),
9977 L.NonNegative && R.NonNegative);
9978 }
9979
9980 /// Returns the infinum of two ranges: i.e. their aggressive merge.
9981 static IntRange meet(IntRange L, IntRange R) {
9982 return IntRange(std::min(L.Width, R.Width),
9983 L.NonNegative || R.NonNegative);
9984 }
9985};
9986
9987} // namespace
9988
9989static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9990 unsigned MaxWidth) {
9991 if (value.isSigned() && value.isNegative())
9992 return IntRange(value.getMinSignedBits(), false);
9993
9994 if (value.getBitWidth() > MaxWidth)
9995 value = value.trunc(MaxWidth);
9996
9997 // isNonNegative() just checks the sign bit without considering
9998 // signedness.
9999 return IntRange(value.getActiveBits(), true);
10000}
10001
10002static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10003 unsigned MaxWidth) {
10004 if (result.isInt())
10005 return GetValueRange(C, result.getInt(), MaxWidth);
10006
10007 if (result.isVector()) {
10008 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10009 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10010 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10011 R = IntRange::join(R, El);
10012 }
10013 return R;
10014 }
10015
10016 if (result.isComplexInt()) {
10017 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10018 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10019 return IntRange::join(R, I);
10020 }
10021
10022 // This can happen with lossless casts to intptr_t of "based" lvalues.
10023 // Assume it might use arbitrary bits.
10024 // FIXME: The only reason we need to pass the type in here is to get
10025 // the sign right on this one case. It would be nice if APValue
10026 // preserved this.
10027 assert(result.isLValue() || result.isAddrLabelDiff())((result.isLValue() || result.isAddrLabelDiff()) ? static_cast
<void> (0) : __assert_fail ("result.isLValue() || result.isAddrLabelDiff()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10027, __PRETTY_FUNCTION__))
;
10028 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10029}
10030
10031static QualType GetExprType(const Expr *E) {
10032 QualType Ty = E->getType();
10033 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10034 Ty = AtomicRHS->getValueType();
10035 return Ty;
10036}
10037
10038/// Pseudo-evaluate the given integer expression, estimating the
10039/// range of values it might take.
10040///
10041/// \param MaxWidth - the width to which the value will be truncated
10042static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10043 bool InConstantContext) {
10044 E = E->IgnoreParens();
10045
10046 // Try a full evaluation first.
10047 Expr::EvalResult result;
10048 if (E->EvaluateAsRValue(result, C, InConstantContext))
10049 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10050
10051 // I think we only want to look through implicit casts here; if the
10052 // user has an explicit widening cast, we should treat the value as
10053 // being of the new, wider type.
10054 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10055 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10056 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10057
10058 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10059
10060 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10061 CE->getCastKind() == CK_BooleanToSignedIntegral;
10062
10063 // Assume that non-integer casts can span the full range of the type.
10064 if (!isIntegerCast)
10065 return OutputTypeRange;
10066
10067 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10068 std::min(MaxWidth, OutputTypeRange.Width),
10069 InConstantContext);
10070
10071 // Bail out if the subexpr's range is as wide as the cast type.
10072 if (SubRange.Width >= OutputTypeRange.Width)
10073 return OutputTypeRange;
10074
10075 // Otherwise, we take the smaller width, and we're non-negative if
10076 // either the output type or the subexpr is.
10077 return IntRange(SubRange.Width,
10078 SubRange.NonNegative || OutputTypeRange.NonNegative);
10079 }
10080
10081 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10082 // If we can fold the condition, just take that operand.
10083 bool CondResult;
10084 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10085 return GetExprRange(C,
10086 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10087 MaxWidth, InConstantContext);
10088
10089 // Otherwise, conservatively merge.
10090 IntRange L =
10091 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10092 IntRange R =
10093 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10094 return IntRange::join(L, R);
10095 }
10096
10097 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10098 switch (BO->getOpcode()) {
10099 case BO_Cmp:
10100 llvm_unreachable("builtin <=> should have class type")::llvm::llvm_unreachable_internal("builtin <=> should have class type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10100)
;
10101
10102 // Boolean-valued operations are single-bit and positive.
10103 case BO_LAnd:
10104 case BO_LOr:
10105 case BO_LT:
10106 case BO_GT:
10107 case BO_LE:
10108 case BO_GE:
10109 case BO_EQ:
10110 case BO_NE:
10111 return IntRange::forBoolType();
10112
10113 // The type of the assignments is the type of the LHS, so the RHS
10114 // is not necessarily the same type.
10115 case BO_MulAssign:
10116 case BO_DivAssign:
10117 case BO_RemAssign:
10118 case BO_AddAssign:
10119 case BO_SubAssign:
10120 case BO_XorAssign:
10121 case BO_OrAssign:
10122 // TODO: bitfields?
10123 return IntRange::forValueOfType(C, GetExprType(E));
10124
10125 // Simple assignments just pass through the RHS, which will have
10126 // been coerced to the LHS type.
10127 case BO_Assign:
10128 // TODO: bitfields?
10129 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10130
10131 // Operations with opaque sources are black-listed.
10132 case BO_PtrMemD:
10133 case BO_PtrMemI:
10134 return IntRange::forValueOfType(C, GetExprType(E));
10135
10136 // Bitwise-and uses the *infinum* of the two source ranges.
10137 case BO_And:
10138 case BO_AndAssign:
10139 return IntRange::meet(
10140 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10141 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10142
10143 // Left shift gets black-listed based on a judgement call.
10144 case BO_Shl:
10145 // ...except that we want to treat '1 << (blah)' as logically
10146 // positive. It's an important idiom.
10147 if (IntegerLiteral *I
10148 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10149 if (I->getValue() == 1) {
10150 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10151 return IntRange(R.Width, /*NonNegative*/ true);
10152 }
10153 }
10154 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10155
10156 case BO_ShlAssign:
10157 return IntRange::forValueOfType(C, GetExprType(E));
10158
10159 // Right shift by a constant can narrow its left argument.
10160 case BO_Shr:
10161 case BO_ShrAssign: {
10162 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10163
10164 // If the shift amount is a positive constant, drop the width by
10165 // that much.
10166 llvm::APSInt shift;
10167 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10168 shift.isNonNegative()) {
10169 unsigned zext = shift.getZExtValue();
10170 if (zext >= L.Width)
10171 L.Width = (L.NonNegative ? 0 : 1);
10172 else
10173 L.Width -= zext;
10174 }
10175
10176 return L;
10177 }
10178
10179 // Comma acts as its right operand.
10180 case BO_Comma:
10181 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10182
10183 // Black-list pointer subtractions.
10184 case BO_Sub:
10185 if (BO->getLHS()->getType()->isPointerType())
10186 return IntRange::forValueOfType(C, GetExprType(E));
10187 break;
10188
10189 // The width of a division result is mostly determined by the size
10190 // of the LHS.
10191 case BO_Div: {
10192 // Don't 'pre-truncate' the operands.
10193 unsigned opWidth = C.getIntWidth(GetExprType(E));
10194 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10195
10196 // If the divisor is constant, use that.
10197 llvm::APSInt divisor;
10198 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10199 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10200 if (log2 >= L.Width)
10201 L.Width = (L.NonNegative ? 0 : 1);
10202 else
10203 L.Width = std::min(L.Width - log2, MaxWidth);
10204 return L;
10205 }
10206
10207 // Otherwise, just use the LHS's width.
10208 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10209 return IntRange(L.Width, L.NonNegative && R.NonNegative);
10210 }
10211
10212 // The result of a remainder can't be larger than the result of
10213 // either side.
10214 case BO_Rem: {
10215 // Don't 'pre-truncate' the operands.
10216 unsigned opWidth = C.getIntWidth(GetExprType(E));
10217 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10218 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10219
10220 IntRange meet = IntRange::meet(L, R);
10221 meet.Width = std::min(meet.Width, MaxWidth);
10222 return meet;
10223 }
10224
10225 // The default behavior is okay for these.
10226 case BO_Mul:
10227 case BO_Add:
10228 case BO_Xor:
10229 case BO_Or:
10230 break;
10231 }
10232
10233 // The default case is to treat the operation as if it were closed
10234 // on the narrowest type that encompasses both operands.
10235 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10236 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10237 return IntRange::join(L, R);
10238 }
10239
10240 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10241 switch (UO->getOpcode()) {
10242 // Boolean-valued operations are white-listed.
10243 case UO_LNot:
10244 return IntRange::forBoolType();
10245
10246 // Operations with opaque sources are black-listed.
10247 case UO_Deref:
10248 case UO_AddrOf: // should be impossible
10249 return IntRange::forValueOfType(C, GetExprType(E));
10250
10251 default:
10252 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10253 }
10254 }
10255
10256 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10257 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10258
10259 if (const auto *BitField = E->getSourceBitField())
10260 return IntRange(BitField->getBitWidthValue(C),
10261 BitField->getType()->isUnsignedIntegerOrEnumerationType());
10262
10263 return IntRange::forValueOfType(C, GetExprType(E));
10264}
10265
10266static IntRange GetExprRange(ASTContext &C, const Expr *E,
10267 bool InConstantContext) {
10268 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10269}
10270
10271/// Checks whether the given value, which currently has the given
10272/// source semantics, has the same value when coerced through the
10273/// target semantics.
10274static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10275 const llvm::fltSemantics &Src,
10276 const llvm::fltSemantics &Tgt) {
10277 llvm::APFloat truncated = value;
10278
10279 bool ignored;
10280 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10281 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10282
10283 return truncated.bitwiseIsEqual(value);
10284}
10285
10286/// Checks whether the given value, which currently has the given
10287/// source semantics, has the same value when coerced through the
10288/// target semantics.
10289///
10290/// The value might be a vector of floats (or a complex number).
10291static bool IsSameFloatAfterCast(const APValue &value,
10292 const llvm::fltSemantics &Src,
10293 const llvm::fltSemantics &Tgt) {
10294 if (value.isFloat())
10295 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10296
10297 if (value.isVector()) {
10298 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10299 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10300 return false;
10301 return true;
10302 }
10303
10304 assert(value.isComplexFloat())((value.isComplexFloat()) ? static_cast<void> (0) : __assert_fail
("value.isComplexFloat()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10304, __PRETTY_FUNCTION__))
;
10305 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10306 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10307}
10308
10309static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10310 bool IsListInit = false);
10311
10312static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10313 // Suppress cases where we are comparing against an enum constant.
10314 if (const DeclRefExpr *DR =
10315 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10316 if (isa<EnumConstantDecl>(DR->getDecl()))
10317 return true;
10318
10319 // Suppress cases where the value is expanded from a macro, unless that macro
10320 // is how a language represents a boolean literal. This is the case in both C
10321 // and Objective-C.
10322 SourceLocation BeginLoc = E->getBeginLoc();
10323 if (BeginLoc.isMacroID()) {
10324 StringRef MacroName = Lexer::getImmediateMacroName(
10325 BeginLoc, S.getSourceManager(), S.getLangOpts());
10326 return MacroName != "YES" && MacroName != "NO" &&
10327 MacroName != "true" && MacroName != "false";
10328 }
10329
10330 return false;
10331}
10332
10333static bool isKnownToHaveUnsignedValue(Expr *E) {
10334 return E->getType()->isIntegerType() &&
10335 (!E->getType()->isSignedIntegerType() ||
10336 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10337}
10338
10339namespace {
10340/// The promoted range of values of a type. In general this has the
10341/// following structure:
10342///
10343/// |-----------| . . . |-----------|
10344/// ^ ^ ^ ^
10345/// Min HoleMin HoleMax Max
10346///
10347/// ... where there is only a hole if a signed type is promoted to unsigned
10348/// (in which case Min and Max are the smallest and largest representable
10349/// values).
10350struct PromotedRange {
10351 // Min, or HoleMax if there is a hole.
10352 llvm::APSInt PromotedMin;
10353 // Max, or HoleMin if there is a hole.
10354 llvm::APSInt PromotedMax;
10355
10356 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10357 if (R.Width == 0)
10358 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10359 else if (R.Width >= BitWidth && !Unsigned) {
10360 // Promotion made the type *narrower*. This happens when promoting
10361 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10362 // Treat all values of 'signed int' as being in range for now.
10363 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10364 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10365 } else {
10366 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10367 .extOrTrunc(BitWidth);
10368 PromotedMin.setIsUnsigned(Unsigned);
10369
10370 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10371 .extOrTrunc(BitWidth);
10372 PromotedMax.setIsUnsigned(Unsigned);
10373 }
10374 }
10375
10376 // Determine whether this range is contiguous (has no hole).
10377 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10378
10379 // Where a constant value is within the range.
10380 enum ComparisonResult {
10381 LT = 0x1,
10382 LE = 0x2,
10383 GT = 0x4,
10384 GE = 0x8,
10385 EQ = 0x10,
10386 NE = 0x20,
10387 InRangeFlag = 0x40,
10388
10389 Less = LE | LT | NE,
10390 Min = LE | InRangeFlag,
10391 InRange = InRangeFlag,
10392 Max = GE | InRangeFlag,
10393 Greater = GE | GT | NE,
10394
10395 OnlyValue = LE | GE | EQ | InRangeFlag,
10396 InHole = NE
10397 };
10398
10399 ComparisonResult compare(const llvm::APSInt &Value) const {
10400 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&((Value.getBitWidth() == PromotedMin.getBitWidth() &&
Value.isUnsigned() == PromotedMin.isUnsigned()) ? static_cast
<void> (0) : __assert_fail ("Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10401, __PRETTY_FUNCTION__))
10401 Value.isUnsigned() == PromotedMin.isUnsigned())((Value.getBitWidth() == PromotedMin.getBitWidth() &&
Value.isUnsigned() == PromotedMin.isUnsigned()) ? static_cast
<void> (0) : __assert_fail ("Value.getBitWidth() == PromotedMin.getBitWidth() && Value.isUnsigned() == PromotedMin.isUnsigned()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10401, __PRETTY_FUNCTION__))
;
10402 if (!isContiguous()) {
10403 assert(Value.isUnsigned() && "discontiguous range for signed compare")((Value.isUnsigned() && "discontiguous range for signed compare"
) ? static_cast<void> (0) : __assert_fail ("Value.isUnsigned() && \"discontiguous range for signed compare\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10403, __PRETTY_FUNCTION__))
;
10404 if (Value.isMinValue()) return Min;
10405 if (Value.isMaxValue()) return Max;
10406 if (Value >= PromotedMin) return InRange;
10407 if (Value <= PromotedMax) return InRange;
10408 return InHole;
10409 }
10410
10411 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10412 case -1: return Less;
10413 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10414 case 1:
10415 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10416 case -1: return InRange;
10417 case 0: return Max;
10418 case 1: return Greater;
10419 }
10420 }
10421
10422 llvm_unreachable("impossible compare result")::llvm::llvm_unreachable_internal("impossible compare result"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10422)
;
10423 }
10424
10425 static llvm::Optional<StringRef>
10426 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10427 if (Op == BO_Cmp) {
10428 ComparisonResult LTFlag = LT, GTFlag = GT;
10429 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10430
10431 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10432 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10433 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10434 return llvm::None;
10435 }
10436
10437 ComparisonResult TrueFlag, FalseFlag;
10438 if (Op == BO_EQ) {
10439 TrueFlag = EQ;
10440 FalseFlag = NE;
10441 } else if (Op == BO_NE) {
10442 TrueFlag = NE;
10443 FalseFlag = EQ;
10444 } else {
10445 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10446 TrueFlag = LT;
10447 FalseFlag = GE;
10448 } else {
10449 TrueFlag = GT;
10450 FalseFlag = LE;
10451 }
10452 if (Op == BO_GE || Op == BO_LE)
10453 std::swap(TrueFlag, FalseFlag);
10454 }
10455 if (R & TrueFlag)
10456 return StringRef("true");
10457 if (R & FalseFlag)
10458 return StringRef("false");
10459 return llvm::None;
10460 }
10461};
10462}
10463
10464static bool HasEnumType(Expr *E) {
10465 // Strip off implicit integral promotions.
10466 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10467 if (ICE->getCastKind() != CK_IntegralCast &&
10468 ICE->getCastKind() != CK_NoOp)
10469 break;
10470 E = ICE->getSubExpr();
10471 }
10472
10473 return E->getType()->isEnumeralType();
10474}
10475
10476static int classifyConstantValue(Expr *Constant) {
10477 // The values of this enumeration are used in the diagnostics
10478 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10479 enum ConstantValueKind {
10480 Miscellaneous = 0,
10481 LiteralTrue,
10482 LiteralFalse
10483 };
10484 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10485 return BL->getValue() ? ConstantValueKind::LiteralTrue
10486 : ConstantValueKind::LiteralFalse;
10487 return ConstantValueKind::Miscellaneous;
10488}
10489
10490static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10491 Expr *Constant, Expr *Other,
10492 const llvm::APSInt &Value,
10493 bool RhsConstant) {
10494 if (S.inTemplateInstantiation())
10495 return false;
10496
10497 Expr *OriginalOther = Other;
10498
10499 Constant = Constant->IgnoreParenImpCasts();
10500 Other = Other->IgnoreParenImpCasts();
10501
10502 // Suppress warnings on tautological comparisons between values of the same
10503 // enumeration type. There are only two ways we could warn on this:
10504 // - If the constant is outside the range of representable values of
10505 // the enumeration. In such a case, we should warn about the cast
10506 // to enumeration type, not about the comparison.
10507 // - If the constant is the maximum / minimum in-range value. For an
10508 // enumeratin type, such comparisons can be meaningful and useful.
10509 if (Constant->getType()->isEnumeralType() &&
10510 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10511 return false;
10512
10513 // TODO: Investigate using GetExprRange() to get tighter bounds
10514 // on the bit ranges.
10515 QualType OtherT = Other->getType();
10516 if (const auto *AT = OtherT->getAs<AtomicType>())
10517 OtherT = AT->getValueType();
10518 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10519
10520 // Special case for ObjC BOOL on targets where its a typedef for a signed char
10521 // (Namely, macOS).
10522 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10523 S.NSAPIObj->isObjCBOOLType(OtherT) &&
10524 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10525
10526 // Whether we're treating Other as being a bool because of the form of
10527 // expression despite it having another type (typically 'int' in C).
10528 bool OtherIsBooleanDespiteType =
10529 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10530 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10531 OtherRange = IntRange::forBoolType();
10532
10533 // Determine the promoted range of the other type and see if a comparison of
10534 // the constant against that range is tautological.
10535 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10536 Value.isUnsigned());
10537 auto Cmp = OtherPromotedRange.compare(Value);
10538 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10539 if (!Result)
10540 return false;
10541
10542 // Suppress the diagnostic for an in-range comparison if the constant comes
10543 // from a macro or enumerator. We don't want to diagnose
10544 //
10545 // some_long_value <= INT_MAX
10546 //
10547 // when sizeof(int) == sizeof(long).
10548 bool InRange = Cmp & PromotedRange::InRangeFlag;
10549 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10550 return false;
10551
10552 // If this is a comparison to an enum constant, include that
10553 // constant in the diagnostic.
10554 const EnumConstantDecl *ED = nullptr;
10555 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10556 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10557
10558 // Should be enough for uint128 (39 decimal digits)
10559 SmallString<64> PrettySourceValue;
10560 llvm::raw_svector_ostream OS(PrettySourceValue);
10561 if (ED) {
10562 OS << '\'' << *ED << "' (" << Value << ")";
10563 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10564 Constant->IgnoreParenImpCasts())) {
10565 OS << (BL->getValue() ? "YES" : "NO");
10566 } else {
10567 OS << Value;
10568 }
10569
10570 if (IsObjCSignedCharBool) {
10571 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10572 S.PDiag(diag::warn_tautological_compare_objc_bool)
10573 << OS.str() << *Result);
10574 return true;
10575 }
10576
10577 // FIXME: We use a somewhat different formatting for the in-range cases and
10578 // cases involving boolean values for historical reasons. We should pick a
10579 // consistent way of presenting these diagnostics.
10580 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10581
10582 S.DiagRuntimeBehavior(
10583 E->getOperatorLoc(), E,
10584 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10585 : diag::warn_tautological_bool_compare)
10586 << OS.str() << classifyConstantValue(Constant) << OtherT
10587 << OtherIsBooleanDespiteType << *Result
10588 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10589 } else {
10590 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10591 ? (HasEnumType(OriginalOther)
10592 ? diag::warn_unsigned_enum_always_true_comparison
10593 : diag::warn_unsigned_always_true_comparison)
10594 : diag::warn_tautological_constant_compare;
10595
10596 S.Diag(E->getOperatorLoc(), Diag)
10597 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10598 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10599 }
10600
10601 return true;
10602}
10603
10604/// Analyze the operands of the given comparison. Implements the
10605/// fallback case from AnalyzeComparison.
10606static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10607 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10608 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10609}
10610
10611/// Implements -Wsign-compare.
10612///
10613/// \param E the binary operator to check for warnings
10614static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10615 // The type the comparison is being performed in.
10616 QualType T = E->getLHS()->getType();
10617
10618 // Only analyze comparison operators where both sides have been converted to
10619 // the same type.
10620 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10621 return AnalyzeImpConvsInComparison(S, E);
10622
10623 // Don't analyze value-dependent comparisons directly.
10624 if (E->isValueDependent())
10625 return AnalyzeImpConvsInComparison(S, E);
10626
10627 Expr *LHS = E->getLHS();
10628 Expr *RHS = E->getRHS();
10629
10630 if (T->isIntegralType(S.Context)) {
10631 llvm::APSInt RHSValue;
10632 llvm::APSInt LHSValue;
10633
10634 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10635 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10636
10637 // We don't care about expressions whose result is a constant.
10638 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10639 return AnalyzeImpConvsInComparison(S, E);
10640
10641 // We only care about expressions where just one side is literal
10642 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10643 // Is the constant on the RHS or LHS?
10644 const bool RhsConstant = IsRHSIntegralLiteral;
10645 Expr *Const = RhsConstant ? RHS : LHS;
10646 Expr *Other = RhsConstant ? LHS : RHS;
10647 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10648
10649 // Check whether an integer constant comparison results in a value
10650 // of 'true' or 'false'.
10651 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10652 return AnalyzeImpConvsInComparison(S, E);
10653 }
10654 }
10655
10656 if (!T->hasUnsignedIntegerRepresentation()) {
10657 // We don't do anything special if this isn't an unsigned integral
10658 // comparison: we're only interested in integral comparisons, and
10659 // signed comparisons only happen in cases we don't care to warn about.
10660 return AnalyzeImpConvsInComparison(S, E);
10661 }
10662
10663 LHS = LHS->IgnoreParenImpCasts();
10664 RHS = RHS->IgnoreParenImpCasts();
10665
10666 if (!S.getLangOpts().CPlusPlus) {
10667 // Avoid warning about comparison of integers with different signs when
10668 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10669 // the type of `E`.
10670 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10671 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10672 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10673 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10674 }
10675
10676 // Check to see if one of the (unmodified) operands is of different
10677 // signedness.
10678 Expr *signedOperand, *unsignedOperand;
10679 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10680 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&((!RHS->getType()->hasSignedIntegerRepresentation() &&
"unsigned comparison between two signed integer expressions?"
) ? static_cast<void> (0) : __assert_fail ("!RHS->getType()->hasSignedIntegerRepresentation() && \"unsigned comparison between two signed integer expressions?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10681, __PRETTY_FUNCTION__))
10681 "unsigned comparison between two signed integer expressions?")((!RHS->getType()->hasSignedIntegerRepresentation() &&
"unsigned comparison between two signed integer expressions?"
) ? static_cast<void> (0) : __assert_fail ("!RHS->getType()->hasSignedIntegerRepresentation() && \"unsigned comparison between two signed integer expressions?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10681, __PRETTY_FUNCTION__))
;
10682 signedOperand = LHS;
10683 unsignedOperand = RHS;
10684 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10685 signedOperand = RHS;
10686 unsignedOperand = LHS;
10687 } else {
10688 return AnalyzeImpConvsInComparison(S, E);
10689 }
10690
10691 // Otherwise, calculate the effective range of the signed operand.
10692 IntRange signedRange =
10693 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10694
10695 // Go ahead and analyze implicit conversions in the operands. Note
10696 // that we skip the implicit conversions on both sides.
10697 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10698 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10699
10700 // If the signed range is non-negative, -Wsign-compare won't fire.
10701 if (signedRange.NonNegative)
10702 return;
10703
10704 // For (in)equality comparisons, if the unsigned operand is a
10705 // constant which cannot collide with a overflowed signed operand,
10706 // then reinterpreting the signed operand as unsigned will not
10707 // change the result of the comparison.
10708 if (E->isEqualityOp()) {
10709 unsigned comparisonWidth = S.Context.getIntWidth(T);
10710 IntRange unsignedRange =
10711 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10712
10713 // We should never be unable to prove that the unsigned operand is
10714 // non-negative.
10715 assert(unsignedRange.NonNegative && "unsigned range includes negative?")((unsignedRange.NonNegative && "unsigned range includes negative?"
) ? static_cast<void> (0) : __assert_fail ("unsignedRange.NonNegative && \"unsigned range includes negative?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10715, __PRETTY_FUNCTION__))
;
10716
10717 if (unsignedRange.Width < comparisonWidth)
10718 return;
10719 }
10720
10721 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10722 S.PDiag(diag::warn_mixed_sign_comparison)
10723 << LHS->getType() << RHS->getType()
10724 << LHS->getSourceRange() << RHS->getSourceRange());
10725}
10726
10727/// Analyzes an attempt to assign the given value to a bitfield.
10728///
10729/// Returns true if there was something fishy about the attempt.
10730static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10731 SourceLocation InitLoc) {
10732 assert(Bitfield->isBitField())((Bitfield->isBitField()) ? static_cast<void> (0) : __assert_fail
("Bitfield->isBitField()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 10732, __PRETTY_FUNCTION__))
;
10733 if (Bitfield->isInvalidDecl())
10734 return false;
10735
10736 // White-list bool bitfields.
10737 QualType BitfieldType = Bitfield->getType();
10738 if (BitfieldType->isBooleanType())
10739 return false;
10740
10741 if (BitfieldType->isEnumeralType()) {
10742 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10743 // If the underlying enum type was not explicitly specified as an unsigned
10744 // type and the enum contain only positive values, MSVC++ will cause an
10745 // inconsistency by storing this as a signed type.
10746 if (S.getLangOpts().CPlusPlus11 &&
10747 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10748 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10749 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10750 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10751 << BitfieldEnumDecl->getNameAsString();
10752 }
10753 }
10754
10755 if (Bitfield->getType()->isBooleanType())
10756 return false;
10757
10758 // Ignore value- or type-dependent expressions.
10759 if (Bitfield->getBitWidth()->isValueDependent() ||
10760 Bitfield->getBitWidth()->isTypeDependent() ||
10761 Init->isValueDependent() ||
10762 Init->isTypeDependent())
10763 return false;
10764
10765 Expr *OriginalInit = Init->IgnoreParenImpCasts();
10766 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10767
10768 Expr::EvalResult Result;
10769 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10770 Expr::SE_AllowSideEffects)) {
10771 // The RHS is not constant. If the RHS has an enum type, make sure the
10772 // bitfield is wide enough to hold all the values of the enum without
10773 // truncation.
10774 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10775 EnumDecl *ED = EnumTy->getDecl();
10776 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10777
10778 // Enum types are implicitly signed on Windows, so check if there are any
10779 // negative enumerators to see if the enum was intended to be signed or
10780 // not.
10781 bool SignedEnum = ED->getNumNegativeBits() > 0;
10782
10783 // Check for surprising sign changes when assigning enum values to a
10784 // bitfield of different signedness. If the bitfield is signed and we
10785 // have exactly the right number of bits to store this unsigned enum,
10786 // suggest changing the enum to an unsigned type. This typically happens
10787 // on Windows where unfixed enums always use an underlying type of 'int'.
10788 unsigned DiagID = 0;
10789 if (SignedEnum && !SignedBitfield) {
10790 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10791 } else if (SignedBitfield && !SignedEnum &&
10792 ED->getNumPositiveBits() == FieldWidth) {
10793 DiagID = diag::warn_signed_bitfield_enum_conversion;
10794 }
10795
10796 if (DiagID) {
10797 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10798 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10799 SourceRange TypeRange =
10800 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10801 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10802 << SignedEnum << TypeRange;
10803 }
10804
10805 // Compute the required bitwidth. If the enum has negative values, we need
10806 // one more bit than the normal number of positive bits to represent the
10807 // sign bit.
10808 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10809 ED->getNumNegativeBits())
10810 : ED->getNumPositiveBits();
10811
10812 // Check the bitwidth.
10813 if (BitsNeeded > FieldWidth) {
10814 Expr *WidthExpr = Bitfield->getBitWidth();
10815 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10816 << Bitfield << ED;
10817 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10818 << BitsNeeded << ED << WidthExpr->getSourceRange();
10819 }
10820 }
10821
10822 return false;
10823 }
10824
10825 llvm::APSInt Value = Result.Val.getInt();
10826
10827 unsigned OriginalWidth = Value.getBitWidth();
10828
10829 if (!Value.isSigned() || Value.isNegative())
10830 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10831 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10832 OriginalWidth = Value.getMinSignedBits();
10833
10834 if (OriginalWidth <= FieldWidth)
10835 return false;
10836
10837 // Compute the value which the bitfield will contain.
10838 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10839 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10840
10841 // Check whether the stored value is equal to the original value.
10842 TruncatedValue = TruncatedValue.extend(OriginalWidth);
10843 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10844 return false;
10845
10846 // Special-case bitfields of width 1: booleans are naturally 0/1, and
10847 // therefore don't strictly fit into a signed bitfield of width 1.
10848 if (FieldWidth == 1 && Value == 1)
10849 return false;
10850
10851 std::string PrettyValue = Value.toString(10);
10852 std::string PrettyTrunc = TruncatedValue.toString(10);
10853
10854 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10855 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10856 << Init->getSourceRange();
10857
10858 return true;
10859}
10860
10861/// Analyze the given simple or compound assignment for warning-worthy
10862/// operations.
10863static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10864 // Just recurse on the LHS.
10865 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10866
10867 // We want to recurse on the RHS as normal unless we're assigning to
10868 // a bitfield.
10869 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10870 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10871 E->getOperatorLoc())) {
10872 // Recurse, ignoring any implicit conversions on the RHS.
10873 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10874 E->getOperatorLoc());
10875 }
10876 }
10877
10878 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10879
10880 // Diagnose implicitly sequentially-consistent atomic assignment.
10881 if (E->getLHS()->getType()->isAtomicType())
10882 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10883}
10884
10885/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10886static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10887 SourceLocation CContext, unsigned diag,
10888 bool pruneControlFlow = false) {
10889 if (pruneControlFlow) {
10890 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10891 S.PDiag(diag)
10892 << SourceType << T << E->getSourceRange()
10893 << SourceRange(CContext));
10894 return;
10895 }
10896 S.Diag(E->getExprLoc(), diag)
10897 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10898}
10899
10900/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
10901static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10902 SourceLocation CContext,
10903 unsigned diag, bool pruneControlFlow = false) {
10904 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10905}
10906
10907static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10908 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10909 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10910}
10911
10912static void adornObjCBoolConversionDiagWithTernaryFixit(
10913 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10914 Expr *Ignored = SourceExpr->IgnoreImplicit();
10915 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10916 Ignored = OVE->getSourceExpr();
10917 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10918 isa<BinaryOperator>(Ignored) ||
10919 isa<CXXOperatorCallExpr>(Ignored);
10920 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10921 if (NeedsParens)
10922 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10923 << FixItHint::CreateInsertion(EndLoc, ")");
10924 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10925}
10926
10927/// Diagnose an implicit cast from a floating point value to an integer value.
10928static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10929 SourceLocation CContext) {
10930 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10931 const bool PruneWarnings = S.inTemplateInstantiation();
10932
10933 Expr *InnerE = E->IgnoreParenImpCasts();
10934 // We also want to warn on, e.g., "int i = -1.234"
10935 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10936 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10937 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10938
10939 const bool IsLiteral =
10940 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10941
10942 llvm::APFloat Value(0.0);
10943 bool IsConstant =
10944 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10945 if (!IsConstant) {
10946 if (isObjCSignedCharBool(S, T)) {
10947 return adornObjCBoolConversionDiagWithTernaryFixit(
10948 S, E,
10949 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10950 << E->getType());
10951 }
10952
10953 return DiagnoseImpCast(S, E, T, CContext,
10954 diag::warn_impcast_float_integer, PruneWarnings);
10955 }
10956
10957 bool isExact = false;
10958
10959 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10960 T->hasUnsignedIntegerRepresentation());
10961 llvm::APFloat::opStatus Result = Value.convertToInteger(
10962 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10963
10964 // FIXME: Force the precision of the source value down so we don't print
10965 // digits which are usually useless (we don't really care here if we
10966 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10967 // would automatically print the shortest representation, but it's a bit
10968 // tricky to implement.
10969 SmallString<16> PrettySourceValue;
10970 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10971 precision = (precision * 59 + 195) / 196;
10972 Value.toString(PrettySourceValue, precision);
10973
10974 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10975 return adornObjCBoolConversionDiagWithTernaryFixit(
10976 S, E,
10977 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10978 << PrettySourceValue);
10979 }
10980
10981 if (Result == llvm::APFloat::opOK && isExact) {
10982 if (IsLiteral) return;
10983 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10984 PruneWarnings);
10985 }
10986
10987 // Conversion of a floating-point value to a non-bool integer where the
10988 // integral part cannot be represented by the integer type is undefined.
10989 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10990 return DiagnoseImpCast(
10991 S, E, T, CContext,
10992 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10993 : diag::warn_impcast_float_to_integer_out_of_range,
10994 PruneWarnings);
10995
10996 unsigned DiagID = 0;
10997 if (IsLiteral) {
10998 // Warn on floating point literal to integer.
10999 DiagID = diag::warn_impcast_literal_float_to_integer;
11000 } else if (IntegerValue == 0) {
11001 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11002 return DiagnoseImpCast(S, E, T, CContext,
11003 diag::warn_impcast_float_integer, PruneWarnings);
11004 }
11005 // Warn on non-zero to zero conversion.
11006 DiagID = diag::warn_impcast_float_to_integer_zero;
11007 } else {
11008 if (IntegerValue.isUnsigned()) {
11009 if (!IntegerValue.isMaxValue()) {
11010 return DiagnoseImpCast(S, E, T, CContext,
11011 diag::warn_impcast_float_integer, PruneWarnings);
11012 }
11013 } else { // IntegerValue.isSigned()
11014 if (!IntegerValue.isMaxSignedValue() &&
11015 !IntegerValue.isMinSignedValue()) {
11016 return DiagnoseImpCast(S, E, T, CContext,
11017 diag::warn_impcast_float_integer, PruneWarnings);
11018 }
11019 }
11020 // Warn on evaluatable floating point expression to integer conversion.
11021 DiagID = diag::warn_impcast_float_to_integer;
11022 }
11023
11024 SmallString<16> PrettyTargetValue;
11025 if (IsBool)
11026 PrettyTargetValue = Value.isZero() ? "false" : "true";
11027 else
11028 IntegerValue.toString(PrettyTargetValue);
11029
11030 if (PruneWarnings) {
11031 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11032 S.PDiag(DiagID)
11033 << E->getType() << T.getUnqualifiedType()
11034 << PrettySourceValue << PrettyTargetValue
11035 << E->getSourceRange() << SourceRange(CContext));
11036 } else {
11037 S.Diag(E->getExprLoc(), DiagID)
11038 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11039 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11040 }
11041}
11042
11043/// Analyze the given compound assignment for the possible losing of
11044/// floating-point precision.
11045static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11046 assert(isa<CompoundAssignOperator>(E) &&((isa<CompoundAssignOperator>(E) && "Must be compound assignment operation"
) ? static_cast<void> (0) : __assert_fail ("isa<CompoundAssignOperator>(E) && \"Must be compound assignment operation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 11047, __PRETTY_FUNCTION__))
11047 "Must be compound assignment operation")((isa<CompoundAssignOperator>(E) && "Must be compound assignment operation"
) ? static_cast<void> (0) : __assert_fail ("isa<CompoundAssignOperator>(E) && \"Must be compound assignment operation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 11047, __PRETTY_FUNCTION__))
;
11048 // Recurse on the LHS and RHS in here
11049 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11050 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11051
11052 if (E->getLHS()->getType()->isAtomicType())
11053 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11054
11055 // Now check the outermost expression
11056 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11057 const auto *RBT = cast<CompoundAssignOperator>(E)
11058 ->getComputationResultType()
11059 ->getAs<BuiltinType>();
11060
11061 // The below checks assume source is floating point.
11062 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11063
11064 // If source is floating point but target is an integer.
11065 if (ResultBT->isInteger())
11066 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11067 E->getExprLoc(), diag::warn_impcast_float_integer);
11068
11069 if (!ResultBT->isFloatingPoint())
11070 return;
11071
11072 // If both source and target are floating points, warn about losing precision.
11073 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11074 QualType(ResultBT, 0), QualType(RBT, 0));
11075 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11076 // warn about dropping FP rank.
11077 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11078 diag::warn_impcast_float_result_precision);
11079}
11080
11081static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11082 IntRange Range) {
11083 if (!Range.Width) return "0";
11084
11085 llvm::APSInt ValueInRange = Value;
11086 ValueInRange.setIsSigned(!Range.NonNegative);
11087 ValueInRange = ValueInRange.trunc(Range.Width);
11088 return ValueInRange.toString(10);
11089}
11090
11091static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11092 if (!isa<ImplicitCastExpr>(Ex))
11093 return false;
11094
11095 Expr *InnerE = Ex->IgnoreParenImpCasts();
11096 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11097 const Type *Source =
11098 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11099 if (Target->isDependentType())
11100 return false;
11101
11102 const BuiltinType *FloatCandidateBT =
11103 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11104 const Type *BoolCandidateType = ToBool ? Target : Source;
11105
11106 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11107 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11108}
11109
11110static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11111 SourceLocation CC) {
11112 unsigned NumArgs = TheCall->getNumArgs();
11113 for (unsigned i = 0; i < NumArgs; ++i) {
11114 Expr *CurrA = TheCall->getArg(i);
11115 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11116 continue;
11117
11118 bool IsSwapped = ((i > 0) &&
11119 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11120 IsSwapped |= ((i < (NumArgs - 1)) &&
11121 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11122 if (IsSwapped) {
11123 // Warn on this floating-point to bool conversion.
11124 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11125 CurrA->getType(), CC,
11126 diag::warn_impcast_floating_point_to_bool);
11127 }
11128 }
11129}
11130
11131static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11132 SourceLocation CC) {
11133 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11134 E->getExprLoc()))
11135 return;
11136
11137 // Don't warn on functions which have return type nullptr_t.
11138 if (isa<CallExpr>(E))
11139 return;
11140
11141 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11142 const Expr::NullPointerConstantKind NullKind =
11143 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11144 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11145 return;
11146
11147 // Return if target type is a safe conversion.
11148 if (T->isAnyPointerType() || T->isBlockPointerType() ||
11149 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11150 return;
11151
11152 SourceLocation Loc = E->getSourceRange().getBegin();
11153
11154 // Venture through the macro stacks to get to the source of macro arguments.
11155 // The new location is a better location than the complete location that was
11156 // passed in.
11157 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11158 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11159
11160 // __null is usually wrapped in a macro. Go up a macro if that is the case.
11161 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11162 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11163 Loc, S.SourceMgr, S.getLangOpts());
11164 if (MacroName == "NULL")
11165 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11166 }
11167
11168 // Only warn if the null and context location are in the same macro expansion.
11169 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11170 return;
11171
11172 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11173 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11174 << FixItHint::CreateReplacement(Loc,
11175 S.getFixItZeroLiteralForType(T, Loc));
11176}
11177
11178static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11179 ObjCArrayLiteral *ArrayLiteral);
11180
11181static void
11182checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11183 ObjCDictionaryLiteral *DictionaryLiteral);
11184
11185/// Check a single element within a collection literal against the
11186/// target element type.
11187static void checkObjCCollectionLiteralElement(Sema &S,
11188 QualType TargetElementType,
11189 Expr *Element,
11190 unsigned ElementKind) {
11191 // Skip a bitcast to 'id' or qualified 'id'.
11192 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11193 if (ICE->getCastKind() == CK_BitCast &&
11194 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11195 Element = ICE->getSubExpr();
11196 }
11197
11198 QualType ElementType = Element->getType();
11199 ExprResult ElementResult(Element);
11200 if (ElementType->getAs<ObjCObjectPointerType>() &&
11201 S.CheckSingleAssignmentConstraints(TargetElementType,
11202 ElementResult,
11203 false, false)
11204 != Sema::Compatible) {
11205 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11206 << ElementType << ElementKind << TargetElementType
11207 << Element->getSourceRange();
11208 }
11209
11210 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11211 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11212 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11213 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11214}
11215
11216/// Check an Objective-C array literal being converted to the given
11217/// target type.
11218static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11219 ObjCArrayLiteral *ArrayLiteral) {
11220 if (!S.NSArrayDecl)
11221 return;
11222
11223 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11224 if (!TargetObjCPtr)
11225 return;
11226
11227 if (TargetObjCPtr->isUnspecialized() ||
11228 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11229 != S.NSArrayDecl->getCanonicalDecl())
11230 return;
11231
11232 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11233 if (TypeArgs.size() != 1)
11234 return;
11235
11236 QualType TargetElementType = TypeArgs[0];
11237 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11238 checkObjCCollectionLiteralElement(S, TargetElementType,
11239 ArrayLiteral->getElement(I),
11240 0);
11241 }
11242}
11243
11244/// Check an Objective-C dictionary literal being converted to the given
11245/// target type.
11246static void
11247checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11248 ObjCDictionaryLiteral *DictionaryLiteral) {
11249 if (!S.NSDictionaryDecl)
11250 return;
11251
11252 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11253 if (!TargetObjCPtr)
11254 return;
11255
11256 if (TargetObjCPtr->isUnspecialized() ||
11257 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11258 != S.NSDictionaryDecl->getCanonicalDecl())
11259 return;
11260
11261 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11262 if (TypeArgs.size() != 2)
11263 return;
11264
11265 QualType TargetKeyType = TypeArgs[0];
11266 QualType TargetObjectType = TypeArgs[1];
11267 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11268 auto Element = DictionaryLiteral->getKeyValueElement(I);
11269 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11270 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11271 }
11272}
11273
11274// Helper function to filter out cases for constant width constant conversion.
11275// Don't warn on char array initialization or for non-decimal values.
11276static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11277 SourceLocation CC) {
11278 // If initializing from a constant, and the constant starts with '0',
11279 // then it is a binary, octal, or hexadecimal. Allow these constants
11280 // to fill all the bits, even if there is a sign change.
11281 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11282 const char FirstLiteralCharacter =
11283 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11284 if (FirstLiteralCharacter == '0')
11285 return false;
11286 }
11287
11288 // If the CC location points to a '{', and the type is char, then assume
11289 // assume it is an array initialization.
11290 if (CC.isValid() && T->isCharType()) {
11291 const char FirstContextCharacter =
11292 S.getSourceManager().getCharacterData(CC)[0];
11293 if (FirstContextCharacter == '{')
11294 return false;
11295 }
11296
11297 return true;
11298}
11299
11300static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11301 const auto *IL = dyn_cast<IntegerLiteral>(E);
11302 if (!IL) {
11303 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11304 if (UO->getOpcode() == UO_Minus)
11305 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11306 }
11307 }
11308
11309 return IL;
11310}
11311
11312static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11313 Expr *LHS, Expr *RHS) {
11314 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11315 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11316
11317 const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11318 if (!LHSEnumType)
11319 return;
11320 const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11321 if (!RHSEnumType)
11322 return;
11323
11324 // Ignore anonymous enums.
11325 if (!LHSEnumType->getDecl()->hasNameForLinkage())
11326 return;
11327 if (!RHSEnumType->getDecl()->hasNameForLinkage())
11328 return;
11329
11330 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11331 return;
11332
11333 S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11334 << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11335 << RHS->getSourceRange();
11336}
11337
11338static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11339 E = E->IgnoreParenImpCasts();
11340 SourceLocation ExprLoc = E->getExprLoc();
11341
11342 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11343 BinaryOperator::Opcode Opc = BO->getOpcode();
11344 Expr::EvalResult Result;
11345 // Do not diagnose unsigned shifts.
11346 if (Opc == BO_Shl) {
11347 const auto *LHS = getIntegerLiteral(BO->getLHS());
11348 const auto *RHS = getIntegerLiteral(BO->getRHS());
11349 if (LHS && LHS->getValue() == 0)
11350 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11351 else if (!E->isValueDependent() && LHS && RHS &&
11352 RHS->getValue().isNonNegative() &&
11353 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11354 S.Diag(ExprLoc, diag::warn_left_shift_always)
11355 << (Result.Val.getInt() != 0);
11356 else if (E->getType()->isSignedIntegerType())
11357 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11358 }
11359 }
11360
11361 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11362 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11363 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11364 if (!LHS || !RHS)
11365 return;
11366 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11367 (RHS->getValue() == 0 || RHS->getValue() == 1))
11368 // Do not diagnose common idioms.
11369 return;
11370 if (LHS->getValue() != 0 && LHS->getValue() != 0)
11371 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11372 }
11373}
11374
11375static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11376 SourceLocation CC,
11377 bool *ICContext = nullptr,
11378 bool IsListInit = false) {
11379 if (E->isTypeDependent() || E->isValueDependent()) return;
11380
11381 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11382 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11383 if (Source == Target) return;
11384 if (Target->isDependentType()) return;
11385
11386 // If the conversion context location is invalid don't complain. We also
11387 // don't want to emit a warning if the issue occurs from the expansion of
11388 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11389 // delay this check as long as possible. Once we detect we are in that
11390 // scenario, we just return.
11391 if (CC.isInvalid())
11392 return;
11393
11394 if (Source->isAtomicType())
11395 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11396
11397 // Diagnose implicit casts to bool.
11398 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11399 if (isa<StringLiteral>(E))
11400 // Warn on string literal to bool. Checks for string literals in logical
11401 // and expressions, for instance, assert(0 && "error here"), are
11402 // prevented by a check in AnalyzeImplicitConversions().
11403 return DiagnoseImpCast(S, E, T, CC,
11404 diag::warn_impcast_string_literal_to_bool);
11405 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11406 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11407 // This covers the literal expressions that evaluate to Objective-C
11408 // objects.
11409 return DiagnoseImpCast(S, E, T, CC,
11410 diag::warn_impcast_objective_c_literal_to_bool);
11411 }
11412 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11413 // Warn on pointer to bool conversion that is always true.
11414 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11415 SourceRange(CC));
11416 }
11417 }
11418
11419 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11420 // is a typedef for signed char (macOS), then that constant value has to be 1
11421 // or 0.
11422 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11423 Expr::EvalResult Result;
11424 if (E->EvaluateAsInt(Result, S.getASTContext(),
11425 Expr::SE_AllowSideEffects)) {
11426 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11427 adornObjCBoolConversionDiagWithTernaryFixit(
11428 S, E,
11429 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11430 << Result.Val.getInt().toString(10));
11431 }
11432 return;
11433 }
11434 }
11435
11436 // Check implicit casts from Objective-C collection literals to specialized
11437 // collection types, e.g., NSArray<NSString *> *.
11438 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11439 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11440 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11441 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11442
11443 // Strip vector types.
11444 if (isa<VectorType>(Source)) {
11445 if (!isa<VectorType>(Target)) {
11446 if (S.SourceMgr.isInSystemMacro(CC))
11447 return;
11448 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11449 }
11450
11451 // If the vector cast is cast between two vectors of the same size, it is
11452 // a bitcast, not a conversion.
11453 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11454 return;
11455
11456 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11457 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11458 }
11459 if (auto VecTy = dyn_cast<VectorType>(Target))
11460 Target = VecTy->getElementType().getTypePtr();
11461
11462 // Strip complex types.
11463 if (isa<ComplexType>(Source)) {
11464 if (!isa<ComplexType>(Target)) {
11465 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11466 return;
11467
11468 return DiagnoseImpCast(S, E, T, CC,
11469 S.getLangOpts().CPlusPlus
11470 ? diag::err_impcast_complex_scalar
11471 : diag::warn_impcast_complex_scalar);
11472 }
11473
11474 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11475 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11476 }
11477
11478 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11479 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11480
11481 // If the source is floating point...
11482 if (SourceBT && SourceBT->isFloatingPoint()) {
11483 // ...and the target is floating point...
11484 if (TargetBT && TargetBT->isFloatingPoint()) {
11485 // ...then warn if we're dropping FP rank.
11486
11487 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11488 QualType(SourceBT, 0), QualType(TargetBT, 0));
11489 if (Order > 0) {
11490 // Don't warn about float constants that are precisely
11491 // representable in the target type.
11492 Expr::EvalResult result;
11493 if (E->EvaluateAsRValue(result, S.Context)) {
11494 // Value might be a float, a float vector, or a float complex.
11495 if (IsSameFloatAfterCast(result.Val,
11496 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11497 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11498 return;
11499 }
11500
11501 if (S.SourceMgr.isInSystemMacro(CC))
11502 return;
11503
11504 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11505 }
11506 // ... or possibly if we're increasing rank, too
11507 else if (Order < 0) {
11508 if (S.SourceMgr.isInSystemMacro(CC))
11509 return;
11510
11511 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11512 }
11513 return;
11514 }
11515
11516 // If the target is integral, always warn.
11517 if (TargetBT && TargetBT->isInteger()) {
11518 if (S.SourceMgr.isInSystemMacro(CC))
11519 return;
11520
11521 DiagnoseFloatingImpCast(S, E, T, CC);
11522 }
11523
11524 // Detect the case where a call result is converted from floating-point to
11525 // to bool, and the final argument to the call is converted from bool, to
11526 // discover this typo:
11527 //
11528 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11529 //
11530 // FIXME: This is an incredibly special case; is there some more general
11531 // way to detect this class of misplaced-parentheses bug?
11532 if (Target->isBooleanType() && isa<CallExpr>(E)) {
11533 // Check last argument of function call to see if it is an
11534 // implicit cast from a type matching the type the result
11535 // is being cast to.
11536 CallExpr *CEx = cast<CallExpr>(E);
11537 if (unsigned NumArgs = CEx->getNumArgs()) {
11538 Expr *LastA = CEx->getArg(NumArgs - 1);
11539 Expr *InnerE = LastA->IgnoreParenImpCasts();
11540 if (isa<ImplicitCastExpr>(LastA) &&
11541 InnerE->getType()->isBooleanType()) {
11542 // Warn on this floating-point to bool conversion
11543 DiagnoseImpCast(S, E, T, CC,
11544 diag::warn_impcast_floating_point_to_bool);
11545 }
11546 }
11547 }
11548 return;
11549 }
11550
11551 // Valid casts involving fixed point types should be accounted for here.
11552 if (Source->isFixedPointType()) {
11553 if (Target->isUnsaturatedFixedPointType()) {
11554 Expr::EvalResult Result;
11555 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11556 S.isConstantEvaluated())) {
11557 APFixedPoint Value = Result.Val.getFixedPoint();
11558 APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11559 APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11560 if (Value > MaxVal || Value < MinVal) {
11561 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11562 S.PDiag(diag::warn_impcast_fixed_point_range)
11563 << Value.toString() << T
11564 << E->getSourceRange()
11565 << clang::SourceRange(CC));
11566 return;
11567 }
11568 }
11569 } else if (Target->isIntegerType()) {
11570 Expr::EvalResult Result;
11571 if (!S.isConstantEvaluated() &&
11572 E->EvaluateAsFixedPoint(Result, S.Context,
11573 Expr::SE_AllowSideEffects)) {
11574 APFixedPoint FXResult = Result.Val.getFixedPoint();
11575
11576 bool Overflowed;
11577 llvm::APSInt IntResult = FXResult.convertToInt(
11578 S.Context.getIntWidth(T),
11579 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11580
11581 if (Overflowed) {
11582 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11583 S.PDiag(diag::warn_impcast_fixed_point_range)
11584 << FXResult.toString() << T
11585 << E->getSourceRange()
11586 << clang::SourceRange(CC));
11587 return;
11588 }
11589 }
11590 }
11591 } else if (Target->isUnsaturatedFixedPointType()) {
11592 if (Source->isIntegerType()) {
11593 Expr::EvalResult Result;
11594 if (!S.isConstantEvaluated() &&
11595 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11596 llvm::APSInt Value = Result.Val.getInt();
11597
11598 bool Overflowed;
11599 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11600 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11601
11602 if (Overflowed) {
11603 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11604 S.PDiag(diag::warn_impcast_fixed_point_range)
11605 << Value.toString(/*Radix=*/10) << T
11606 << E->getSourceRange()
11607 << clang::SourceRange(CC));
11608 return;
11609 }
11610 }
11611 }
11612 }
11613
11614 // If we are casting an integer type to a floating point type without
11615 // initialization-list syntax, we might lose accuracy if the floating
11616 // point type has a narrower significand than the integer type.
11617 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11618 TargetBT->isFloatingType() && !IsListInit) {
11619 // Determine the number of precision bits in the source integer type.
11620 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11621 unsigned int SourcePrecision = SourceRange.Width;
11622
11623 // Determine the number of precision bits in the
11624 // target floating point type.
11625 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11626 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11627
11628 if (SourcePrecision > 0 && TargetPrecision > 0 &&
11629 SourcePrecision > TargetPrecision) {
11630
11631 llvm::APSInt SourceInt;
11632 if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11633 // If the source integer is a constant, convert it to the target
11634 // floating point type. Issue a warning if the value changes
11635 // during the whole conversion.
11636 llvm::APFloat TargetFloatValue(
11637 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11638 llvm::APFloat::opStatus ConversionStatus =
11639 TargetFloatValue.convertFromAPInt(
11640 SourceInt, SourceBT->isSignedInteger(),
11641 llvm::APFloat::rmNearestTiesToEven);
11642
11643 if (ConversionStatus != llvm::APFloat::opOK) {
11644 std::string PrettySourceValue = SourceInt.toString(10);
11645 SmallString<32> PrettyTargetValue;
11646 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11647
11648 S.DiagRuntimeBehavior(
11649 E->getExprLoc(), E,
11650 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11651 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11652 << E->getSourceRange() << clang::SourceRange(CC));
11653 }
11654 } else {
11655 // Otherwise, the implicit conversion may lose precision.
11656 DiagnoseImpCast(S, E, T, CC,
11657 diag::warn_impcast_integer_float_precision);
11658 }
11659 }
11660 }
11661
11662 DiagnoseNullConversion(S, E, T, CC);
11663
11664 S.DiscardMisalignedMemberAddress(Target, E);
11665
11666 if (Target->isBooleanType())
11667 DiagnoseIntInBoolContext(S, E);
11668
11669 if (!Source->isIntegerType() || !Target->isIntegerType())
11670 return;
11671
11672 // TODO: remove this early return once the false positives for constant->bool
11673 // in templates, macros, etc, are reduced or removed.
11674 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11675 return;
11676
11677 if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11678 !E->isKnownToHaveBooleanValue()) {
11679 return adornObjCBoolConversionDiagWithTernaryFixit(
11680 S, E,
11681 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11682 << E->getType());
11683 }
11684
11685 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11686 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11687
11688 if (SourceRange.Width > TargetRange.Width) {
11689 // If the source is a constant, use a default-on diagnostic.
11690 // TODO: this should happen for bitfield stores, too.
11691 Expr::EvalResult Result;
11692 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11693 S.isConstantEvaluated())) {
11694 llvm::APSInt Value(32);
11695 Value = Result.Val.getInt();
11696
11697 if (S.SourceMgr.isInSystemMacro(CC))
11698 return;
11699
11700 std::string PrettySourceValue = Value.toString(10);
11701 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11702
11703 S.DiagRuntimeBehavior(
11704 E->getExprLoc(), E,
11705 S.PDiag(diag::warn_impcast_integer_precision_constant)
11706 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11707 << E->getSourceRange() << clang::SourceRange(CC));
11708 return;
11709 }
11710
11711 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11712 if (S.SourceMgr.isInSystemMacro(CC))
11713 return;
11714
11715 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11716 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11717 /* pruneControlFlow */ true);
11718 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11719 }
11720
11721 if (TargetRange.Width > SourceRange.Width) {
11722 if (auto *UO = dyn_cast<UnaryOperator>(E))
11723 if (UO->getOpcode() == UO_Minus)
11724 if (Source->isUnsignedIntegerType()) {
11725 if (Target->isUnsignedIntegerType())
11726 return DiagnoseImpCast(S, E, T, CC,
11727 diag::warn_impcast_high_order_zero_bits);
11728 if (Target->isSignedIntegerType())
11729 return DiagnoseImpCast(S, E, T, CC,
11730 diag::warn_impcast_nonnegative_result);
11731 }
11732 }
11733
11734 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11735 SourceRange.NonNegative && Source->isSignedIntegerType()) {
11736 // Warn when doing a signed to signed conversion, warn if the positive
11737 // source value is exactly the width of the target type, which will
11738 // cause a negative value to be stored.
11739
11740 Expr::EvalResult Result;
11741 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11742 !S.SourceMgr.isInSystemMacro(CC)) {
11743 llvm::APSInt Value = Result.Val.getInt();
11744 if (isSameWidthConstantConversion(S, E, T, CC)) {
11745 std::string PrettySourceValue = Value.toString(10);
11746 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11747
11748 S.DiagRuntimeBehavior(
11749 E->getExprLoc(), E,
11750 S.PDiag(diag::warn_impcast_integer_precision_constant)
11751 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11752 << E->getSourceRange() << clang::SourceRange(CC));
11753 return;
11754 }
11755 }
11756
11757 // Fall through for non-constants to give a sign conversion warning.
11758 }
11759
11760 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11761 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11762 SourceRange.Width == TargetRange.Width)) {
11763 if (S.SourceMgr.isInSystemMacro(CC))
11764 return;
11765
11766 unsigned DiagID = diag::warn_impcast_integer_sign;
11767
11768 // Traditionally, gcc has warned about this under -Wsign-compare.
11769 // We also want to warn about it in -Wconversion.
11770 // So if -Wconversion is off, use a completely identical diagnostic
11771 // in the sign-compare group.
11772 // The conditional-checking code will
11773 if (ICContext) {
11774 DiagID = diag::warn_impcast_integer_sign_conditional;
11775 *ICContext = true;
11776 }
11777
11778 return DiagnoseImpCast(S, E, T, CC, DiagID);
11779 }
11780
11781 // Diagnose conversions between different enumeration types.
11782 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11783 // type, to give us better diagnostics.
11784 QualType SourceType = E->getType();
11785 if (!S.getLangOpts().CPlusPlus) {
11786 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11787 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11788 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11789 SourceType = S.Context.getTypeDeclType(Enum);
11790 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11791 }
11792 }
11793
11794 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11795 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11796 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11797 TargetEnum->getDecl()->hasNameForLinkage() &&
11798 SourceEnum != TargetEnum) {
11799 if (S.SourceMgr.isInSystemMacro(CC))
11800 return;
11801
11802 return DiagnoseImpCast(S, E, SourceType, T, CC,
11803 diag::warn_impcast_different_enum_types);
11804 }
11805}
11806
11807static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11808 SourceLocation CC, QualType T);
11809
11810static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11811 SourceLocation CC, bool &ICContext) {
11812 E = E->IgnoreParenImpCasts();
11813
11814 if (isa<ConditionalOperator>(E))
11815 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11816
11817 AnalyzeImplicitConversions(S, E, CC);
11818 if (E->getType() != T)
11819 return CheckImplicitConversion(S, E, T, CC, &ICContext);
11820}
11821
11822static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11823 SourceLocation CC, QualType T) {
11824 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11825
11826 bool Suspicious = false;
11827 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11828 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11829 CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
11830 E->getFalseExpr());
11831
11832 if (T->isBooleanType())
11833 DiagnoseIntInBoolContext(S, E);
11834
11835 // If -Wconversion would have warned about either of the candidates
11836 // for a signedness conversion to the context type...
11837 if (!Suspicious) return;
11838
11839 // ...but it's currently ignored...
11840 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11841 return;
11842
11843 // ...then check whether it would have warned about either of the
11844 // candidates for a signedness conversion to the condition type.
11845 if (E->getType() == T) return;
11846
11847 Suspicious = false;
11848 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11849 E->getType(), CC, &Suspicious);
11850 if (!Suspicious)
11851 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11852 E->getType(), CC, &Suspicious);
11853}
11854
11855/// Check conversion of given expression to boolean.
11856/// Input argument E is a logical expression.
11857static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11858 if (S.getLangOpts().Bool)
11859 return;
11860 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11861 return;
11862 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11863}
11864
11865/// AnalyzeImplicitConversions - Find and report any interesting
11866/// implicit conversions in the given expression. There are a couple
11867/// of competing diagnostics here, -Wconversion and -Wsign-compare.
11868static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11869 bool IsListInit/*= false*/) {
11870 QualType T = OrigE->getType();
11871 Expr *E = OrigE->IgnoreParenImpCasts();
11872
11873 // Propagate whether we are in a C++ list initialization expression.
11874 // If so, we do not issue warnings for implicit int-float conversion
11875 // precision loss, because C++11 narrowing already handles it.
11876 IsListInit =
11877 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11878
11879 if (E->isTypeDependent() || E->isValueDependent())
11880 return;
11881
11882 // For conditional operators, we analyze the arguments as if they
11883 // were being fed directly into the output.
11884 if (isa<ConditionalOperator>(E)) {
11885 ConditionalOperator *CO = cast<ConditionalOperator>(E);
11886 CheckConditionalOperator(S, CO, CC, T);
11887 return;
11888 }
11889
11890 // Check implicit argument conversions for function calls.
11891 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11892 CheckImplicitArgumentConversions(S, Call, CC);
11893
11894 // Go ahead and check any implicit conversions we might have skipped.
11895 // The non-canonical typecheck is just an optimization;
11896 // CheckImplicitConversion will filter out dead implicit conversions.
11897 if (E->getType() != T)
11898 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11899
11900 // Now continue drilling into this expression.
11901
11902 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11903 // The bound subexpressions in a PseudoObjectExpr are not reachable
11904 // as transitive children.
11905 // FIXME: Use a more uniform representation for this.
11906 for (auto *SE : POE->semantics())
11907 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11908 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11909 }
11910
11911 // Skip past explicit casts.
11912 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11913 E = CE->getSubExpr()->IgnoreParenImpCasts();
11914 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11915 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11916 return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11917 }
11918
11919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11920 // Do a somewhat different check with comparison operators.
11921 if (BO->isComparisonOp())
11922 return AnalyzeComparison(S, BO);
11923
11924 // And with simple assignments.
11925 if (BO->getOpcode() == BO_Assign)
11926 return AnalyzeAssignment(S, BO);
11927 // And with compound assignments.
11928 if (BO->isAssignmentOp())
11929 return AnalyzeCompoundAssignment(S, BO);
11930 }
11931
11932 // These break the otherwise-useful invariant below. Fortunately,
11933 // we don't really need to recurse into them, because any internal
11934 // expressions should have been analyzed already when they were
11935 // built into statements.
11936 if (isa<StmtExpr>(E)) return;
11937
11938 // Don't descend into unevaluated contexts.
11939 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11940
11941 // Now just recurse over the expression's children.
11942 CC = E->getExprLoc();
11943 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11944 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11945 for (Stmt *SubStmt : E->children()) {
11946 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11947 if (!ChildExpr)
11948 continue;
11949
11950 if (IsLogicalAndOperator &&
11951 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11952 // Ignore checking string literals that are in logical and operators.
11953 // This is a common pattern for asserts.
11954 continue;
11955 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
11956 }
11957
11958 if (BO && BO->isLogicalOp()) {
11959 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11960 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11961 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11962
11963 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11964 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11965 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11966 }
11967
11968 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11969 if (U->getOpcode() == UO_LNot) {
11970 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11971 } else if (U->getOpcode() != UO_AddrOf) {
11972 if (U->getSubExpr()->getType()->isAtomicType())
11973 S.Diag(U->getSubExpr()->getBeginLoc(),
11974 diag::warn_atomic_implicit_seq_cst);
11975 }
11976 }
11977}
11978
11979/// Diagnose integer type and any valid implicit conversion to it.
11980static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11981 // Taking into account implicit conversions,
11982 // allow any integer.
11983 if (!E->getType()->isIntegerType()) {
11984 S.Diag(E->getBeginLoc(),
11985 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11986 return true;
11987 }
11988 // Potentially emit standard warnings for implicit conversions if enabled
11989 // using -Wconversion.
11990 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11991 return false;
11992}
11993
11994// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11995// Returns true when emitting a warning about taking the address of a reference.
11996static bool CheckForReference(Sema &SemaRef, const Expr *E,
11997 const PartialDiagnostic &PD) {
11998 E = E->IgnoreParenImpCasts();
11999
12000 const FunctionDecl *FD = nullptr;
12001
12002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12003 if (!DRE->getDecl()->getType()->isReferenceType())
12004 return false;
12005 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12006 if (!M->getMemberDecl()->getType()->isReferenceType())
12007 return false;
12008 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12009 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12010 return false;
12011 FD = Call->getDirectCallee();
12012 } else {
12013 return false;
12014 }
12015
12016 SemaRef.Diag(E->getExprLoc(), PD);
12017
12018 // If possible, point to location of function.
12019 if (FD) {
12020 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12021 }
12022
12023 return true;
12024}
12025
12026// Returns true if the SourceLocation is expanded from any macro body.
12027// Returns false if the SourceLocation is invalid, is from not in a macro
12028// expansion, or is from expanded from a top-level macro argument.
12029static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12030 if (Loc.isInvalid())
12031 return false;
12032
12033 while (Loc.isMacroID()) {
12034 if (SM.isMacroBodyExpansion(Loc))
12035 return true;
12036 Loc = SM.getImmediateMacroCallerLoc(Loc);
12037 }
12038
12039 return false;
12040}
12041
12042/// Diagnose pointers that are always non-null.
12043/// \param E the expression containing the pointer
12044/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12045/// compared to a null pointer
12046/// \param IsEqual True when the comparison is equal to a null pointer
12047/// \param Range Extra SourceRange to highlight in the diagnostic
12048void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12049 Expr::NullPointerConstantKind NullKind,
12050 bool IsEqual, SourceRange Range) {
12051 if (!E)
12052 return;
12053
12054 // Don't warn inside macros.
12055 if (E->getExprLoc().isMacroID()) {
12056 const SourceManager &SM = getSourceManager();
12057 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12058 IsInAnyMacroBody(SM, Range.getBegin()))
12059 return;
12060 }
12061 E = E->IgnoreImpCasts();
12062
12063 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12064
12065 if (isa<CXXThisExpr>(E)) {
12066 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12067 : diag::warn_this_bool_conversion;
12068 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12069 return;
12070 }
12071
12072 bool IsAddressOf = false;
12073
12074 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12075 if (UO->getOpcode() != UO_AddrOf)
12076 return;
12077 IsAddressOf = true;
12078 E = UO->getSubExpr();
12079 }
12080
12081 if (IsAddressOf) {
12082 unsigned DiagID = IsCompare
12083 ? diag::warn_address_of_reference_null_compare
12084 : diag::warn_address_of_reference_bool_conversion;
12085 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12086 << IsEqual;
12087 if (CheckForReference(*this, E, PD)) {
12088 return;
12089 }
12090 }
12091
12092 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12093 bool IsParam = isa<NonNullAttr>(NonnullAttr);
12094 std::string Str;
12095 llvm::raw_string_ostream S(Str);
12096 E->printPretty(S, nullptr, getPrintingPolicy());
12097 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12098 : diag::warn_cast_nonnull_to_bool;
12099 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12100 << E->getSourceRange() << Range << IsEqual;
12101 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12102 };
12103
12104 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12105 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12106 if (auto *Callee = Call->getDirectCallee()) {
12107 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12108 ComplainAboutNonnullParamOrCall(A);
12109 return;
12110 }
12111 }
12112 }
12113
12114 // Expect to find a single Decl. Skip anything more complicated.
12115 ValueDecl *D = nullptr;
12116 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12117 D = R->getDecl();
12118 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12119 D = M->getMemberDecl();
12120 }
12121
12122 // Weak Decls can be null.
12123 if (!D || D->isWeak())
12124 return;
12125
12126 // Check for parameter decl with nonnull attribute
12127 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12128 if (getCurFunction() &&
12129 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12130 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12131 ComplainAboutNonnullParamOrCall(A);
12132 return;
12133 }
12134
12135 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12136 // Skip function template not specialized yet.
12137 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12138 return;
12139 auto ParamIter = llvm::find(FD->parameters(), PV);
12140 assert(ParamIter != FD->param_end())((ParamIter != FD->param_end()) ? static_cast<void> (
0) : __assert_fail ("ParamIter != FD->param_end()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 12140, __PRETTY_FUNCTION__))
;
12141 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12142
12143 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12144 if (!NonNull->args_size()) {
12145 ComplainAboutNonnullParamOrCall(NonNull);
12146 return;
12147 }
12148
12149 for (const ParamIdx &ArgNo : NonNull->args()) {
12150 if (ArgNo.getASTIndex() == ParamNo) {
12151 ComplainAboutNonnullParamOrCall(NonNull);
12152 return;
12153 }
12154 }
12155 }
12156 }
12157 }
12158 }
12159
12160 QualType T = D->getType();
12161 const bool IsArray = T->isArrayType();
12162 const bool IsFunction = T->isFunctionType();
12163
12164 // Address of function is used to silence the function warning.
12165 if (IsAddressOf && IsFunction) {
12166 return;
12167 }
12168
12169 // Found nothing.
12170 if (!IsAddressOf && !IsFunction && !IsArray)
12171 return;
12172
12173 // Pretty print the expression for the diagnostic.
12174 std::string Str;
12175 llvm::raw_string_ostream S(Str);
12176 E->printPretty(S, nullptr, getPrintingPolicy());
12177
12178 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12179 : diag::warn_impcast_pointer_to_bool;
12180 enum {
12181 AddressOf,
12182 FunctionPointer,
12183 ArrayPointer
12184 } DiagType;
12185 if (IsAddressOf)
12186 DiagType = AddressOf;
12187 else if (IsFunction)
12188 DiagType = FunctionPointer;
12189 else if (IsArray)
12190 DiagType = ArrayPointer;
12191 else
12192 llvm_unreachable("Could not determine diagnostic.")::llvm::llvm_unreachable_internal("Could not determine diagnostic."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 12192)
;
12193 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12194 << Range << IsEqual;
12195
12196 if (!IsFunction)
12197 return;
12198
12199 // Suggest '&' to silence the function warning.
12200 Diag(E->getExprLoc(), diag::note_function_warning_silence)
12201 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12202
12203 // Check to see if '()' fixit should be emitted.
12204 QualType ReturnType;
12205 UnresolvedSet<4> NonTemplateOverloads;
12206 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12207 if (ReturnType.isNull())
12208 return;
12209
12210 if (IsCompare) {
12211 // There are two cases here. If there is null constant, the only suggest
12212 // for a pointer return type. If the null is 0, then suggest if the return
12213 // type is a pointer or an integer type.
12214 if (!ReturnType->isPointerType()) {
12215 if (NullKind == Expr::NPCK_ZeroExpression ||
12216 NullKind == Expr::NPCK_ZeroLiteral) {
12217 if (!ReturnType->isIntegerType())
12218 return;
12219 } else {
12220 return;
12221 }
12222 }
12223 } else { // !IsCompare
12224 // For function to bool, only suggest if the function pointer has bool
12225 // return type.
12226 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12227 return;
12228 }
12229 Diag(E->getExprLoc(), diag::note_function_to_function_call)
12230 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12231}
12232
12233/// Diagnoses "dangerous" implicit conversions within the given
12234/// expression (which is a full expression). Implements -Wconversion
12235/// and -Wsign-compare.
12236///
12237/// \param CC the "context" location of the implicit conversion, i.e.
12238/// the most location of the syntactic entity requiring the implicit
12239/// conversion
12240void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12241 // Don't diagnose in unevaluated contexts.
12242 if (isUnevaluatedContext())
12243 return;
12244
12245 // Don't diagnose for value- or type-dependent expressions.
12246 if (E->isTypeDependent() || E->isValueDependent())
12247 return;
12248
12249 // Check for array bounds violations in cases where the check isn't triggered
12250 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12251 // ArraySubscriptExpr is on the RHS of a variable initialization.
12252 CheckArrayAccess(E);
12253
12254 // This is not the right CC for (e.g.) a variable initialization.
12255 AnalyzeImplicitConversions(*this, E, CC);
12256}
12257
12258/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12259/// Input argument E is a logical expression.
12260void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12261 ::CheckBoolLikeConversion(*this, E, CC);
12262}
12263
12264/// Diagnose when expression is an integer constant expression and its evaluation
12265/// results in integer overflow
12266void Sema::CheckForIntOverflow (Expr *E) {
12267 // Use a work list to deal with nested struct initializers.
12268 SmallVector<Expr *, 2> Exprs(1, E);
12269
12270 do {
12271 Expr *OriginalE = Exprs.pop_back_val();
12272 Expr *E = OriginalE->IgnoreParenCasts();
12273
12274 if (isa<BinaryOperator>(E)) {
12275 E->EvaluateForOverflow(Context);
12276 continue;
12277 }
12278
12279 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12280 Exprs.append(InitList->inits().begin(), InitList->inits().end());
12281 else if (isa<ObjCBoxedExpr>(OriginalE))
12282 E->EvaluateForOverflow(Context);
12283 else if (auto Call = dyn_cast<CallExpr>(E))
12284 Exprs.append(Call->arg_begin(), Call->arg_end());
12285 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12286 Exprs.append(Message->arg_begin(), Message->arg_end());
12287 } while (!Exprs.empty());
12288}
12289
12290namespace {
12291
12292/// Visitor for expressions which looks for unsequenced operations on the
12293/// same object.
12294class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12295 using Base = EvaluatedExprVisitor<SequenceChecker>;
12296
12297 /// A tree of sequenced regions within an expression. Two regions are
12298 /// unsequenced if one is an ancestor or a descendent of the other. When we
12299 /// finish processing an expression with sequencing, such as a comma
12300 /// expression, we fold its tree nodes into its parent, since they are
12301 /// unsequenced with respect to nodes we will visit later.
12302 class SequenceTree {
12303 struct Value {
12304 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12305 unsigned Parent : 31;
12306 unsigned Merged : 1;
12307 };
12308 SmallVector<Value, 8> Values;
12309
12310 public:
12311 /// A region within an expression which may be sequenced with respect
12312 /// to some other region.
12313 class Seq {
12314 friend class SequenceTree;
12315
12316 unsigned Index;
12317
12318 explicit Seq(unsigned N) : Index(N) {}
12319
12320 public:
12321 Seq() : Index(0) {}
12322 };
12323
12324 SequenceTree() { Values.push_back(Value(0)); }
12325 Seq root() const { return Seq(0); }
12326
12327 /// Create a new sequence of operations, which is an unsequenced
12328 /// subset of \p Parent. This sequence of operations is sequenced with
12329 /// respect to other children of \p Parent.
12330 Seq allocate(Seq Parent) {
12331 Values.push_back(Value(Parent.Index));
12332 return Seq(Values.size() - 1);
12333 }
12334
12335 /// Merge a sequence of operations into its parent.
12336 void merge(Seq S) {
12337 Values[S.Index].Merged = true;
12338 }
12339
12340 /// Determine whether two operations are unsequenced. This operation
12341 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12342 /// should have been merged into its parent as appropriate.
12343 bool isUnsequenced(Seq Cur, Seq Old) {
12344 unsigned C = representative(Cur.Index);
12345 unsigned Target = representative(Old.Index);
12346 while (C >= Target) {
12347 if (C == Target)
12348 return true;
12349 C = Values[C].Parent;
12350 }
12351 return false;
12352 }
12353
12354 private:
12355 /// Pick a representative for a sequence.
12356 unsigned representative(unsigned K) {
12357 if (Values[K].Merged)
12358 // Perform path compression as we go.
12359 return Values[K].Parent = representative(Values[K].Parent);
12360 return K;
12361 }
12362 };
12363
12364 /// An object for which we can track unsequenced uses.
12365 using Object = NamedDecl *;
12366
12367 /// Different flavors of object usage which we track. We only track the
12368 /// least-sequenced usage of each kind.
12369 enum UsageKind {
12370 /// A read of an object. Multiple unsequenced reads are OK.
12371 UK_Use,
12372
12373 /// A modification of an object which is sequenced before the value
12374 /// computation of the expression, such as ++n in C++.
12375 UK_ModAsValue,
12376
12377 /// A modification of an object which is not sequenced before the value
12378 /// computation of the expression, such as n++.
12379 UK_ModAsSideEffect,
12380
12381 UK_Count = UK_ModAsSideEffect + 1
12382 };
12383
12384 struct Usage {
12385 Expr *Use;
12386 SequenceTree::Seq Seq;
12387
12388 Usage() : Use(nullptr), Seq() {}
12389 };
12390
12391 struct UsageInfo {
12392 Usage Uses[UK_Count];
12393
12394 /// Have we issued a diagnostic for this variable already?
12395 bool Diagnosed;
12396
12397 UsageInfo() : Uses(), Diagnosed(false) {}
12398 };
12399 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12400
12401 Sema &SemaRef;
12402
12403 /// Sequenced regions within the expression.
12404 SequenceTree Tree;
12405
12406 /// Declaration modifications and references which we have seen.
12407 UsageInfoMap UsageMap;
12408
12409 /// The region we are currently within.
12410 SequenceTree::Seq Region;
12411
12412 /// Filled in with declarations which were modified as a side-effect
12413 /// (that is, post-increment operations).
12414 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12415
12416 /// Expressions to check later. We defer checking these to reduce
12417 /// stack usage.
12418 SmallVectorImpl<Expr *> &WorkList;
12419
12420 /// RAII object wrapping the visitation of a sequenced subexpression of an
12421 /// expression. At the end of this process, the side-effects of the evaluation
12422 /// become sequenced with respect to the value computation of the result, so
12423 /// we downgrade any UK_ModAsSideEffect within the evaluation to
12424 /// UK_ModAsValue.
12425 struct SequencedSubexpression {
12426 SequencedSubexpression(SequenceChecker &Self)
12427 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12428 Self.ModAsSideEffect = &ModAsSideEffect;
12429 }
12430
12431 ~SequencedSubexpression() {
12432 for (auto &M : llvm::reverse(ModAsSideEffect)) {
12433 UsageInfo &U = Self.UsageMap[M.first];
12434 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12435 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12436 SideEffectUsage = M.second;
12437 }
12438 Self.ModAsSideEffect = OldModAsSideEffect;
12439 }
12440
12441 SequenceChecker &Self;
12442 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12443 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12444 };
12445
12446 /// RAII object wrapping the visitation of a subexpression which we might
12447 /// choose to evaluate as a constant. If any subexpression is evaluated and
12448 /// found to be non-constant, this allows us to suppress the evaluation of
12449 /// the outer expression.
12450 class EvaluationTracker {
12451 public:
12452 EvaluationTracker(SequenceChecker &Self)
12453 : Self(Self), Prev(Self.EvalTracker) {
12454 Self.EvalTracker = this;
12455 }
12456
12457 ~EvaluationTracker() {
12458 Self.EvalTracker = Prev;
12459 if (Prev)
12460 Prev->EvalOK &= EvalOK;
12461 }
12462
12463 bool evaluate(const Expr *E, bool &Result) {
12464 if (!EvalOK || E->isValueDependent())
12465 return false;
12466 EvalOK = E->EvaluateAsBooleanCondition(
12467 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12468 return EvalOK;
12469 }
12470
12471 private:
12472 SequenceChecker &Self;
12473 EvaluationTracker *Prev;
12474 bool EvalOK = true;
12475 } *EvalTracker = nullptr;
12476
12477 /// Find the object which is produced by the specified expression,
12478 /// if any.
12479 Object getObject(Expr *E, bool Mod) const {
12480 E = E->IgnoreParenCasts();
12481 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12482 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12483 return getObject(UO->getSubExpr(), Mod);
12484 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12485 if (BO->getOpcode() == BO_Comma)
12486 return getObject(BO->getRHS(), Mod);
12487 if (Mod && BO->isAssignmentOp())
12488 return getObject(BO->getLHS(), Mod);
12489 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12490 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12491 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12492 return ME->getMemberDecl();
12493 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12494 // FIXME: If this is a reference, map through to its value.
12495 return DRE->getDecl();
12496 return nullptr;
12497 }
12498
12499 /// Note that an object was modified or used by an expression.
12500 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12501 Usage &U = UI.Uses[UK];
12502 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12503 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12504 ModAsSideEffect->push_back(std::make_pair(O, U));
12505 U.Use = Ref;
12506 U.Seq = Region;
12507 }
12508 }
12509
12510 /// Check whether a modification or use conflicts with a prior usage.
12511 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12512 bool IsModMod) {
12513 if (UI.Diagnosed)
12514 return;
12515
12516 const Usage &U = UI.Uses[OtherKind];
12517 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12518 return;
12519
12520 Expr *Mod = U.Use;
12521 Expr *ModOrUse = Ref;
12522 if (OtherKind == UK_Use)
12523 std::swap(Mod, ModOrUse);
12524
12525 SemaRef.DiagRuntimeBehavior(
12526 Mod->getExprLoc(), {Mod, ModOrUse},
12527 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12528 : diag::warn_unsequenced_mod_use)
12529 << O << SourceRange(ModOrUse->getExprLoc()));
12530 UI.Diagnosed = true;
12531 }
12532
12533 void notePreUse(Object O, Expr *Use) {
12534 UsageInfo &U = UsageMap[O];
12535 // Uses conflict with other modifications.
12536 checkUsage(O, U, Use, UK_ModAsValue, false);
12537 }
12538
12539 void notePostUse(Object O, Expr *Use) {
12540 UsageInfo &U = UsageMap[O];
12541 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12542 addUsage(U, O, Use, UK_Use);
12543 }
12544
12545 void notePreMod(Object O, Expr *Mod) {
12546 UsageInfo &U = UsageMap[O];
12547 // Modifications conflict with other modifications and with uses.
12548 checkUsage(O, U, Mod, UK_ModAsValue, true);
12549 checkUsage(O, U, Mod, UK_Use, false);
12550 }
12551
12552 void notePostMod(Object O, Expr *Use, UsageKind UK) {
12553 UsageInfo &U = UsageMap[O];
12554 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12555 addUsage(U, O, Use, UK);
12556 }
12557
12558public:
12559 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12560 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12561 Visit(E);
12562 }
12563
12564 void VisitStmt(Stmt *S) {
12565 // Skip all statements which aren't expressions for now.
12566 }
12567
12568 void VisitExpr(Expr *E) {
12569 // By default, just recurse to evaluated subexpressions.
12570 Base::VisitStmt(E);
12571 }
12572
12573 void VisitCastExpr(CastExpr *E) {
12574 Object O = Object();
12575 if (E->getCastKind() == CK_LValueToRValue)
12576 O = getObject(E->getSubExpr(), false);
12577
12578 if (O)
12579 notePreUse(O, E);
12580 VisitExpr(E);
12581 if (O)
12582 notePostUse(O, E);
12583 }
12584
12585 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12586 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12587 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12588 SequenceTree::Seq OldRegion = Region;
12589
12590 {
12591 SequencedSubexpression SeqBefore(*this);
12592 Region = BeforeRegion;
12593 Visit(SequencedBefore);
12594 }
12595
12596 Region = AfterRegion;
12597 Visit(SequencedAfter);
12598
12599 Region = OldRegion;
12600
12601 Tree.merge(BeforeRegion);
12602 Tree.merge(AfterRegion);
12603 }
12604
12605 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12606 // C++17 [expr.sub]p1:
12607 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12608 // expression E1 is sequenced before the expression E2.
12609 if (SemaRef.getLangOpts().CPlusPlus17)
12610 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12611 else
12612 Base::VisitStmt(ASE);
12613 }
12614
12615 void VisitBinComma(BinaryOperator *BO) {
12616 // C++11 [expr.comma]p1:
12617 // Every value computation and side effect associated with the left
12618 // expression is sequenced before every value computation and side
12619 // effect associated with the right expression.
12620 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12621 }
12622
12623 void VisitBinAssign(BinaryOperator *BO) {
12624 // The modification is sequenced after the value computation of the LHS
12625 // and RHS, so check it before inspecting the operands and update the
12626 // map afterwards.
12627 Object O = getObject(BO->getLHS(), true);
12628 if (!O)
12629 return VisitExpr(BO);
12630
12631 notePreMod(O, BO);
12632
12633 // C++11 [expr.ass]p7:
12634 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12635 // only once.
12636 //
12637 // Therefore, for a compound assignment operator, O is considered used
12638 // everywhere except within the evaluation of E1 itself.
12639 if (isa<CompoundAssignOperator>(BO))
12640 notePreUse(O, BO);
12641
12642 Visit(BO->getLHS());
12643
12644 if (isa<CompoundAssignOperator>(BO))
12645 notePostUse(O, BO);
12646
12647 Visit(BO->getRHS());
12648
12649 // C++11 [expr.ass]p1:
12650 // the assignment is sequenced [...] before the value computation of the
12651 // assignment expression.
12652 // C11 6.5.16/3 has no such rule.
12653 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12654 : UK_ModAsSideEffect);
12655 }
12656
12657 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12658 VisitBinAssign(CAO);
12659 }
12660
12661 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12662 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12663 void VisitUnaryPreIncDec(UnaryOperator *UO) {
12664 Object O = getObject(UO->getSubExpr(), true);
12665 if (!O)
12666 return VisitExpr(UO);
12667
12668 notePreMod(O, UO);
12669 Visit(UO->getSubExpr());
12670 // C++11 [expr.pre.incr]p1:
12671 // the expression ++x is equivalent to x+=1
12672 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12673 : UK_ModAsSideEffect);
12674 }
12675
12676 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12677 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12678 void VisitUnaryPostIncDec(UnaryOperator *UO) {
12679 Object O = getObject(UO->getSubExpr(), true);
12680 if (!O)
12681 return VisitExpr(UO);
12682
12683 notePreMod(O, UO);
12684 Visit(UO->getSubExpr());
12685 notePostMod(O, UO, UK_ModAsSideEffect);
12686 }
12687
12688 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12689 void VisitBinLOr(BinaryOperator *BO) {
12690 // The side-effects of the LHS of an '&&' are sequenced before the
12691 // value computation of the RHS, and hence before the value computation
12692 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12693 // as if they were unconditionally sequenced.
12694 EvaluationTracker Eval(*this);
12695 {
12696 SequencedSubexpression Sequenced(*this);
12697 Visit(BO->getLHS());
12698 }
12699
12700 bool Result;
12701 if (Eval.evaluate(BO->getLHS(), Result)) {
12702 if (!Result)
12703 Visit(BO->getRHS());
12704 } else {
12705 // Check for unsequenced operations in the RHS, treating it as an
12706 // entirely separate evaluation.
12707 //
12708 // FIXME: If there are operations in the RHS which are unsequenced
12709 // with respect to operations outside the RHS, and those operations
12710 // are unconditionally evaluated, diagnose them.
12711 WorkList.push_back(BO->getRHS());
12712 }
12713 }
12714 void VisitBinLAnd(BinaryOperator *BO) {
12715 EvaluationTracker Eval(*this);
12716 {
12717 SequencedSubexpression Sequenced(*this);
12718 Visit(BO->getLHS());
12719 }
12720
12721 bool Result;
12722 if (Eval.evaluate(BO->getLHS(), Result)) {
12723 if (Result)
12724 Visit(BO->getRHS());
12725 } else {
12726 WorkList.push_back(BO->getRHS());
12727 }
12728 }
12729
12730 // Only visit the condition, unless we can be sure which subexpression will
12731 // be chosen.
12732 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12733 EvaluationTracker Eval(*this);
12734 {
12735 SequencedSubexpression Sequenced(*this);
12736 Visit(CO->getCond());
12737 }
12738
12739 bool Result;
12740 if (Eval.evaluate(CO->getCond(), Result))
12741 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12742 else {
12743 WorkList.push_back(CO->getTrueExpr());
12744 WorkList.push_back(CO->getFalseExpr());
12745 }
12746 }
12747
12748 void VisitCallExpr(CallExpr *CE) {
12749 // C++11 [intro.execution]p15:
12750 // When calling a function [...], every value computation and side effect
12751 // associated with any argument expression, or with the postfix expression
12752 // designating the called function, is sequenced before execution of every
12753 // expression or statement in the body of the function [and thus before
12754 // the value computation of its result].
12755 SequencedSubexpression Sequenced(*this);
12756 Base::VisitCallExpr(CE);
12757
12758 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12759 }
12760
12761 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12762 // This is a call, so all subexpressions are sequenced before the result.
12763 SequencedSubexpression Sequenced(*this);
12764
12765 if (!CCE->isListInitialization())
12766 return VisitExpr(CCE);
12767
12768 // In C++11, list initializations are sequenced.
12769 SmallVector<SequenceTree::Seq, 32> Elts;
12770 SequenceTree::Seq Parent = Region;
12771 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12772 E = CCE->arg_end();
12773 I != E; ++I) {
12774 Region = Tree.allocate(Parent);
12775 Elts.push_back(Region);
12776 Visit(*I);
12777 }
12778
12779 // Forget that the initializers are sequenced.
12780 Region = Parent;
12781 for (unsigned I = 0; I < Elts.size(); ++I)
12782 Tree.merge(Elts[I]);
12783 }
12784
12785 void VisitInitListExpr(InitListExpr *ILE) {
12786 if (!SemaRef.getLangOpts().CPlusPlus11)
12787 return VisitExpr(ILE);
12788
12789 // In C++11, list initializations are sequenced.
12790 SmallVector<SequenceTree::Seq, 32> Elts;
12791 SequenceTree::Seq Parent = Region;
12792 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12793 Expr *E = ILE->getInit(I);
12794 if (!E) continue;
12795 Region = Tree.allocate(Parent);
12796 Elts.push_back(Region);
12797 Visit(E);
12798 }
12799
12800 // Forget that the initializers are sequenced.
12801 Region = Parent;
12802 for (unsigned I = 0; I < Elts.size(); ++I)
12803 Tree.merge(Elts[I]);
12804 }
12805};
12806
12807} // namespace
12808
12809void Sema::CheckUnsequencedOperations(Expr *E) {
12810 SmallVector<Expr *, 8> WorkList;
12811 WorkList.push_back(E);
12812 while (!WorkList.empty()) {
12813 Expr *Item = WorkList.pop_back_val();
12814 SequenceChecker(*this, Item, WorkList);
12815 }
12816}
12817
12818void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12819 bool IsConstexpr) {
12820 llvm::SaveAndRestore<bool> ConstantContext(
12821 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12822 CheckImplicitConversions(E, CheckLoc);
12823 if (!E->isInstantiationDependent())
12824 CheckUnsequencedOperations(E);
12825 if (!IsConstexpr && !E->isValueDependent())
12826 CheckForIntOverflow(E);
12827 DiagnoseMisalignedMembers();
12828}
12829
12830void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12831 FieldDecl *BitField,
12832 Expr *Init) {
12833 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12834}
12835
12836static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12837 SourceLocation Loc) {
12838 if (!PType->isVariablyModifiedType())
12839 return;
12840 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12841 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12842 return;
12843 }
12844 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12845 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12846 return;
12847 }
12848 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12849 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12850 return;
12851 }
12852
12853 const ArrayType *AT = S.Context.getAsArrayType(PType);
12854 if (!AT)
12855 return;
12856
12857 if (AT->getSizeModifier() != ArrayType::Star) {
12858 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12859 return;
12860 }
12861
12862 S.Diag(Loc, diag::err_array_star_in_function_definition);
12863}
12864
12865/// CheckParmsForFunctionDef - Check that the parameters of the given
12866/// function are appropriate for the definition of a function. This
12867/// takes care of any checks that cannot be performed on the
12868/// declaration itself, e.g., that the types of each of the function
12869/// parameters are complete.
12870bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12871 bool CheckParameterNames) {
12872 bool HasInvalidParm = false;
12873 for (ParmVarDecl *Param : Parameters) {
12874 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12875 // function declarator that is part of a function definition of
12876 // that function shall not have incomplete type.
12877 //
12878 // This is also C++ [dcl.fct]p6.
12879 if (!Param->isInvalidDecl() &&
12880 RequireCompleteType(Param->getLocation(), Param->getType(),
12881 diag::err_typecheck_decl_incomplete_type)) {
12882 Param->setInvalidDecl();
12883 HasInvalidParm = true;
12884 }
12885
12886 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12887 // declaration of each parameter shall include an identifier.
12888 if (CheckParameterNames &&
12889 Param->getIdentifier() == nullptr &&
12890 !Param->isImplicit() &&
12891 !getLangOpts().CPlusPlus)
12892 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12893
12894 // C99 6.7.5.3p12:
12895 // If the function declarator is not part of a definition of that
12896 // function, parameters may have incomplete type and may use the [*]
12897 // notation in their sequences of declarator specifiers to specify
12898 // variable length array types.
12899 QualType PType = Param->getOriginalType();
12900 // FIXME: This diagnostic should point the '[*]' if source-location
12901 // information is added for it.
12902 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12903
12904 // If the parameter is a c++ class type and it has to be destructed in the
12905 // callee function, declare the destructor so that it can be called by the
12906 // callee function. Do not perform any direct access check on the dtor here.
12907 if (!Param->isInvalidDecl()) {
12908 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12909 if (!ClassDecl->isInvalidDecl() &&
12910 !ClassDecl->hasIrrelevantDestructor() &&
12911 !ClassDecl->isDependentContext() &&
12912 ClassDecl->isParamDestroyedInCallee()) {
12913 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12914 MarkFunctionReferenced(Param->getLocation(), Destructor);
12915 DiagnoseUseOfDecl(Destructor, Param->getLocation());
12916 }
12917 }
12918 }
12919
12920 // Parameters with the pass_object_size attribute only need to be marked
12921 // constant at function definitions. Because we lack information about
12922 // whether we're on a declaration or definition when we're instantiating the
12923 // attribute, we need to check for constness here.
12924 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12925 if (!Param->getType().isConstQualified())
12926 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12927 << Attr->getSpelling() << 1;
12928
12929 // Check for parameter names shadowing fields from the class.
12930 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12931 // The owning context for the parameter should be the function, but we
12932 // want to see if this function's declaration context is a record.
12933 DeclContext *DC = Param->getDeclContext();
12934 if (DC && DC->isFunctionOrMethod()) {
12935 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12936 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12937 RD, /*DeclIsField*/ false);
12938 }
12939 }
12940 }
12941
12942 return HasInvalidParm;
12943}
12944
12945/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12946/// or MemberExpr.
12947static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12948 ASTContext &Context) {
12949 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12950 return Context.getDeclAlign(DRE->getDecl());
12951
12952 if (const auto *ME = dyn_cast<MemberExpr>(E))
12953 return Context.getDeclAlign(ME->getMemberDecl());
12954
12955 return TypeAlign;
12956}
12957
12958/// CheckCastAlign - Implements -Wcast-align, which warns when a
12959/// pointer cast increases the alignment requirements.
12960void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12961 // This is actually a lot of work to potentially be doing on every
12962 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12963 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12964 return;
12965
12966 // Ignore dependent types.
12967 if (T->isDependentType() || Op->getType()->isDependentType())
12968 return;
12969
12970 // Require that the destination be a pointer type.
12971 const PointerType *DestPtr = T->getAs<PointerType>();
12972 if (!DestPtr) return;
12973
12974 // If the destination has alignment 1, we're done.
12975 QualType DestPointee = DestPtr->getPointeeType();
12976 if (DestPointee->isIncompleteType()) return;
12977 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12978 if (DestAlign.isOne()) return;
12979
12980 // Require that the source be a pointer type.
12981 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12982 if (!SrcPtr) return;
12983 QualType SrcPointee = SrcPtr->getPointeeType();
12984
12985 // Whitelist casts from cv void*. We already implicitly
12986 // whitelisted casts to cv void*, since they have alignment 1.
12987 // Also whitelist casts involving incomplete types, which implicitly
12988 // includes 'void'.
12989 if (SrcPointee->isIncompleteType()) return;
12990
12991 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12992
12993 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12994 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12995 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12996 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12997 if (UO->getOpcode() == UO_AddrOf)
12998 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12999 }
13000
13001 if (SrcAlign >= DestAlign) return;
13002
13003 Diag(TRange.getBegin(), diag::warn_cast_align)
13004 << Op->getType() << T
13005 << static_cast<unsigned>(SrcAlign.getQuantity())
13006 << static_cast<unsigned>(DestAlign.getQuantity())
13007 << TRange << Op->getSourceRange();
13008}
13009
13010/// Check whether this array fits the idiom of a size-one tail padded
13011/// array member of a struct.
13012///
13013/// We avoid emitting out-of-bounds access warnings for such arrays as they are
13014/// commonly used to emulate flexible arrays in C89 code.
13015static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13016 const NamedDecl *ND) {
13017 if (Size != 1 || !ND) return false;
13018
13019 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13020 if (!FD) return false;
13021
13022 // Don't consider sizes resulting from macro expansions or template argument
13023 // substitution to form C89 tail-padded arrays.
13024
13025 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13026 while (TInfo) {
13027 TypeLoc TL = TInfo->getTypeLoc();
13028 // Look through typedefs.
13029 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13030 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13031 TInfo = TDL->getTypeSourceInfo();
13032 continue;
13033 }
13034 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13035 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13036 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13037 return false;
13038 }
13039 break;
13040 }
13041
13042 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13043 if (!RD) return false;
13044 if (RD->isUnion()) return false;
13045 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13046 if (!CRD->isStandardLayout()) return false;
13047 }
13048
13049 // See if this is the last field decl in the record.
13050 const Decl *D = FD;
13051 while ((D = D->getNextDeclInContext()))
13052 if (isa<FieldDecl>(D))
13053 return false;
13054 return true;
13055}
13056
13057void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13058 const ArraySubscriptExpr *ASE,
13059 bool AllowOnePastEnd, bool IndexNegated) {
13060 // Already diagnosed by the constant evaluator.
13061 if (isConstantEvaluated())
13062 return;
13063
13064 IndexExpr = IndexExpr->IgnoreParenImpCasts();
13065 if (IndexExpr->isValueDependent())
13066 return;
13067
13068 const Type *EffectiveType =
13069 BaseExpr->getType()->getPointeeOrArrayElementType();
13070 BaseExpr = BaseExpr->IgnoreParenCasts();
13071 const ConstantArrayType *ArrayTy =
13072 Context.getAsConstantArrayType(BaseExpr->getType());
13073
13074 if (!ArrayTy)
13075 return;
13076
13077 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13078 if (EffectiveType->isDependentType() || BaseType->isDependentType())
13079 return;
13080
13081 Expr::EvalResult Result;
13082 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13083 return;
13084
13085 llvm::APSInt index = Result.Val.getInt();
13086 if (IndexNegated)
13087 index = -index;
13088
13089 const NamedDecl *ND = nullptr;
13090 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13091 ND = DRE->getDecl();
13092 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13093 ND = ME->getMemberDecl();
13094
13095 if (index.isUnsigned() || !index.isNegative()) {
13096 // It is possible that the type of the base expression after
13097 // IgnoreParenCasts is incomplete, even though the type of the base
13098 // expression before IgnoreParenCasts is complete (see PR39746 for an
13099 // example). In this case we have no information about whether the array
13100 // access exceeds the array bounds. However we can still diagnose an array
13101 // access which precedes the array bounds.
13102 if (BaseType->isIncompleteType())
13103 return;
13104
13105 llvm::APInt size = ArrayTy->getSize();
13106 if (!size.isStrictlyPositive())
13107 return;
13108
13109 if (BaseType != EffectiveType) {
13110 // Make sure we're comparing apples to apples when comparing index to size
13111 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13112 uint64_t array_typesize = Context.getTypeSize(BaseType);
13113 // Handle ptrarith_typesize being zero, such as when casting to void*
13114 if (!ptrarith_typesize) ptrarith_typesize = 1;
13115 if (ptrarith_typesize != array_typesize) {
13116 // There's a cast to a different size type involved
13117 uint64_t ratio = array_typesize / ptrarith_typesize;
13118 // TODO: Be smarter about handling cases where array_typesize is not a
13119 // multiple of ptrarith_typesize
13120 if (ptrarith_typesize * ratio == array_typesize)
13121 size *= llvm::APInt(size.getBitWidth(), ratio);
13122 }
13123 }
13124
13125 if (size.getBitWidth() > index.getBitWidth())
13126 index = index.zext(size.getBitWidth());
13127 else if (size.getBitWidth() < index.getBitWidth())
13128 size = size.zext(index.getBitWidth());
13129
13130 // For array subscripting the index must be less than size, but for pointer
13131 // arithmetic also allow the index (offset) to be equal to size since
13132 // computing the next address after the end of the array is legal and
13133 // commonly done e.g. in C++ iterators and range-based for loops.
13134 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13135 return;
13136
13137 // Also don't warn for arrays of size 1 which are members of some
13138 // structure. These are often used to approximate flexible arrays in C89
13139 // code.
13140 if (IsTailPaddedMemberArray(*this, size, ND))
13141 return;
13142
13143 // Suppress the warning if the subscript expression (as identified by the
13144 // ']' location) and the index expression are both from macro expansions
13145 // within a system header.
13146 if (ASE) {
13147 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13148 ASE->getRBracketLoc());
13149 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13150 SourceLocation IndexLoc =
13151 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13152 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13153 return;
13154 }
13155 }
13156
13157 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13158 if (ASE)
13159 DiagID = diag::warn_array_index_exceeds_bounds;
13160
13161 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13162 PDiag(DiagID) << index.toString(10, true)
13163 << size.toString(10, true)
13164 << (unsigned)size.getLimitedValue(~0U)
13165 << IndexExpr->getSourceRange());
13166 } else {
13167 unsigned DiagID = diag::warn_array_index_precedes_bounds;
13168 if (!ASE) {
13169 DiagID = diag::warn_ptr_arith_precedes_bounds;
13170 if (index.isNegative()) index = -index;
13171 }
13172
13173 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13174 PDiag(DiagID) << index.toString(10, true)
13175 << IndexExpr->getSourceRange());
13176 }
13177
13178 if (!ND) {
13179 // Try harder to find a NamedDecl to point at in the note.
13180 while (const ArraySubscriptExpr *ASE =
13181 dyn_cast<ArraySubscriptExpr>(BaseExpr))
13182 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13183 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13184 ND = DRE->getDecl();
13185 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13186 ND = ME->getMemberDecl();
13187 }
13188
13189 if (ND)
13190 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13191 PDiag(diag::note_array_declared_here)
13192 << ND->getDeclName());
13193}
13194
13195void Sema::CheckArrayAccess(const Expr *expr) {
13196 int AllowOnePastEnd = 0;
13197 while (expr) {
13198 expr = expr->IgnoreParenImpCasts();
13199 switch (expr->getStmtClass()) {
13200 case Stmt::ArraySubscriptExprClass: {
13201 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13202 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13203 AllowOnePastEnd > 0);
13204 expr = ASE->getBase();
13205 break;
13206 }
13207 case Stmt::MemberExprClass: {
13208 expr = cast<MemberExpr>(expr)->getBase();
13209 break;
13210 }
13211 case Stmt::OMPArraySectionExprClass: {
13212 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13213 if (ASE->getLowerBound())
13214 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13215 /*ASE=*/nullptr, AllowOnePastEnd > 0);
13216 return;
13217 }
13218 case Stmt::UnaryOperatorClass: {
13219 // Only unwrap the * and & unary operators
13220 const UnaryOperator *UO = cast<UnaryOperator>(expr);
13221 expr = UO->getSubExpr();
13222 switch (UO->getOpcode()) {
13223 case UO_AddrOf:
13224 AllowOnePastEnd++;
13225 break;
13226 case UO_Deref:
13227 AllowOnePastEnd--;
13228 break;
13229 default:
13230 return;
13231 }
13232 break;
13233 }
13234 case Stmt::ConditionalOperatorClass: {
13235 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13236 if (const Expr *lhs = cond->getLHS())
13237 CheckArrayAccess(lhs);
13238 if (const Expr *rhs = cond->getRHS())
13239 CheckArrayAccess(rhs);
13240 return;
13241 }
13242 case Stmt::CXXOperatorCallExprClass: {
13243 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13244 for (const auto *Arg : OCE->arguments())
13245 CheckArrayAccess(Arg);
13246 return;
13247 }
13248 default:
13249 return;
13250 }
13251 }
13252}
13253
13254//===--- CHECK: Objective-C retain cycles ----------------------------------//
13255
13256namespace {
13257
13258struct RetainCycleOwner {
13259 VarDecl *Variable = nullptr;
13260 SourceRange Range;
13261 SourceLocation Loc;
13262 bool Indirect = false;
13263
13264 RetainCycleOwner() = default;
13265
13266 void setLocsFrom(Expr *e) {
13267 Loc = e->getExprLoc();
13268 Range = e->getSourceRange();
13269 }
13270};
13271
13272} // namespace
13273
13274/// Consider whether capturing the given variable can possibly lead to
13275/// a retain cycle.
13276static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13277 // In ARC, it's captured strongly iff the variable has __strong
13278 // lifetime. In MRR, it's captured strongly if the variable is
13279 // __block and has an appropriate type.
13280 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13281 return false;
13282
13283 owner.Variable = var;
13284 if (ref)
13285 owner.setLocsFrom(ref);
13286 return true;
13287}
13288
13289static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13290 while (true) {
13291 e = e->IgnoreParens();
13292 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13293 switch (cast->getCastKind()) {
13294 case CK_BitCast:
13295 case CK_LValueBitCast:
13296 case CK_LValueToRValue:
13297 case CK_ARCReclaimReturnedObject:
13298 e = cast->getSubExpr();
13299 continue;
13300
13301 default:
13302 return false;
13303 }
13304 }
13305
13306 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13307 ObjCIvarDecl *ivar = ref->getDecl();
13308 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13309 return false;
13310
13311 // Try to find a retain cycle in the base.
13312 if (!findRetainCycleOwner(S, ref->getBase(), owner))
13313 return false;
13314
13315 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13316 owner.Indirect = true;
13317 return true;
13318 }
13319
13320 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13321 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13322 if (!var) return false;
13323 return considerVariable(var, ref, owner);
13324 }
13325
13326 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13327 if (member->isArrow()) return false;
13328
13329 // Don't count this as an indirect ownership.
13330 e = member->getBase();
13331 continue;
13332 }
13333
13334 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13335 // Only pay attention to pseudo-objects on property references.
13336 ObjCPropertyRefExpr *pre
13337 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13338 ->IgnoreParens());
13339 if (!pre) return false;
13340 if (pre->isImplicitProperty()) return false;
13341 ObjCPropertyDecl *property = pre->getExplicitProperty();
13342 if (!property->isRetaining() &&
13343 !(property->getPropertyIvarDecl() &&
13344 property->getPropertyIvarDecl()->getType()
13345 .getObjCLifetime() == Qualifiers::OCL_Strong))
13346 return false;
13347
13348 owner.Indirect = true;
13349 if (pre->isSuperReceiver()) {
13350 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13351 if (!owner.Variable)
13352 return false;
13353 owner.Loc = pre->getLocation();
13354 owner.Range = pre->getSourceRange();
13355 return true;
13356 }
13357 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13358 ->getSourceExpr());
13359 continue;
13360 }
13361
13362 // Array ivars?
13363
13364 return false;
13365 }
13366}
13367
13368namespace {
13369
13370 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13371 ASTContext &Context;
13372 VarDecl *Variable;
13373 Expr *Capturer = nullptr;
13374 bool VarWillBeReased = false;
13375
13376 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13377 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13378 Context(Context), Variable(variable) {}
13379
13380 void VisitDeclRefExpr(DeclRefExpr *ref) {
13381 if (ref->getDecl() == Variable && !Capturer)
13382 Capturer = ref;
13383 }
13384
13385 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13386 if (Capturer) return;
13387 Visit(ref->getBase());
13388 if (Capturer && ref->isFreeIvar())
13389 Capturer = ref;
13390 }
13391
13392 void VisitBlockExpr(BlockExpr *block) {
13393 // Look inside nested blocks
13394 if (block->getBlockDecl()->capturesVariable(Variable))
13395 Visit(block->getBlockDecl()->getBody());
13396 }
13397
13398 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13399 if (Capturer) return;
13400 if (OVE->getSourceExpr())
13401 Visit(OVE->getSourceExpr());
13402 }
13403
13404 void VisitBinaryOperator(BinaryOperator *BinOp) {
13405 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13406 return;
13407 Expr *LHS = BinOp->getLHS();
13408 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13409 if (DRE->getDecl() != Variable)
13410 return;
13411 if (Expr *RHS = BinOp->getRHS()) {
13412 RHS = RHS->IgnoreParenCasts();
13413 llvm::APSInt Value;
13414 VarWillBeReased =
13415 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13416 }
13417 }
13418 }
13419 };
13420
13421} // namespace
13422
13423/// Check whether the given argument is a block which captures a
13424/// variable.
13425static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13426 assert(owner.Variable && owner.Loc.isValid())((owner.Variable && owner.Loc.isValid()) ? static_cast
<void> (0) : __assert_fail ("owner.Variable && owner.Loc.isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 13426, __PRETTY_FUNCTION__))
;
13427
13428 e = e->IgnoreParenCasts();
13429
13430 // Look through [^{...} copy] and Block_copy(^{...}).
13431 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13432 Selector Cmd = ME->getSelector();
13433 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13434 e = ME->getInstanceReceiver();
13435 if (!e)
13436 return nullptr;
13437 e = e->IgnoreParenCasts();
13438 }
13439 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13440 if (CE->getNumArgs() == 1) {
13441 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13442 if (Fn) {
13443 const IdentifierInfo *FnI = Fn->getIdentifier();
13444 if (FnI && FnI->isStr("_Block_copy")) {
13445 e = CE->getArg(0)->IgnoreParenCasts();
13446 }
13447 }
13448 }
13449 }
13450
13451 BlockExpr *block = dyn_cast<BlockExpr>(e);
13452 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13453 return nullptr;
13454
13455 FindCaptureVisitor visitor(S.Context, owner.Variable);
13456 visitor.Visit(block->getBlockDecl()->getBody());
13457 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13458}
13459
13460static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13461 RetainCycleOwner &owner) {
13462 assert(capturer)((capturer) ? static_cast<void> (0) : __assert_fail ("capturer"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 13462, __PRETTY_FUNCTION__))
;
13463 assert(owner.Variable && owner.Loc.isValid())((owner.Variable && owner.Loc.isValid()) ? static_cast
<void> (0) : __assert_fail ("owner.Variable && owner.Loc.isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 13463, __PRETTY_FUNCTION__))
;
13464
13465 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13466 << owner.Variable << capturer->getSourceRange();
13467 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13468 << owner.Indirect << owner.Range;
13469}
13470
13471/// Check for a keyword selector that starts with the word 'add' or
13472/// 'set'.
13473static bool isSetterLikeSelector(Selector sel) {
13474 if (sel.isUnarySelector()) return false;
13475
13476 StringRef str = sel.getNameForSlot(0);
13477 while (!str.empty() && str.front() == '_') str = str.substr(1);
13478 if (str.startswith("set"))
13479 str = str.substr(3);
13480 else if (str.startswith("add")) {
13481 // Specially whitelist 'addOperationWithBlock:'.
13482 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13483 return false;
13484 str = str.substr(3);
13485 }
13486 else
13487 return false;
13488
13489 if (str.empty()) return true;
13490 return !isLowercase(str.front());
13491}
13492
13493static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13494 ObjCMessageExpr *Message) {
13495 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13496 Message->getReceiverInterface(),
13497 NSAPI::ClassId_NSMutableArray);
13498 if (!IsMutableArray) {
13499 return None;
13500 }
13501
13502 Selector Sel = Message->getSelector();
13503
13504 Optional<NSAPI::NSArrayMethodKind> MKOpt =
13505 S.NSAPIObj->getNSArrayMethodKind(Sel);
13506 if (!MKOpt) {
13507 return None;
13508 }
13509
13510 NSAPI::NSArrayMethodKind MK = *MKOpt;
13511
13512 switch (MK) {
13513 case NSAPI::NSMutableArr_addObject:
13514 case NSAPI::NSMutableArr_insertObjectAtIndex:
13515 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13516 return 0;
13517 case NSAPI::NSMutableArr_replaceObjectAtIndex:
13518 return 1;
13519
13520 default:
13521 return None;
13522 }
13523
13524 return None;
13525}
13526
13527static
13528Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13529 ObjCMessageExpr *Message) {
13530 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13531 Message->getReceiverInterface(),
13532 NSAPI::ClassId_NSMutableDictionary);
13533 if (!IsMutableDictionary) {
13534 return None;
13535 }
13536
13537 Selector Sel = Message->getSelector();
13538
13539 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13540 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13541 if (!MKOpt) {
13542 return None;
13543 }
13544
13545 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13546
13547 switch (MK) {
13548 case NSAPI::NSMutableDict_setObjectForKey:
13549 case NSAPI::NSMutableDict_setValueForKey:
13550 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13551 return 0;
13552
13553 default:
13554 return None;
13555 }
13556
13557 return None;
13558}
13559
13560static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13561 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13562 Message->getReceiverInterface(),
13563 NSAPI::ClassId_NSMutableSet);
13564
13565 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13566 Message->getReceiverInterface(),
13567 NSAPI::ClassId_NSMutableOrderedSet);
13568 if (!IsMutableSet && !IsMutableOrderedSet) {
13569 return None;
13570 }
13571
13572 Selector Sel = Message->getSelector();
13573
13574 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13575 if (!MKOpt) {
13576 return None;
13577 }
13578
13579 NSAPI::NSSetMethodKind MK = *MKOpt;
13580
13581 switch (MK) {
13582 case NSAPI::NSMutableSet_addObject:
13583 case NSAPI::NSOrderedSet_setObjectAtIndex:
13584 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13585 case NSAPI::NSOrderedSet_insertObjectAtIndex:
13586 return 0;
13587 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13588 return 1;
13589 }
13590
13591 return None;
13592}
13593
13594void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13595 if (!Message->isInstanceMessage()) {
13596 return;
13597 }
13598
13599 Optional<int> ArgOpt;
13600
13601 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13602 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13603 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13604 return;
13605 }
13606
13607 int ArgIndex = *ArgOpt;
13608
13609 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13610 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13611 Arg = OE->getSourceExpr()->IgnoreImpCasts();
13612 }
13613
13614 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13615 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13616 if (ArgRE->isObjCSelfExpr()) {
13617 Diag(Message->getSourceRange().getBegin(),
13618 diag::warn_objc_circular_container)
13619 << ArgRE->getDecl() << StringRef("'super'");
13620 }
13621 }
13622 } else {
13623 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13624
13625 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13626 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13627 }
13628
13629 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13630 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13631 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13632 ValueDecl *Decl = ReceiverRE->getDecl();
13633 Diag(Message->getSourceRange().getBegin(),
13634 diag::warn_objc_circular_container)
13635 << Decl << Decl;
13636 if (!ArgRE->isObjCSelfExpr()) {
13637 Diag(Decl->getLocation(),
13638 diag::note_objc_circular_container_declared_here)
13639 << Decl;
13640 }
13641 }
13642 }
13643 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13644 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13645 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13646 ObjCIvarDecl *Decl = IvarRE->getDecl();
13647 Diag(Message->getSourceRange().getBegin(),
13648 diag::warn_objc_circular_container)
13649 << Decl << Decl;
13650 Diag(Decl->getLocation(),
13651 diag::note_objc_circular_container_declared_here)
13652 << Decl;
13653 }
13654 }
13655 }
13656 }
13657}
13658
13659/// Check a message send to see if it's likely to cause a retain cycle.
13660void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13661 // Only check instance methods whose selector looks like a setter.
13662 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13663 return;
13664
13665 // Try to find a variable that the receiver is strongly owned by.
13666 RetainCycleOwner owner;
13667 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13668 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13669 return;
13670 } else {
13671 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance)((msg->getReceiverKind() == ObjCMessageExpr::SuperInstance
) ? static_cast<void> (0) : __assert_fail ("msg->getReceiverKind() == ObjCMessageExpr::SuperInstance"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 13671, __PRETTY_FUNCTION__))
;
13672 owner.Variable = getCurMethodDecl()->getSelfDecl();
13673 owner.Loc = msg->getSuperLoc();
13674 owner.Range = msg->getSuperLoc();
13675 }
13676
13677 // Check whether the receiver is captured by any of the arguments.
13678 const ObjCMethodDecl *MD = msg->getMethodDecl();
13679 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13680 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13681 // noescape blocks should not be retained by the method.
13682 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13683 continue;
13684 return diagnoseRetainCycle(*this, capturer, owner);
13685 }
13686 }
13687}
13688
13689/// Check a property assign to see if it's likely to cause a retain cycle.
13690void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13691 RetainCycleOwner owner;
13692 if (!findRetainCycleOwner(*this, receiver, owner))
13693 return;
13694
13695 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13696 diagnoseRetainCycle(*this, capturer, owner);
13697}
13698
13699void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13700 RetainCycleOwner Owner;
13701 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13702 return;
13703
13704 // Because we don't have an expression for the variable, we have to set the
13705 // location explicitly here.
13706 Owner.Loc = Var->getLocation();
13707 Owner.Range = Var->getSourceRange();
13708
13709 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13710 diagnoseRetainCycle(*this, Capturer, Owner);
13711}
13712
13713static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13714 Expr *RHS, bool isProperty) {
13715 // Check if RHS is an Objective-C object literal, which also can get
13716 // immediately zapped in a weak reference. Note that we explicitly
13717 // allow ObjCStringLiterals, since those are designed to never really die.
13718 RHS = RHS->IgnoreParenImpCasts();
13719
13720 // This enum needs to match with the 'select' in
13721 // warn_objc_arc_literal_assign (off-by-1).
13722 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13723 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13724 return false;
13725
13726 S.Diag(Loc, diag::warn_arc_literal_assign)
13727 << (unsigned) Kind
13728 << (isProperty ? 0 : 1)
13729 << RHS->getSourceRange();
13730
13731 return true;
13732}
13733
13734static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13735 Qualifiers::ObjCLifetime LT,
13736 Expr *RHS, bool isProperty) {
13737 // Strip off any implicit cast added to get to the one ARC-specific.
13738 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13739 if (cast->getCastKind() == CK_ARCConsumeObject) {
13740 S.Diag(Loc, diag::warn_arc_retained_assign)
13741 << (LT == Qualifiers::OCL_ExplicitNone)
13742 << (isProperty ? 0 : 1)
13743 << RHS->getSourceRange();
13744 return true;
13745 }
13746 RHS = cast->getSubExpr();
13747 }
13748
13749 if (LT == Qualifiers::OCL_Weak &&
13750 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13751 return true;
13752
13753 return false;
13754}
13755
13756bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13757 QualType LHS, Expr *RHS) {
13758 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13759
13760 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13761 return false;
13762
13763 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13764 return true;
13765
13766 return false;
13767}
13768
13769void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13770 Expr *LHS, Expr *RHS) {
13771 QualType LHSType;
13772 // PropertyRef on LHS type need be directly obtained from
13773 // its declaration as it has a PseudoType.
13774 ObjCPropertyRefExpr *PRE
13775 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13776 if (PRE && !PRE->isImplicitProperty()) {
13777 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13778 if (PD)
13779 LHSType = PD->getType();
13780 }
13781
13782 if (LHSType.isNull())
13783 LHSType = LHS->getType();
13784
13785 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13786
13787 if (LT == Qualifiers::OCL_Weak) {
13788 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13789 getCurFunction()->markSafeWeakUse(LHS);
13790 }
13791
13792 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13793 return;
13794
13795 // FIXME. Check for other life times.
13796 if (LT != Qualifiers::OCL_None)
13797 return;
13798
13799 if (PRE) {
13800 if (PRE->isImplicitProperty())
13801 return;
13802 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13803 if (!PD)
13804 return;
13805
13806 unsigned Attributes = PD->getPropertyAttributes();
13807 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13808 // when 'assign' attribute was not explicitly specified
13809 // by user, ignore it and rely on property type itself
13810 // for lifetime info.
13811 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13812 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13813 LHSType->isObjCRetainableType())
13814 return;
13815
13816 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13817 if (cast->getCastKind() == CK_ARCConsumeObject) {
13818 Diag(Loc, diag::warn_arc_retained_property_assign)
13819 << RHS->getSourceRange();
13820 return;
13821 }
13822 RHS = cast->getSubExpr();
13823 }
13824 }
13825 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13826 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13827 return;
13828 }
13829 }
13830}
13831
13832//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13833
13834static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13835 SourceLocation StmtLoc,
13836 const NullStmt *Body) {
13837 // Do not warn if the body is a macro that expands to nothing, e.g:
13838 //
13839 // #define CALL(x)
13840 // if (condition)
13841 // CALL(0);
13842 if (Body->hasLeadingEmptyMacro())
13843 return false;
13844
13845 // Get line numbers of statement and body.
13846 bool StmtLineInvalid;
13847 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13848 &StmtLineInvalid);
13849 if (StmtLineInvalid)
13850 return false;
13851
13852 bool BodyLineInvalid;
13853 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13854 &BodyLineInvalid);
13855 if (BodyLineInvalid)
13856 return false;
13857
13858 // Warn if null statement and body are on the same line.
13859 if (StmtLine != BodyLine)
13860 return false;
13861
13862 return true;
13863}
13864
13865void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13866 const Stmt *Body,
13867 unsigned DiagID) {
13868 // Since this is a syntactic check, don't emit diagnostic for template
13869 // instantiations, this just adds noise.
13870 if (CurrentInstantiationScope)
13871 return;
13872
13873 // The body should be a null statement.
13874 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13875 if (!NBody)
13876 return;
13877
13878 // Do the usual checks.
13879 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13880 return;
13881
13882 Diag(NBody->getSemiLoc(), DiagID);
13883 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13884}
13885
13886void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13887 const Stmt *PossibleBody) {
13888 assert(!CurrentInstantiationScope)((!CurrentInstantiationScope) ? static_cast<void> (0) :
__assert_fail ("!CurrentInstantiationScope", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 13888, __PRETTY_FUNCTION__))
; // Ensured by caller
13889
13890 SourceLocation StmtLoc;
13891 const Stmt *Body;
13892 unsigned DiagID;
13893 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13894 StmtLoc = FS->getRParenLoc();
13895 Body = FS->getBody();
13896 DiagID = diag::warn_empty_for_body;
13897 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13898 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13899 Body = WS->getBody();
13900 DiagID = diag::warn_empty_while_body;
13901 } else
13902 return; // Neither `for' nor `while'.
13903
13904 // The body should be a null statement.
13905 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13906 if (!NBody)
13907 return;
13908
13909 // Skip expensive checks if diagnostic is disabled.
13910 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13911 return;
13912
13913 // Do the usual checks.
13914 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13915 return;
13916
13917 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13918 // noise level low, emit diagnostics only if for/while is followed by a
13919 // CompoundStmt, e.g.:
13920 // for (int i = 0; i < n; i++);
13921 // {
13922 // a(i);
13923 // }
13924 // or if for/while is followed by a statement with more indentation
13925 // than for/while itself:
13926 // for (int i = 0; i < n; i++);
13927 // a(i);
13928 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13929 if (!ProbableTypo) {
13930 bool BodyColInvalid;
13931 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13932 PossibleBody->getBeginLoc(), &BodyColInvalid);
13933 if (BodyColInvalid)
13934 return;
13935
13936 bool StmtColInvalid;
13937 unsigned StmtCol =
13938 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13939 if (StmtColInvalid)
13940 return;
13941
13942 if (BodyCol > StmtCol)
13943 ProbableTypo = true;
13944 }
13945
13946 if (ProbableTypo) {
13947 Diag(NBody->getSemiLoc(), DiagID);
13948 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13949 }
13950}
13951
13952//===--- CHECK: Warn on self move with std::move. -------------------------===//
13953
13954/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13955void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13956 SourceLocation OpLoc) {
13957 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13958 return;
13959
13960 if (inTemplateInstantiation())
13961 return;
13962
13963 // Strip parens and casts away.
13964 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13965 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13966
13967 // Check for a call expression
13968 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13969 if (!CE || CE->getNumArgs() != 1)
13970 return;
13971
13972 // Check for a call to std::move
13973 if (!CE->isCallToStdMove())
13974 return;
13975
13976 // Get argument from std::move
13977 RHSExpr = CE->getArg(0);
13978
13979 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13980 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13981
13982 // Two DeclRefExpr's, check that the decls are the same.
13983 if (LHSDeclRef && RHSDeclRef) {
13984 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13985 return;
13986 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13987 RHSDeclRef->getDecl()->getCanonicalDecl())
13988 return;
13989
13990 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13991 << LHSExpr->getSourceRange()
13992 << RHSExpr->getSourceRange();
13993 return;
13994 }
13995
13996 // Member variables require a different approach to check for self moves.
13997 // MemberExpr's are the same if every nested MemberExpr refers to the same
13998 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13999 // the base Expr's are CXXThisExpr's.
14000 const Expr *LHSBase = LHSExpr;
14001 const Expr *RHSBase = RHSExpr;
14002 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14003 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14004 if (!LHSME || !RHSME)
14005 return;
14006
14007 while (LHSME && RHSME) {
14008 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14009 RHSME->getMemberDecl()->getCanonicalDecl())
14010 return;
14011
14012 LHSBase = LHSME->getBase();
14013 RHSBase = RHSME->getBase();
14014 LHSME = dyn_cast<MemberExpr>(LHSBase);
14015 RHSME = dyn_cast<MemberExpr>(RHSBase);
14016 }
14017
14018 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14019 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14020 if (LHSDeclRef && RHSDeclRef) {
14021 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14022 return;
14023 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14024 RHSDeclRef->getDecl()->getCanonicalDecl())
14025 return;
14026
14027 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14028 << LHSExpr->getSourceRange()
14029 << RHSExpr->getSourceRange();
14030 return;
14031 }
14032
14033 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14034 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14035 << LHSExpr->getSourceRange()
14036 << RHSExpr->getSourceRange();
14037}
14038
14039//===--- Layout compatibility ----------------------------------------------//
14040
14041static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14042
14043/// Check if two enumeration types are layout-compatible.
14044static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14045 // C++11 [dcl.enum] p8:
14046 // Two enumeration types are layout-compatible if they have the same
14047 // underlying type.
14048 return ED1->isComplete() && ED2->isComplete() &&
14049 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14050}
14051
14052/// Check if two fields are layout-compatible.
14053static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14054 FieldDecl *Field2) {
14055 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14056 return false;
14057
14058 if (Field1->isBitField() != Field2->isBitField())
14059 return false;
14060
14061 if (Field1->isBitField()) {
14062 // Make sure that the bit-fields are the same length.
14063 unsigned Bits1 = Field1->getBitWidthValue(C);
14064 unsigned Bits2 = Field2->getBitWidthValue(C);
14065
14066 if (Bits1 != Bits2)
14067 return false;
14068 }
14069
14070 return true;
14071}
14072
14073/// Check if two standard-layout structs are layout-compatible.
14074/// (C++11 [class.mem] p17)
14075static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14076 RecordDecl *RD2) {
14077 // If both records are C++ classes, check that base classes match.
14078 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14079 // If one of records is a CXXRecordDecl we are in C++ mode,
14080 // thus the other one is a CXXRecordDecl, too.
14081 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14082 // Check number of base classes.
14083 if (D1CXX->getNumBases() != D2CXX->getNumBases())
14084 return false;
14085
14086 // Check the base classes.
14087 for (CXXRecordDecl::base_class_const_iterator
14088 Base1 = D1CXX->bases_begin(),
14089 BaseEnd1 = D1CXX->bases_end(),
14090 Base2 = D2CXX->bases_begin();
14091 Base1 != BaseEnd1;
14092 ++Base1, ++Base2) {
14093 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14094 return false;
14095 }
14096 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14097 // If only RD2 is a C++ class, it should have zero base classes.
14098 if (D2CXX->getNumBases() > 0)
14099 return false;
14100 }
14101
14102 // Check the fields.
14103 RecordDecl::field_iterator Field2 = RD2->field_begin(),
14104 Field2End = RD2->field_end(),
14105 Field1 = RD1->field_begin(),
14106 Field1End = RD1->field_end();
14107 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14108 if (!isLayoutCompatible(C, *Field1, *Field2))
14109 return false;
14110 }
14111 if (Field1 != Field1End || Field2 != Field2End)
14112 return false;
14113
14114 return true;
14115}
14116
14117/// Check if two standard-layout unions are layout-compatible.
14118/// (C++11 [class.mem] p18)
14119static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14120 RecordDecl *RD2) {
14121 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14122 for (auto *Field2 : RD2->fields())
14123 UnmatchedFields.insert(Field2);
14124
14125 for (auto *Field1 : RD1->fields()) {
14126 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14127 I = UnmatchedFields.begin(),
14128 E = UnmatchedFields.end();
14129
14130 for ( ; I != E; ++I) {
14131 if (isLayoutCompatible(C, Field1, *I)) {
14132 bool Result = UnmatchedFields.erase(*I);
14133 (void) Result;
14134 assert(Result)((Result) ? static_cast<void> (0) : __assert_fail ("Result"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 14134, __PRETTY_FUNCTION__))
;
14135 break;
14136 }
14137 }
14138 if (I == E)
14139 return false;
14140 }
14141
14142 return UnmatchedFields.empty();
14143}
14144
14145static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14146 RecordDecl *RD2) {
14147 if (RD1->isUnion() != RD2->isUnion())
14148 return false;
14149
14150 if (RD1->isUnion())
14151 return isLayoutCompatibleUnion(C, RD1, RD2);
14152 else
14153 return isLayoutCompatibleStruct(C, RD1, RD2);
14154}
14155
14156/// Check if two types are layout-compatible in C++11 sense.
14157static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14158 if (T1.isNull() || T2.isNull())
14159 return false;
14160
14161 // C++11 [basic.types] p11:
14162 // If two types T1 and T2 are the same type, then T1 and T2 are
14163 // layout-compatible types.
14164 if (C.hasSameType(T1, T2))
14165 return true;
14166
14167 T1 = T1.getCanonicalType().getUnqualifiedType();
14168 T2 = T2.getCanonicalType().getUnqualifiedType();
14169
14170 const Type::TypeClass TC1 = T1->getTypeClass();
14171 const Type::TypeClass TC2 = T2->getTypeClass();
14172
14173 if (TC1 != TC2)
14174 return false;
14175
14176 if (TC1 == Type::Enum) {
14177 return isLayoutCompatible(C,
14178 cast<EnumType>(T1)->getDecl(),
14179 cast<EnumType>(T2)->getDecl());
14180 } else if (TC1 == Type::Record) {
14181 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14182 return false;
14183
14184 return isLayoutCompatible(C,
14185 cast<RecordType>(T1)->getDecl(),
14186 cast<RecordType>(T2)->getDecl());
14187 }
14188
14189 return false;
14190}
14191
14192//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14193
14194/// Given a type tag expression find the type tag itself.
14195///
14196/// \param TypeExpr Type tag expression, as it appears in user's code.
14197///
14198/// \param VD Declaration of an identifier that appears in a type tag.
14199///
14200/// \param MagicValue Type tag magic value.
14201///
14202/// \param isConstantEvaluated wether the evalaution should be performed in
14203
14204/// constant context.
14205static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14206 const ValueDecl **VD, uint64_t *MagicValue,
14207 bool isConstantEvaluated) {
14208 while(true) {
14209 if (!TypeExpr)
14210 return false;
14211
14212 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14213
14214 switch (TypeExpr->getStmtClass()) {
14215 case Stmt::UnaryOperatorClass: {
14216 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14217 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14218 TypeExpr = UO->getSubExpr();
14219 continue;
14220 }
14221 return false;
14222 }
14223
14224 case Stmt::DeclRefExprClass: {
14225 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14226 *VD = DRE->getDecl();
14227 return true;
14228 }
14229
14230 case Stmt::IntegerLiteralClass: {
14231 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14232 llvm::APInt MagicValueAPInt = IL->getValue();
14233 if (MagicValueAPInt.getActiveBits() <= 64) {
14234 *MagicValue = MagicValueAPInt.getZExtValue();
14235 return true;
14236 } else
14237 return false;
14238 }
14239
14240 case Stmt::BinaryConditionalOperatorClass:
14241 case Stmt::ConditionalOperatorClass: {
14242 const AbstractConditionalOperator *ACO =
14243 cast<AbstractConditionalOperator>(TypeExpr);
14244 bool Result;
14245 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14246 isConstantEvaluated)) {
14247 if (Result)
14248 TypeExpr = ACO->getTrueExpr();
14249 else
14250 TypeExpr = ACO->getFalseExpr();
14251 continue;
14252 }
14253 return false;
14254 }
14255
14256 case Stmt::BinaryOperatorClass: {
14257 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14258 if (BO->getOpcode() == BO_Comma) {
14259 TypeExpr = BO->getRHS();
14260 continue;
14261 }
14262 return false;
14263 }
14264
14265 default:
14266 return false;
14267 }
14268 }
14269}
14270
14271/// Retrieve the C type corresponding to type tag TypeExpr.
14272///
14273/// \param TypeExpr Expression that specifies a type tag.
14274///
14275/// \param MagicValues Registered magic values.
14276///
14277/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14278/// kind.
14279///
14280/// \param TypeInfo Information about the corresponding C type.
14281///
14282/// \param isConstantEvaluated wether the evalaution should be performed in
14283/// constant context.
14284///
14285/// \returns true if the corresponding C type was found.
14286static bool GetMatchingCType(
14287 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14288 const ASTContext &Ctx,
14289 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14290 *MagicValues,
14291 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14292 bool isConstantEvaluated) {
14293 FoundWrongKind = false;
14294
14295 // Variable declaration that has type_tag_for_datatype attribute.
14296 const ValueDecl *VD = nullptr;
14297
14298 uint64_t MagicValue;
14299
14300 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14301 return false;
14302
14303 if (VD) {
14304 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14305 if (I->getArgumentKind() != ArgumentKind) {
14306 FoundWrongKind = true;
14307 return false;
14308 }
14309 TypeInfo.Type = I->getMatchingCType();
14310 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14311 TypeInfo.MustBeNull = I->getMustBeNull();
14312 return true;
14313 }
14314 return false;
14315 }
14316
14317 if (!MagicValues)
14318 return false;
14319
14320 llvm::DenseMap<Sema::TypeTagMagicValue,
14321 Sema::TypeTagData>::const_iterator I =
14322 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14323 if (I == MagicValues->end())
14324 return false;
14325
14326 TypeInfo = I->second;
14327 return true;
14328}
14329
14330void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14331 uint64_t MagicValue, QualType Type,
14332 bool LayoutCompatible,
14333 bool MustBeNull) {
14334 if (!TypeTagForDatatypeMagicValues)
14335 TypeTagForDatatypeMagicValues.reset(
14336 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14337
14338 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14339 (*TypeTagForDatatypeMagicValues)[Magic] =
14340 TypeTagData(Type, LayoutCompatible, MustBeNull);
14341}
14342
14343static bool IsSameCharType(QualType T1, QualType T2) {
14344 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14345 if (!BT1)
14346 return false;
14347
14348 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14349 if (!BT2)
14350 return false;
14351
14352 BuiltinType::Kind T1Kind = BT1->getKind();
14353 BuiltinType::Kind T2Kind = BT2->getKind();
14354
14355 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14356 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14357 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14358 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14359}
14360
14361void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14362 const ArrayRef<const Expr *> ExprArgs,
14363 SourceLocation CallSiteLoc) {
14364 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14365 bool IsPointerAttr = Attr->getIsPointer();
14366
14367 // Retrieve the argument representing the 'type_tag'.
14368 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14369 if (TypeTagIdxAST >= ExprArgs.size()) {
14370 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14371 << 0 << Attr->getTypeTagIdx().getSourceIndex();
14372 return;
14373 }
14374 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14375 bool FoundWrongKind;
14376 TypeTagData TypeInfo;
14377 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14378 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14379 TypeInfo, isConstantEvaluated())) {
14380 if (FoundWrongKind)
14381 Diag(TypeTagExpr->getExprLoc(),
14382 diag::warn_type_tag_for_datatype_wrong_kind)
14383 << TypeTagExpr->getSourceRange();
14384 return;
14385 }
14386
14387 // Retrieve the argument representing the 'arg_idx'.
14388 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14389 if (ArgumentIdxAST >= ExprArgs.size()) {
14390 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14391 << 1 << Attr->getArgumentIdx().getSourceIndex();
14392 return;
14393 }
14394 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14395 if (IsPointerAttr) {
14396 // Skip implicit cast of pointer to `void *' (as a function argument).
14397 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14398 if (ICE->getType()->isVoidPointerType() &&
14399 ICE->getCastKind() == CK_BitCast)
14400 ArgumentExpr = ICE->getSubExpr();
14401 }
14402 QualType ArgumentType = ArgumentExpr->getType();
14403
14404 // Passing a `void*' pointer shouldn't trigger a warning.
14405 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14406 return;
14407
14408 if (TypeInfo.MustBeNull) {
14409 // Type tag with matching void type requires a null pointer.
14410 if (!ArgumentExpr->isNullPointerConstant(Context,
14411 Expr::NPC_ValueDependentIsNotNull)) {
14412 Diag(ArgumentExpr->getExprLoc(),
14413 diag::warn_type_safety_null_pointer_required)
14414 << ArgumentKind->getName()
14415 << ArgumentExpr->getSourceRange()
14416 << TypeTagExpr->getSourceRange();
14417 }
14418 return;
14419 }
14420
14421 QualType RequiredType = TypeInfo.Type;
14422 if (IsPointerAttr)
14423 RequiredType = Context.getPointerType(RequiredType);
14424
14425 bool mismatch = false;
14426 if (!TypeInfo.LayoutCompatible) {
14427 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14428
14429 // C++11 [basic.fundamental] p1:
14430 // Plain char, signed char, and unsigned char are three distinct types.
14431 //
14432 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14433 // char' depending on the current char signedness mode.
14434 if (mismatch)
14435 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14436 RequiredType->getPointeeType())) ||
14437 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14438 mismatch = false;
14439 } else
14440 if (IsPointerAttr)
14441 mismatch = !isLayoutCompatible(Context,
14442 ArgumentType->getPointeeType(),
14443 RequiredType->getPointeeType());
14444 else
14445 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14446
14447 if (mismatch)
14448 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14449 << ArgumentType << ArgumentKind
14450 << TypeInfo.LayoutCompatible << RequiredType
14451 << ArgumentExpr->getSourceRange()
14452 << TypeTagExpr->getSourceRange();
14453}
14454
14455void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14456 CharUnits Alignment) {
14457 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14458}
14459
14460void Sema::DiagnoseMisalignedMembers() {
14461 for (MisalignedMember &m : MisalignedMembers) {
14462 const NamedDecl *ND = m.RD;
14463 if (ND->getName().empty()) {
14464 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14465 ND = TD;
14466 }
14467 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14468 << m.MD << ND << m.E->getSourceRange();
14469 }
14470 MisalignedMembers.clear();
14471}
14472
14473void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14474 E = E->IgnoreParens();
14475 if (!T->isPointerType() && !T->isIntegerType())
14476 return;
14477 if (isa<UnaryOperator>(E) &&
14478 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14479 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14480 if (isa<MemberExpr>(Op)) {
14481 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14482 if (MA != MisalignedMembers.end() &&
14483 (T->isIntegerType() ||
14484 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14485 Context.getTypeAlignInChars(
14486 T->getPointeeType()) <= MA->Alignment))))
14487 MisalignedMembers.erase(MA);
14488 }
14489 }
14490}
14491
14492void Sema::RefersToMemberWithReducedAlignment(
14493 Expr *E,
14494 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14495 Action) {
14496 const auto *ME = dyn_cast<MemberExpr>(E);
14497 if (!ME)
14498 return;
14499
14500 // No need to check expressions with an __unaligned-qualified type.
14501 if (E->getType().getQualifiers().hasUnaligned())
14502 return;
14503
14504 // For a chain of MemberExpr like "a.b.c.d" this list
14505 // will keep FieldDecl's like [d, c, b].
14506 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14507 const MemberExpr *TopME = nullptr;
14508 bool AnyIsPacked = false;
14509 do {
14510 QualType BaseType = ME->getBase()->getType();
14511 if (ME->isArrow())
14512 BaseType = BaseType->getPointeeType();
14513 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
14514 if (RD->isInvalidDecl())
14515 return;
14516
14517 ValueDecl *MD = ME->getMemberDecl();
14518 auto *FD = dyn_cast<FieldDecl>(MD);
14519 // We do not care about non-data members.
14520 if (!FD || FD->isInvalidDecl())
14521 return;
14522
14523 AnyIsPacked =
14524 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14525 ReverseMemberChain.push_back(FD);
14526
14527 TopME = ME;
14528 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14529 } while (ME);
14530 assert(TopME && "We did not compute a topmost MemberExpr!")((TopME && "We did not compute a topmost MemberExpr!"
) ? static_cast<void> (0) : __assert_fail ("TopME && \"We did not compute a topmost MemberExpr!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 14530, __PRETTY_FUNCTION__))
;
14531
14532 // Not the scope of this diagnostic.
14533 if (!AnyIsPacked)
14534 return;
14535
14536 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14537 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14538 // TODO: The innermost base of the member expression may be too complicated.
14539 // For now, just disregard these cases. This is left for future
14540 // improvement.
14541 if (!DRE && !isa<CXXThisExpr>(TopBase))
14542 return;
14543
14544 // Alignment expected by the whole expression.
14545 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14546
14547 // No need to do anything else with this case.
14548 if (ExpectedAlignment.isOne())
14549 return;
14550
14551 // Synthesize offset of the whole access.
14552 CharUnits Offset;
14553 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14554 I++) {
14555 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14556 }
14557
14558 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14559 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14560 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14561
14562 // The base expression of the innermost MemberExpr may give
14563 // stronger guarantees than the class containing the member.
14564 if (DRE && !TopME->isArrow()) {
14565 const ValueDecl *VD = DRE->getDecl();
14566 if (!VD->getType()->isReferenceType())
14567 CompleteObjectAlignment =
14568 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14569 }
14570
14571 // Check if the synthesized offset fulfills the alignment.
14572 if (Offset % ExpectedAlignment != 0 ||
14573 // It may fulfill the offset it but the effective alignment may still be
14574 // lower than the expected expression alignment.
14575 CompleteObjectAlignment < ExpectedAlignment) {
14576 // If this happens, we want to determine a sensible culprit of this.
14577 // Intuitively, watching the chain of member expressions from right to
14578 // left, we start with the required alignment (as required by the field
14579 // type) but some packed attribute in that chain has reduced the alignment.
14580 // It may happen that another packed structure increases it again. But if
14581 // we are here such increase has not been enough. So pointing the first
14582 // FieldDecl that either is packed or else its RecordDecl is,
14583 // seems reasonable.
14584 FieldDecl *FD = nullptr;
14585 CharUnits Alignment;
14586 for (FieldDecl *FDI : ReverseMemberChain) {
14587 if (FDI->hasAttr<PackedAttr>() ||
14588 FDI->getParent()->hasAttr<PackedAttr>()) {
14589 FD = FDI;
14590 Alignment = std::min(
14591 Context.getTypeAlignInChars(FD->getType()),
14592 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14593 break;
14594 }
14595 }
14596 assert(FD && "We did not find a packed FieldDecl!")((FD && "We did not find a packed FieldDecl!") ? static_cast
<void> (0) : __assert_fail ("FD && \"We did not find a packed FieldDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaChecking.cpp"
, 14596, __PRETTY_FUNCTION__))
;
14597 Action(E, FD->getParent(), FD, Alignment);
14598 }
14599}
14600
14601void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14602 using namespace std::placeholders;
14603
14604 RefersToMemberWithReducedAlignment(
14605 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14606 _2, _3, _4));
14607}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- 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/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class BuiltinTypeBitfields {
1517 friend class BuiltinType;
1518
1519 unsigned : NumTypeBits;
1520
1521 /// The kind (BuiltinType::Kind) of builtin type this is.
1522 unsigned Kind : 8;
1523 };
1524
1525 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1526 /// Only common bits are stored here. Additional uncommon bits are stored
1527 /// in a trailing object after FunctionProtoType.
1528 class FunctionTypeBitfields {
1529 friend class FunctionProtoType;
1530 friend class FunctionType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// Extra information which affects how the function is called, like
1535 /// regparm and the calling convention.
1536 unsigned ExtInfo : 12;
1537
1538 /// The ref-qualifier associated with a \c FunctionProtoType.
1539 ///
1540 /// This is a value of type \c RefQualifierKind.
1541 unsigned RefQualifier : 2;
1542
1543 /// Used only by FunctionProtoType, put here to pack with the
1544 /// other bitfields.
1545 /// The qualifiers are part of FunctionProtoType because...
1546 ///
1547 /// C++ 8.3.5p4: The return type, the parameter type list and the
1548 /// cv-qualifier-seq, [...], are part of the function type.
1549 unsigned FastTypeQuals : Qualifiers::FastWidth;
1550 /// Whether this function has extended Qualifiers.
1551 unsigned HasExtQuals : 1;
1552
1553 /// The number of parameters this function has, not counting '...'.
1554 /// According to [implimits] 8 bits should be enough here but this is
1555 /// somewhat easy to exceed with metaprogramming and so we would like to
1556 /// keep NumParams as wide as reasonably possible.
1557 unsigned NumParams : 16;
1558
1559 /// The type of exception specification this function has.
1560 unsigned ExceptionSpecType : 4;
1561
1562 /// Whether this function has extended parameter information.
1563 unsigned HasExtParameterInfos : 1;
1564
1565 /// Whether the function is variadic.
1566 unsigned Variadic : 1;
1567
1568 /// Whether this function has a trailing return type.
1569 unsigned HasTrailingReturn : 1;
1570 };
1571
1572 class ObjCObjectTypeBitfields {
1573 friend class ObjCObjectType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The number of type arguments stored directly on this object type.
1578 unsigned NumTypeArgs : 7;
1579
1580 /// The number of protocols stored directly on this object type.
1581 unsigned NumProtocols : 6;
1582
1583 /// Whether this is a "kindof" type.
1584 unsigned IsKindOf : 1;
1585 };
1586
1587 class ReferenceTypeBitfields {
1588 friend class ReferenceType;
1589
1590 unsigned : NumTypeBits;
1591
1592 /// True if the type was originally spelled with an lvalue sigil.
1593 /// This is never true of rvalue references but can also be false
1594 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// as follows:
1596 ///
1597 /// typedef int &ref; // lvalue, spelled lvalue
1598 /// typedef int &&rvref; // rvalue
1599 /// ref &a; // lvalue, inner ref, spelled lvalue
1600 /// ref &&a; // lvalue, inner ref
1601 /// rvref &a; // lvalue, inner ref, spelled lvalue
1602 /// rvref &&a; // rvalue, inner ref
1603 unsigned SpelledAsLValue : 1;
1604
1605 /// True if the inner type is a reference type. This only happens
1606 /// in non-canonical forms.
1607 unsigned InnerRef : 1;
1608 };
1609
1610 class TypeWithKeywordBitfields {
1611 friend class TypeWithKeyword;
1612
1613 unsigned : NumTypeBits;
1614
1615 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1616 unsigned Keyword : 8;
1617 };
1618
1619 enum { NumTypeWithKeywordBits = 8 };
1620
1621 class ElaboratedTypeBitfields {
1622 friend class ElaboratedType;
1623
1624 unsigned : NumTypeBits;
1625 unsigned : NumTypeWithKeywordBits;
1626
1627 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1628 unsigned HasOwnedTagDecl : 1;
1629 };
1630
1631 class VectorTypeBitfields {
1632 friend class VectorType;
1633 friend class DependentVectorType;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// The kind of vector, either a generic vector type or some
1638 /// target-specific vector type such as for AltiVec or Neon.
1639 unsigned VecKind : 3;
1640
1641 /// The number of elements in the vector.
1642 unsigned NumElements : 29 - NumTypeBits;
1643
1644 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 };
1646
1647 class AttributedTypeBitfields {
1648 friend class AttributedType;
1649
1650 unsigned : NumTypeBits;
1651
1652 /// An AttributedType::Kind
1653 unsigned AttrKind : 32 - NumTypeBits;
1654 };
1655
1656 class AutoTypeBitfields {
1657 friend class AutoType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1662 /// or '__auto_type'? AutoTypeKeyword value.
1663 unsigned Keyword : 2;
1664 };
1665
1666 class SubstTemplateTypeParmPackTypeBitfields {
1667 friend class SubstTemplateTypeParmPackType;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// The number of template arguments in \c Arguments, which is
1672 /// expected to be able to hold at least 1024 according to [implimits].
1673 /// However as this limit is somewhat easy to hit with template
1674 /// metaprogramming we'd prefer to keep it as large as possible.
1675 /// At the moment it has been left as a non-bitfield since this type
1676 /// safely fits in 64 bits as an unsigned, so there is no reason to
1677 /// introduce the performance impact of a bitfield.
1678 unsigned NumArgs;
1679 };
1680
1681 class TemplateSpecializationTypeBitfields {
1682 friend class TemplateSpecializationType;
1683
1684 unsigned : NumTypeBits;
1685
1686 /// Whether this template specialization type is a substituted type alias.
1687 unsigned TypeAlias : 1;
1688
1689 /// The number of template arguments named in this class template
1690 /// specialization, which is expected to be able to hold at least 1024
1691 /// according to [implimits]. However, as this limit is somewhat easy to
1692 /// hit with template metaprogramming we'd prefer to keep it as large
1693 /// as possible. At the moment it has been left as a non-bitfield since
1694 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1695 /// to introduce the performance impact of a bitfield.
1696 unsigned NumArgs;
1697 };
1698
1699 class DependentTemplateSpecializationTypeBitfields {
1700 friend class DependentTemplateSpecializationType;
1701
1702 unsigned : NumTypeBits;
1703 unsigned : NumTypeWithKeywordBits;
1704
1705 /// The number of template arguments named in this class template
1706 /// specialization, which is expected to be able to hold at least 1024
1707 /// according to [implimits]. However, as this limit is somewhat easy to
1708 /// hit with template metaprogramming we'd prefer to keep it as large
1709 /// as possible. At the moment it has been left as a non-bitfield since
1710 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1711 /// to introduce the performance impact of a bitfield.
1712 unsigned NumArgs;
1713 };
1714
1715 class PackExpansionTypeBitfields {
1716 friend class PackExpansionType;
1717
1718 unsigned : NumTypeBits;
1719
1720 /// The number of expansions that this pack expansion will
1721 /// generate when substituted (+1), which is expected to be able to
1722 /// hold at least 1024 according to [implimits]. However, as this limit
1723 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1724 /// keep it as large as possible. At the moment it has been left as a
1725 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1726 /// there is no reason to introduce the performance impact of a bitfield.
1727 ///
1728 /// This field will only have a non-zero value when some of the parameter
1729 /// packs that occur within the pattern have been substituted but others
1730 /// have not.
1731 unsigned NumExpansions;
1732 };
1733
1734 union {
1735 TypeBitfields TypeBits;
1736 ArrayTypeBitfields ArrayTypeBits;
1737 AttributedTypeBitfields AttributedTypeBits;
1738 AutoTypeBitfields AutoTypeBits;
1739 BuiltinTypeBitfields BuiltinTypeBits;
1740 FunctionTypeBitfields FunctionTypeBits;
1741 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1742 ReferenceTypeBitfields ReferenceTypeBits;
1743 TypeWithKeywordBitfields TypeWithKeywordBits;
1744 ElaboratedTypeBitfields ElaboratedTypeBits;
1745 VectorTypeBitfields VectorTypeBits;
1746 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1747 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1748 DependentTemplateSpecializationTypeBitfields
1749 DependentTemplateSpecializationTypeBits;
1750 PackExpansionTypeBitfields PackExpansionTypeBits;
1751
1752 static_assert(sizeof(TypeBitfields) <= 8,
1753 "TypeBitfields is larger than 8 bytes!");
1754 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1755 "ArrayTypeBitfields is larger than 8 bytes!");
1756 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1757 "AttributedTypeBitfields is larger than 8 bytes!");
1758 static_assert(sizeof(AutoTypeBitfields) <= 8,
1759 "AutoTypeBitfields is larger than 8 bytes!");
1760 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1761 "BuiltinTypeBitfields is larger than 8 bytes!");
1762 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1763 "FunctionTypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1765 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1767 "ReferenceTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1769 "TypeWithKeywordBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1771 "ElaboratedTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(VectorTypeBitfields) <= 8,
1773 "VectorTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1775 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 " than 8 bytes!");
1777 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1778 "TemplateSpecializationTypeBitfields is larger"
1779 " than 8 bytes!");
1780 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1781 "DependentTemplateSpecializationTypeBitfields is larger"
1782 " than 8 bytes!");
1783 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1784 "PackExpansionTypeBitfields is larger than 8 bytes");
1785 };
1786
1787private:
1788 template <class T> friend class TypePropertyCache;
1789
1790 /// Set whether this type comes from an AST file.
1791 void setFromAST(bool V = true) const {
1792 TypeBits.FromAST = V;
1793 }
1794
1795protected:
1796 friend class ASTContext;
1797
1798 Type(TypeClass tc, QualType canon, bool Dependent,
1799 bool InstantiationDependent, bool VariablyModified,
1800 bool ContainsUnexpandedParameterPack)
1801 : ExtQualsTypeCommonBase(this,
1802 canon.isNull() ? QualType(this_(), 0) : canon) {
1803 TypeBits.TC = tc;
1804 TypeBits.Dependent = Dependent;
1805 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1806 TypeBits.VariablyModified = VariablyModified;
1807 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1808 TypeBits.CacheValid = false;
1809 TypeBits.CachedLocalOrUnnamed = false;
1810 TypeBits.CachedLinkage = NoLinkage;
1811 TypeBits.FromAST = false;
1812 }
1813
1814 // silence VC++ warning C4355: 'this' : used in base member initializer list
1815 Type *this_() { return this; }
1816
1817 void setDependent(bool D = true) {
1818 TypeBits.Dependent = D;
1819 if (D)
1820 TypeBits.InstantiationDependent = true;
1821 }
1822
1823 void setInstantiationDependent(bool D = true) {
1824 TypeBits.InstantiationDependent = D; }
1825
1826 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1827
1828 void setContainsUnexpandedParameterPack(bool PP = true) {
1829 TypeBits.ContainsUnexpandedParameterPack = PP;
1830 }
1831
1832public:
1833 friend class ASTReader;
1834 friend class ASTWriter;
1835
1836 Type(const Type &) = delete;
1837 Type(Type &&) = delete;
1838 Type &operator=(const Type &) = delete;
1839 Type &operator=(Type &&) = delete;
1840
1841 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1842
1843 /// Whether this type comes from an AST file.
1844 bool isFromAST() const { return TypeBits.FromAST; }
1845
1846 /// Whether this type is or contains an unexpanded parameter
1847 /// pack, used to support C++0x variadic templates.
1848 ///
1849 /// A type that contains a parameter pack shall be expanded by the
1850 /// ellipsis operator at some point. For example, the typedef in the
1851 /// following example contains an unexpanded parameter pack 'T':
1852 ///
1853 /// \code
1854 /// template<typename ...T>
1855 /// struct X {
1856 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1857 /// };
1858 /// \endcode
1859 ///
1860 /// Note that this routine does not specify which
1861 bool containsUnexpandedParameterPack() const {
1862 return TypeBits.ContainsUnexpandedParameterPack;
1863 }
1864
1865 /// Determines if this type would be canonical if it had no further
1866 /// qualification.
1867 bool isCanonicalUnqualified() const {
1868 return CanonicalType == QualType(this, 0);
1869 }
1870
1871 /// Pull a single level of sugar off of this locally-unqualified type.
1872 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1873 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1874 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1875
1876 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1877 /// object types, function types, and incomplete types.
1878
1879 /// Return true if this is an incomplete type.
1880 /// A type that can describe objects, but which lacks information needed to
1881 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1882 /// routine will need to determine if the size is actually required.
1883 ///
1884 /// Def If non-null, and the type refers to some kind of declaration
1885 /// that can be completed (such as a C struct, C++ class, or Objective-C
1886 /// class), will be set to the declaration.
1887 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1888
1889 /// Return true if this is an incomplete or object
1890 /// type, in other words, not a function type.
1891 bool isIncompleteOrObjectType() const {
1892 return !isFunctionType();
1893 }
1894
1895 /// Determine whether this type is an object type.
1896 bool isObjectType() const {
1897 // C++ [basic.types]p8:
1898 // An object type is a (possibly cv-qualified) type that is not a
1899 // function type, not a reference type, and not a void type.
1900 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 }
1902
1903 /// Return true if this is a literal type
1904 /// (C++11 [basic.types]p10)
1905 bool isLiteralType(const ASTContext &Ctx) const;
1906
1907 /// Test if this type is a standard-layout type.
1908 /// (C++0x [basic.type]p9)
1909 bool isStandardLayoutType() const;
1910
1911 /// Helper methods to distinguish type categories. All type predicates
1912 /// operate on the canonical type, ignoring typedefs and qualifiers.
1913
1914 /// Returns true if the type is a builtin type.
1915 bool isBuiltinType() const;
1916
1917 /// Test for a particular builtin type.
1918 bool isSpecificBuiltinType(unsigned K) const;
1919
1920 /// Test for a type which does not represent an actual type-system type but
1921 /// is instead used as a placeholder for various convenient purposes within
1922 /// Clang. All such types are BuiltinTypes.
1923 bool isPlaceholderType() const;
1924 const BuiltinType *getAsPlaceholderType() const;
1925
1926 /// Test for a specific placeholder type.
1927 bool isSpecificPlaceholderType(unsigned K) const;
1928
1929 /// Test for a placeholder type other than Overload; see
1930 /// BuiltinType::isNonOverloadPlaceholderType.
1931 bool isNonOverloadPlaceholderType() const;
1932
1933 /// isIntegerType() does *not* include complex integers (a GCC extension).
1934 /// isComplexIntegerType() can be used to test for complex integers.
1935 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1936 bool isEnumeralType() const;
1937
1938 /// Determine whether this type is a scoped enumeration type.
1939 bool isScopedEnumeralType() const;
1940 bool isBooleanType() const;
1941 bool isCharType() const;
1942 bool isWideCharType() const;
1943 bool isChar8Type() const;
1944 bool isChar16Type() const;
1945 bool isChar32Type() const;
1946 bool isAnyCharacterType() const;
1947 bool isIntegralType(const ASTContext &Ctx) const;
1948
1949 /// Determine whether this type is an integral or enumeration type.
1950 bool isIntegralOrEnumerationType() const;
1951
1952 /// Determine whether this type is an integral or unscoped enumeration type.
1953 bool isIntegralOrUnscopedEnumerationType() const;
1954
1955 /// Floating point categories.
1956 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1957 /// isComplexType() does *not* include complex integers (a GCC extension).
1958 /// isComplexIntegerType() can be used to test for complex integers.
1959 bool isComplexType() const; // C99 6.2.5p11 (complex)
1960 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1961 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1962 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1963 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1964 bool isFloat128Type() const;
1965 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1966 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1967 bool isVoidType() const; // C99 6.2.5p19
1968 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1969 bool isAggregateType() const;
1970 bool isFundamentalType() const;
1971 bool isCompoundType() const;
1972
1973 // Type Predicates: Check to see if this type is structurally the specified
1974 // type, ignoring typedefs and qualifiers.
1975 bool isFunctionType() const;
1976 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1977 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1978 bool isPointerType() const;
1979 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1980 bool isBlockPointerType() const;
1981 bool isVoidPointerType() const;
1982 bool isReferenceType() const;
1983 bool isLValueReferenceType() const;
1984 bool isRValueReferenceType() const;
1985 bool isFunctionPointerType() const;
1986 bool isFunctionReferenceType() const;
1987 bool isMemberPointerType() const;
1988 bool isMemberFunctionPointerType() const;
1989 bool isMemberDataPointerType() const;
1990 bool isArrayType() const;
1991 bool isConstantArrayType() const;
1992 bool isIncompleteArrayType() const;
1993 bool isVariableArrayType() const;
1994 bool isDependentSizedArrayType() const;
1995 bool isRecordType() const;
1996 bool isClassType() const;
1997 bool isStructureType() const;
1998 bool isObjCBoxableRecordType() const;
1999 bool isInterfaceType() const;
2000 bool isStructureOrClassType() const;
2001 bool isUnionType() const;
2002 bool isComplexIntegerType() const; // GCC _Complex integer type.
2003 bool isVectorType() const; // GCC vector type.
2004 bool isExtVectorType() const; // Extended vector type.
2005 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2006 bool isObjCObjectPointerType() const; // pointer to ObjC object
2007 bool isObjCRetainableType() const; // ObjC object or block pointer
2008 bool isObjCLifetimeType() const; // (array of)* retainable type
2009 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2010 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2011 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2012 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2013 // for the common case.
2014 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2015 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2016 bool isObjCQualifiedIdType() const; // id<foo>
2017 bool isObjCQualifiedClassType() const; // Class<foo>
2018 bool isObjCObjectOrInterfaceType() const;
2019 bool isObjCIdType() const; // id
2020 bool isDecltypeType() const;
2021 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// qualifier?
2023 ///
2024 /// This approximates the answer to the following question: if this
2025 /// translation unit were compiled in ARC, would this type be qualified
2026 /// with __unsafe_unretained?
2027 bool isObjCInertUnsafeUnretainedType() const {
2028 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 }
2030
2031 /// Whether the type is Objective-C 'id' or a __kindof type of an
2032 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// <NSCopying>.
2034 ///
2035 /// \param bound Will be set to the bound on non-id subtype types,
2036 /// which will be (possibly specialized) Objective-C class type, or
2037 /// null for 'id.
2038 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2039 const ObjCObjectType *&bound) const;
2040
2041 bool isObjCClassType() const; // Class
2042
2043 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2044 /// Class type, e.g., __kindof Class <NSCopying>.
2045 ///
2046 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2047 /// here because Objective-C's type system cannot express "a class
2048 /// object for a subclass of NSFoo".
2049 bool isObjCClassOrClassKindOfType() const;
2050
2051 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2052 bool isObjCSelType() const; // Class
2053 bool isObjCBuiltinType() const; // 'id' or 'Class'
2054 bool isObjCARCBridgableType() const;
2055 bool isCARCBridgableType() const;
2056 bool isTemplateTypeParmType() const; // C++ template type parameter
2057 bool isNullPtrType() const; // C++11 std::nullptr_t
2058 bool isNothrowT() const; // C++ std::nothrow_t
2059 bool isAlignValT() const; // C++17 std::align_val_t
2060 bool isStdByteType() const; // C++17 std::byte
2061 bool isAtomicType() const; // C11 _Atomic()
2062
2063#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2064 bool is##Id##Type() const;
2065#include "clang/Basic/OpenCLImageTypes.def"
2066
2067 bool isImageType() const; // Any OpenCL image type
2068
2069 bool isSamplerT() const; // OpenCL sampler_t
2070 bool isEventT() const; // OpenCL event_t
2071 bool isClkEventT() const; // OpenCL clk_event_t
2072 bool isQueueT() const; // OpenCL queue_t
2073 bool isReserveIDT() const; // OpenCL reserve_id_t
2074
2075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2076 bool is##Id##Type() const;
2077#include "clang/Basic/OpenCLExtensionTypes.def"
2078 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2079 bool isOCLIntelSubgroupAVCType() const;
2080 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2081
2082 bool isPipeType() const; // OpenCL pipe type
2083 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2084
2085 /// Determines if this type, which must satisfy
2086 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2087 /// than implicitly __strong.
2088 bool isObjCARCImplicitlyUnretainedType() const;
2089
2090 /// Return the implicit lifetime for this type, which must not be dependent.
2091 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2092
2093 enum ScalarTypeKind {
2094 STK_CPointer,
2095 STK_BlockPointer,
2096 STK_ObjCObjectPointer,
2097 STK_MemberPointer,
2098 STK_Bool,
2099 STK_Integral,
2100 STK_Floating,
2101 STK_IntegralComplex,
2102 STK_FloatingComplex,
2103 STK_FixedPoint
2104 };
2105
2106 /// Given that this is a scalar type, classify it.
2107 ScalarTypeKind getScalarTypeKind() const;
2108
2109 /// Whether this type is a dependent type, meaning that its definition
2110 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2111 bool isDependentType() const { return TypeBits.Dependent; }
2112
2113 /// Determine whether this type is an instantiation-dependent type,
2114 /// meaning that the type involves a template parameter (even if the
2115 /// definition does not actually depend on the type substituted for that
2116 /// template parameter).
2117 bool isInstantiationDependentType() const {
2118 return TypeBits.InstantiationDependent;
2119 }
2120
2121 /// Determine whether this type is an undeduced type, meaning that
2122 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2123 /// deduced.
2124 bool isUndeducedType() const;
2125
2126 /// Whether this type is a variably-modified type (C99 6.7.5).
2127 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2128
2129 /// Whether this type involves a variable-length array type
2130 /// with a definite size.
2131 bool hasSizedVLAType() const;
2132
2133 /// Whether this type is or contains a local or unnamed type.
2134 bool hasUnnamedOrLocalType() const;
2135
2136 bool isOverloadableType() const;
2137
2138 /// Determine wither this type is a C++ elaborated-type-specifier.
2139 bool isElaboratedTypeSpecifier() const;
2140
2141 bool canDecayToPointerType() const;
2142
2143 /// Whether this type is represented natively as a pointer. This includes
2144 /// pointers, references, block pointers, and Objective-C interface,
2145 /// qualified id, and qualified interface types, as well as nullptr_t.
2146 bool hasPointerRepresentation() const;
2147
2148 /// Whether this type can represent an objective pointer type for the
2149 /// purpose of GC'ability
2150 bool hasObjCPointerRepresentation() const;
2151
2152 /// Determine whether this type has an integer representation
2153 /// of some sort, e.g., it is an integer type or a vector.
2154 bool hasIntegerRepresentation() const;
2155
2156 /// Determine whether this type has an signed integer representation
2157 /// of some sort, e.g., it is an signed integer type or a vector.
2158 bool hasSignedIntegerRepresentation() const;
2159
2160 /// Determine whether this type has an unsigned integer representation
2161 /// of some sort, e.g., it is an unsigned integer type or a vector.
2162 bool hasUnsignedIntegerRepresentation() const;
2163
2164 /// Determine whether this type has a floating-point representation
2165 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2166 bool hasFloatingRepresentation() const;
2167
2168 // Type Checking Functions: Check to see if this type is structurally the
2169 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2170 // the best type we can.
2171 const RecordType *getAsStructureType() const;
2172 /// NOTE: getAs*ArrayType are methods on ASTContext.
2173 const RecordType *getAsUnionType() const;
2174 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2175 const ObjCObjectType *getAsObjCInterfaceType() const;
2176
2177 // The following is a convenience method that returns an ObjCObjectPointerType
2178 // for object declared using an interface.
2179 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2180 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2181 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2182 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2183
2184 /// Retrieves the CXXRecordDecl that this type refers to, either
2185 /// because the type is a RecordType or because it is the injected-class-name
2186 /// type of a class template or class template partial specialization.
2187 CXXRecordDecl *getAsCXXRecordDecl() const;
2188
2189 /// Retrieves the RecordDecl this type refers to.
2190 RecordDecl *getAsRecordDecl() const;
2191
2192 /// Retrieves the TagDecl that this type refers to, either
2193 /// because the type is a TagType or because it is the injected-class-name
2194 /// type of a class template or class template partial specialization.
2195 TagDecl *getAsTagDecl() const;
2196
2197 /// If this is a pointer or reference to a RecordType, return the
2198 /// CXXRecordDecl that the type refers to.
2199 ///
2200 /// If this is not a pointer or reference, or the type being pointed to does
2201 /// not refer to a CXXRecordDecl, returns NULL.
2202 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2203
2204 /// Get the DeducedType whose type will be deduced for a variable with
2205 /// an initializer of this type. This looks through declarators like pointer
2206 /// types, but not through decltype or typedefs.
2207 DeducedType *getContainedDeducedType() const;
2208
2209 /// Get the AutoType whose type will be deduced for a variable with
2210 /// an initializer of this type. This looks through declarators like pointer
2211 /// types, but not through decltype or typedefs.
2212 AutoType *getContainedAutoType() const {
2213 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2214 }
2215
2216 /// Determine whether this type was written with a leading 'auto'
2217 /// corresponding to a trailing return type (possibly for a nested
2218 /// function type within a pointer to function type or similar).
2219 bool hasAutoForTrailingReturnType() const;
2220
2221 /// Member-template getAs<specific type>'. Look through sugar for
2222 /// an instance of \<specific type>. This scheme will eventually
2223 /// replace the specific getAsXXXX methods above.
2224 ///
2225 /// There are some specializations of this member template listed
2226 /// immediately following this class.
2227 template <typename T> const T *getAs() const;
2228
2229 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2230 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2231 /// This is used when you need to walk over sugar nodes that represent some
2232 /// kind of type adjustment from a type that was written as a \<specific type>
2233 /// to another type that is still canonically a \<specific type>.
2234 template <typename T> const T *getAsAdjusted() const;
2235
2236 /// A variant of getAs<> for array types which silently discards
2237 /// qualifiers from the outermost type.
2238 const ArrayType *getAsArrayTypeUnsafe() const;
2239
2240 /// Member-template castAs<specific type>. Look through sugar for
2241 /// the underlying instance of \<specific type>.
2242 ///
2243 /// This method has the same relationship to getAs<T> as cast<T> has
2244 /// to dyn_cast<T>; which is to say, the underlying type *must*
2245 /// have the intended type, and this method will never return null.
2246 template <typename T> const T *castAs() const;
2247
2248 /// A variant of castAs<> for array type which silently discards
2249 /// qualifiers from the outermost type.
2250 const ArrayType *castAsArrayTypeUnsafe() const;
2251
2252 /// Determine whether this type had the specified attribute applied to it
2253 /// (looking through top-level type sugar).
2254 bool hasAttr(attr::Kind AK) const;
2255
2256 /// Get the base element type of this type, potentially discarding type
2257 /// qualifiers. This should never be used when type qualifiers
2258 /// are meaningful.
2259 const Type *getBaseElementTypeUnsafe() const;
2260
2261 /// If this is an array type, return the element type of the array,
2262 /// potentially with type qualifiers missing.
2263 /// This should never be used when type qualifiers are meaningful.
2264 const Type *getArrayElementTypeNoTypeQual() const;
2265
2266 /// If this is a pointer type, return the pointee type.
2267 /// If this is an array type, return the array element type.
2268 /// This should never be used when type qualifiers are meaningful.
2269 const Type *getPointeeOrArrayElementType() const;
2270
2271 /// If this is a pointer, ObjC object pointer, or block
2272 /// pointer, this returns the respective pointee.
2273 QualType getPointeeType() const;
2274
2275 /// Return the specified type with any "sugar" removed from the type,
2276 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2277 const Type *getUnqualifiedDesugaredType() const;
2278
2279 /// More type predicates useful for type checking/promotion
2280 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2281
2282 /// Return true if this is an integer type that is
2283 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2284 /// or an enum decl which has a signed representation.
2285 bool isSignedIntegerType() const;
2286
2287 /// Return true if this is an integer type that is
2288 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2289 /// or an enum decl which has an unsigned representation.
2290 bool isUnsignedIntegerType() const;
2291
2292 /// Determines whether this is an integer type that is signed or an
2293 /// enumeration types whose underlying type is a signed integer type.
2294 bool isSignedIntegerOrEnumerationType() const;
2295
2296 /// Determines whether this is an integer type that is unsigned or an
2297 /// enumeration types whose underlying type is a unsigned integer type.
2298 bool isUnsignedIntegerOrEnumerationType() const;
2299
2300 /// Return true if this is a fixed point type according to
2301 /// ISO/IEC JTC1 SC22 WG14 N1169.
2302 bool isFixedPointType() const;
2303
2304 /// Return true if this is a fixed point or integer type.
2305 bool isFixedPointOrIntegerType() const;
2306
2307 /// Return true if this is a saturated fixed point type according to
2308 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2309 bool isSaturatedFixedPointType() const;
2310
2311 /// Return true if this is a saturated fixed point type according to
2312 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2313 bool isUnsaturatedFixedPointType() const;
2314
2315 /// Return true if this is a fixed point type that is signed according
2316 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2317 bool isSignedFixedPointType() const;
2318
2319 /// Return true if this is a fixed point type that is unsigned according
2320 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2321 bool isUnsignedFixedPointType() const;
2322
2323 /// Return true if this is not a variable sized type,
2324 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2325 /// incomplete types.
2326 bool isConstantSizeType() const;
2327
2328 /// Returns true if this type can be represented by some
2329 /// set of type specifiers.
2330 bool isSpecifierType() const;
2331
2332 /// Determine the linkage of this type.
2333 Linkage getLinkage() const;
2334
2335 /// Determine the visibility of this type.
2336 Visibility getVisibility() const {
2337 return getLinkageAndVisibility().getVisibility();
2338 }
2339
2340 /// Return true if the visibility was explicitly set is the code.
2341 bool isVisibilityExplicit() const {
2342 return getLinkageAndVisibility().isVisibilityExplicit();
2343 }
2344
2345 /// Determine the linkage and visibility of this type.
2346 LinkageInfo getLinkageAndVisibility() const;
2347
2348 /// True if the computed linkage is valid. Used for consistency
2349 /// checking. Should always return true.
2350 bool isLinkageValid() const;
2351
2352 /// Determine the nullability of the given type.
2353 ///
2354 /// Note that nullability is only captured as sugar within the type
2355 /// system, not as part of the canonical type, so nullability will
2356 /// be lost by canonicalization and desugaring.
2357 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2358
2359 /// Determine whether the given type can have a nullability
2360 /// specifier applied to it, i.e., if it is any kind of pointer type.
2361 ///
2362 /// \param ResultIfUnknown The value to return if we don't yet know whether
2363 /// this type can have nullability because it is dependent.
2364 bool canHaveNullability(bool ResultIfUnknown = true) const;
2365
2366 /// Retrieve the set of substitutions required when accessing a member
2367 /// of the Objective-C receiver type that is declared in the given context.
2368 ///
2369 /// \c *this is the type of the object we're operating on, e.g., the
2370 /// receiver for a message send or the base of a property access, and is
2371 /// expected to be of some object or object pointer type.
2372 ///
2373 /// \param dc The declaration context for which we are building up a
2374 /// substitution mapping, which should be an Objective-C class, extension,
2375 /// category, or method within.
2376 ///
2377 /// \returns an array of type arguments that can be substituted for
2378 /// the type parameters of the given declaration context in any type described
2379 /// within that context, or an empty optional to indicate that no
2380 /// substitution is required.
2381 Optional<ArrayRef<QualType>>
2382 getObjCSubstitutions(const DeclContext *dc) const;
2383
2384 /// Determines if this is an ObjC interface type that may accept type
2385 /// parameters.
2386 bool acceptsObjCTypeParams() const;
2387
2388 const char *getTypeClassName() const;
2389
2390 QualType getCanonicalTypeInternal() const {
2391 return CanonicalType;
2392 }
2393
2394 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2395 void dump() const;
2396 void dump(llvm::raw_ostream &OS) const;
2397};
2398
2399/// This will check for a TypedefType by removing any existing sugar
2400/// until it reaches a TypedefType or a non-sugared type.
2401template <> const TypedefType *Type::getAs() const;
2402
2403/// This will check for a TemplateSpecializationType by removing any
2404/// existing sugar until it reaches a TemplateSpecializationType or a
2405/// non-sugared type.
2406template <> const TemplateSpecializationType *Type::getAs() const;
2407
2408/// This will check for an AttributedType by removing any existing sugar
2409/// until it reaches an AttributedType or a non-sugared type.
2410template <> const AttributedType *Type::getAs() const;
2411
2412// We can do canonical leaf types faster, because we don't have to
2413// worry about preserving child type decoration.
2414#define TYPE(Class, Base)
2415#define LEAF_TYPE(Class) \
2416template <> inline const Class##Type *Type::getAs() const { \
2417 return dyn_cast<Class##Type>(CanonicalType); \
2418} \
2419template <> inline const Class##Type *Type::castAs() const { \
2420 return cast<Class##Type>(CanonicalType); \
2421}
2422#include "clang/AST/TypeNodes.inc"
2423
2424/// This class is used for builtin types like 'int'. Builtin
2425/// types are always canonical and have a literal name field.
2426class BuiltinType : public Type {
2427public:
2428 enum Kind {
2429// OpenCL image types
2430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2431#include "clang/Basic/OpenCLImageTypes.def"
2432// OpenCL extension types
2433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2434#include "clang/Basic/OpenCLExtensionTypes.def"
2435// SVE Types
2436#define SVE_TYPE(Name, Id, SingletonId) Id,
2437#include "clang/Basic/AArch64SVEACLETypes.def"
2438// All other builtin types
2439#define BUILTIN_TYPE(Id, SingletonId) Id,
2440#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2441#include "clang/AST/BuiltinTypes.def"
2442 };
2443
2444private:
2445 friend class ASTContext; // ASTContext creates these.
2446
2447 BuiltinType(Kind K)
2448 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2449 /*InstantiationDependent=*/(K == Dependent),
2450 /*VariablyModified=*/false,
2451 /*Unexpanded parameter pack=*/false) {
2452 BuiltinTypeBits.Kind = K;
2453 }
2454
2455public:
2456 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2457 StringRef getName(const PrintingPolicy &Policy) const;
2458
2459 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2460 // The StringRef is null-terminated.
2461 StringRef str = getName(Policy);
2462 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return str.data();
2464 }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 bool isInteger() const {
2470 return getKind() >= Bool && getKind() <= Int128;
2471 }
2472
2473 bool isSignedInteger() const {
2474 return getKind() >= Char_S && getKind() <= Int128;
2475 }
2476
2477 bool isUnsignedInteger() const {
2478 return getKind() >= Bool && getKind() <= UInt128;
2479 }
2480
2481 bool isFloatingPoint() const {
2482 return getKind() >= Half && getKind() <= Float128;
2483 }
2484
2485 /// Determines whether the given kind corresponds to a placeholder type.
2486 static bool isPlaceholderTypeKind(Kind K) {
2487 return K >= Overload;
2488 }
2489
2490 /// Determines whether this type is a placeholder type, i.e. a type
2491 /// which cannot appear in arbitrary positions in a fully-formed
2492 /// expression.
2493 bool isPlaceholderType() const {
2494 return isPlaceholderTypeKind(getKind());
2495 }
2496
2497 /// Determines whether this type is a placeholder type other than
2498 /// Overload. Most placeholder types require only syntactic
2499 /// information about their context in order to be resolved (e.g.
2500 /// whether it is a call expression), which means they can (and
2501 /// should) be resolved in an earlier "phase" of analysis.
2502 /// Overload expressions sometimes pick up further information
2503 /// from their context, like whether the context expects a
2504 /// specific function-pointer type, and so frequently need
2505 /// special treatment.
2506 bool isNonOverloadPlaceholderType() const {
2507 return getKind() > Overload;
2508 }
2509
2510 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2511};
2512
2513/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2514/// types (_Complex float etc) as well as the GCC integer complex extensions.
2515class ComplexType : public Type, public llvm::FoldingSetNode {
2516 friend class ASTContext; // ASTContext creates these.
2517
2518 QualType ElementType;
2519
2520 ComplexType(QualType Element, QualType CanonicalPtr)
2521 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2522 Element->isInstantiationDependentType(),
2523 Element->isVariablyModifiedType(),
2524 Element->containsUnexpandedParameterPack()),
2525 ElementType(Element) {}
2526
2527public:
2528 QualType getElementType() const { return ElementType; }
2529
2530 bool isSugared() const { return false; }
2531 QualType desugar() const { return QualType(this, 0); }
2532
2533 void Profile(llvm::FoldingSetNodeID &ID) {
2534 Profile(ID, getElementType());
2535 }
2536
2537 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2538 ID.AddPointer(Element.getAsOpaquePtr());
2539 }
2540
2541 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2542};
2543
2544/// Sugar for parentheses used when specifying types.
2545class ParenType : public Type, public llvm::FoldingSetNode {
2546 friend class ASTContext; // ASTContext creates these.
2547
2548 QualType Inner;
2549
2550 ParenType(QualType InnerType, QualType CanonType)
2551 : Type(Paren, CanonType, InnerType->isDependentType(),
2552 InnerType->isInstantiationDependentType(),
2553 InnerType->isVariablyModifiedType(),
2554 InnerType->containsUnexpandedParameterPack()),
2555 Inner(InnerType) {}
2556
2557public:
2558 QualType getInnerType() const { return Inner; }
2559
2560 bool isSugared() const { return true; }
2561 QualType desugar() const { return getInnerType(); }
2562
2563 void Profile(llvm::FoldingSetNodeID &ID) {
2564 Profile(ID, getInnerType());
2565 }
2566
2567 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2568 Inner.Profile(ID);
2569 }
2570
2571 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2572};
2573
2574/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2575class PointerType : public Type, public llvm::FoldingSetNode {
2576 friend class ASTContext; // ASTContext creates these.
2577
2578 QualType PointeeType;
2579
2580 PointerType(QualType Pointee, QualType CanonicalPtr)
2581 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2582 Pointee->isInstantiationDependentType(),
2583 Pointee->isVariablyModifiedType(),
2584 Pointee->containsUnexpandedParameterPack()),
2585 PointeeType(Pointee) {}
2586
2587public:
2588 QualType getPointeeType() const { return PointeeType; }
2589
2590 /// Returns true if address spaces of pointers overlap.
2591 /// OpenCL v2.0 defines conversion rules for pointers to different
2592 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2593 /// address spaces.
2594 /// CL1.1 or CL1.2:
2595 /// address spaces overlap iff they are they same.
2596 /// CL2.0 adds:
2597 /// __generic overlaps with any address space except for __constant.
2598 bool isAddressSpaceOverlapping(const PointerType &other) const {
2599 Qualifiers thisQuals = PointeeType.getQualifiers();
2600 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2601 // Address spaces overlap if at least one of them is a superset of another
2602 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2603 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2604 }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getPointeeType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2614 ID.AddPointer(Pointee.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2618};
2619
2620/// Represents a type which was implicitly adjusted by the semantic
2621/// engine for arbitrary reasons. For example, array and function types can
2622/// decay, and function types can have their calling conventions adjusted.
2623class AdjustedType : public Type, public llvm::FoldingSetNode {
2624 QualType OriginalTy;
2625 QualType AdjustedTy;
2626
2627protected:
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2631 QualType CanonicalPtr)
2632 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2633 OriginalTy->isInstantiationDependentType(),
2634 OriginalTy->isVariablyModifiedType(),
2635 OriginalTy->containsUnexpandedParameterPack()),
2636 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2637
2638public:
2639 QualType getOriginalType() const { return OriginalTy; }
2640 QualType getAdjustedType() const { return AdjustedTy; }
2641
2642 bool isSugared() const { return true; }
2643 QualType desugar() const { return AdjustedTy; }
2644
2645 void Profile(llvm::FoldingSetNodeID &ID) {
2646 Profile(ID, OriginalTy, AdjustedTy);
2647 }
2648
2649 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2650 ID.AddPointer(Orig.getAsOpaquePtr());
2651 ID.AddPointer(New.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) {
2655 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2656 }
2657};
2658
2659/// Represents a pointer type decayed from an array or function type.
2660class DecayedType : public AdjustedType {
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 inline
2664 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2665
2666public:
2667 QualType getDecayedType() const { return getAdjustedType(); }
2668
2669 inline QualType getPointeeType() const;
2670
2671 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2672};
2673
2674/// Pointer to a block type.
2675/// This type is to represent types syntactically represented as
2676/// "void (^)(int)", etc. Pointee is required to always be a function type.
2677class BlockPointerType : public Type, public llvm::FoldingSetNode {
2678 friend class ASTContext; // ASTContext creates these.
2679
2680 // Block is some kind of pointer type
2681 QualType PointeeType;
2682
2683 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2684 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2685 Pointee->isInstantiationDependentType(),
2686 Pointee->isVariablyModifiedType(),
2687 Pointee->containsUnexpandedParameterPack()),
2688 PointeeType(Pointee) {}
2689
2690public:
2691 // Get the pointee type. Pointee is required to always be a function type.
2692 QualType getPointeeType() const { return PointeeType; }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 void Profile(llvm::FoldingSetNodeID &ID) {
2698 Profile(ID, getPointeeType());
2699 }
2700
2701 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2702 ID.AddPointer(Pointee.getAsOpaquePtr());
2703 }
2704
2705 static bool classof(const Type *T) {
2706 return T->getTypeClass() == BlockPointer;
2707 }
2708};
2709
2710/// Base for LValueReferenceType and RValueReferenceType
2711class ReferenceType : public Type, public llvm::FoldingSetNode {
2712 QualType PointeeType;
2713
2714protected:
2715 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2716 bool SpelledAsLValue)
2717 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2718 Referencee->isInstantiationDependentType(),
2719 Referencee->isVariablyModifiedType(),
2720 Referencee->containsUnexpandedParameterPack()),
2721 PointeeType(Referencee) {
2722 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2723 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2724 }
2725
2726public:
2727 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2728 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2729
2730 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2731
2732 QualType getPointeeType() const {
2733 // FIXME: this might strip inner qualifiers; okay?
2734 const ReferenceType *T = this;
2735 while (T->isInnerRef())
2736 T = T->PointeeType->castAs<ReferenceType>();
2737 return T->PointeeType;
2738 }
2739
2740 void Profile(llvm::FoldingSetNodeID &ID) {
2741 Profile(ID, PointeeType, isSpelledAsLValue());
2742 }
2743
2744 static void Profile(llvm::FoldingSetNodeID &ID,
2745 QualType Referencee,
2746 bool SpelledAsLValue) {
2747 ID.AddPointer(Referencee.getAsOpaquePtr());
2748 ID.AddBoolean(SpelledAsLValue);
2749 }
2750
2751 static bool classof(const Type *T) {
2752 return T->getTypeClass() == LValueReference ||
2753 T->getTypeClass() == RValueReference;
2754 }
2755};
2756
2757/// An lvalue reference type, per C++11 [dcl.ref].
2758class LValueReferenceType : public ReferenceType {
2759 friend class ASTContext; // ASTContext creates these
2760
2761 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2762 bool SpelledAsLValue)
2763 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2764 SpelledAsLValue) {}
2765
2766public:
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference;
2772 }
2773};
2774
2775/// An rvalue reference type, per C++11 [dcl.ref].
2776class RValueReferenceType : public ReferenceType {
2777 friend class ASTContext; // ASTContext creates these
2778
2779 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2780 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == RValueReference;
2788 }
2789};
2790
2791/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2792///
2793/// This includes both pointers to data members and pointer to member functions.
2794class MemberPointerType : public Type, public llvm::FoldingSetNode {
2795 friend class ASTContext; // ASTContext creates these.
2796
2797 QualType PointeeType;
2798
2799 /// The class of which the pointee is a member. Must ultimately be a
2800 /// RecordType, but could be a typedef or a template parameter too.
2801 const Type *Class;
2802
2803 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2804 : Type(MemberPointer, CanonicalPtr,
2805 Cls->isDependentType() || Pointee->isDependentType(),
2806 (Cls->isInstantiationDependentType() ||
2807 Pointee->isInstantiationDependentType()),
2808 Pointee->isVariablyModifiedType(),
2809 (Cls->containsUnexpandedParameterPack() ||
2810 Pointee->containsUnexpandedParameterPack())),
2811 PointeeType(Pointee), Class(Cls) {}
2812
2813public:
2814 QualType getPointeeType() const { return PointeeType; }
2815
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// function type rather than a data-member type.
2818 bool isMemberFunctionPointer() const {
2819 return PointeeType->isFunctionProtoType();
2820 }
2821
2822 /// Returns true if the member type (i.e. the pointee type) is a
2823 /// data type rather than a function type.
2824 bool isMemberDataPointer() const {
2825 return !PointeeType->isFunctionProtoType();
2826 }
2827
2828 const Type *getClass() const { return Class; }
2829 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2830
2831 bool isSugared() const { return false; }
2832 QualType desugar() const { return QualType(this, 0); }
2833
2834 void Profile(llvm::FoldingSetNodeID &ID) {
2835 Profile(ID, getPointeeType(), getClass());
2836 }
2837
2838 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2839 const Type *Class) {
2840 ID.AddPointer(Pointee.getAsOpaquePtr());
2841 ID.AddPointer(Class);
2842 }
2843
2844 static bool classof(const Type *T) {
2845 return T->getTypeClass() == MemberPointer;
2846 }
2847};
2848
2849/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2850class ArrayType : public Type, public llvm::FoldingSetNode {
2851public:
2852 /// Capture whether this is a normal array (e.g. int X[4])
2853 /// an array with a static size (e.g. int X[static 4]), or an array
2854 /// with a star size (e.g. int X[*]).
2855 /// 'static' is only allowed on function parameters.
2856 enum ArraySizeModifier {
2857 Normal, Static, Star
2858 };
2859
2860private:
2861 /// The element type of the array.
2862 QualType ElementType;
2863
2864protected:
2865 friend class ASTContext; // ASTContext creates these.
2866
2867 // C++ [temp.dep.type]p1:
2868 // A type is dependent if it is...
2869 // - an array type constructed from any dependent type or whose
2870 // size is specified by a constant expression that is
2871 // value-dependent,
2872 ArrayType(TypeClass tc, QualType et, QualType can,
2873 ArraySizeModifier sm, unsigned tq,
2874 bool ContainsUnexpandedParameterPack)
2875 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2876 et->isInstantiationDependentType() || tc == DependentSizedArray,
2877 (tc == VariableArray || et->isVariablyModifiedType()),
2878 ContainsUnexpandedParameterPack),
2879 ElementType(et) {
2880 ArrayTypeBits.IndexTypeQuals = tq;
2881 ArrayTypeBits.SizeModifier = sm;
2882 }
2883
2884public:
2885 QualType getElementType() const { return ElementType; }
2886
2887 ArraySizeModifier getSizeModifier() const {
2888 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2889 }
2890
2891 Qualifiers getIndexTypeQualifiers() const {
2892 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2893 }
2894
2895 unsigned getIndexTypeCVRQualifiers() const {
2896 return ArrayTypeBits.IndexTypeQuals;
2897 }
2898
2899 static bool classof(const Type *T) {
2900 return T->getTypeClass() == ConstantArray ||
2901 T->getTypeClass() == VariableArray ||
2902 T->getTypeClass() == IncompleteArray ||
2903 T->getTypeClass() == DependentSizedArray;
2904 }
2905};
2906
2907/// Represents the canonical version of C arrays with a specified constant size.
2908/// For example, the canonical type for 'int A[4 + 4*100]' is a
2909/// ConstantArrayType where the element type is 'int' and the size is 404.
2910class ConstantArrayType : public ArrayType {
2911 llvm::APInt Size; // Allows us to unique the type.
2912
2913 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2914 ArraySizeModifier sm, unsigned tq)
2915 : ArrayType(ConstantArray, et, can, sm, tq,
2916 et->containsUnexpandedParameterPack()),
2917 Size(size) {}
2918
2919protected:
2920 friend class ASTContext; // ASTContext creates these.
2921
2922 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2923 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2924 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2925 Size(size) {}
2926
2927public:
2928 const llvm::APInt &getSize() const { return Size; }
2929 bool isSugared() const { return false; }
2930 QualType desugar() const { return QualType(this, 0); }
2931
2932 /// Determine the number of bits required to address a member of
2933 // an array with the given element type and number of elements.
2934 static unsigned getNumAddressingBits(const ASTContext &Context,
2935 QualType ElementType,
2936 const llvm::APInt &NumElements);
2937
2938 /// Determine the maximum number of active bits that an array's size
2939 /// can require, which limits the maximum size of the array.
2940 static unsigned getMaxSizeBits(const ASTContext &Context);
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getElementType(), getSize(),
2944 getSizeModifier(), getIndexTypeCVRQualifiers());
2945 }
2946
2947 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2948 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2949 unsigned TypeQuals) {
2950 ID.AddPointer(ET.getAsOpaquePtr());
2951 ID.AddInteger(ArraySize.getZExtValue());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2954 }
2955
2956 static bool classof(const Type *T) {
2957 return T->getTypeClass() == ConstantArray;
2958 }
2959};
2960
2961/// Represents a C array with an unspecified size. For example 'int A[]' has
2962/// an IncompleteArrayType where the element type is 'int' and the size is
2963/// unspecified.
2964class IncompleteArrayType : public ArrayType {
2965 friend class ASTContext; // ASTContext creates these.
2966
2967 IncompleteArrayType(QualType et, QualType can,
2968 ArraySizeModifier sm, unsigned tq)
2969 : ArrayType(IncompleteArray, et, can, sm, tq,
2970 et->containsUnexpandedParameterPack()) {}
2971
2972public:
2973 friend class StmtIteratorBase;
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == IncompleteArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 Profile(ID, getElementType(), getSizeModifier(),
2984 getIndexTypeCVRQualifiers());
2985 }
2986
2987 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2988 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2989 ID.AddPointer(ET.getAsOpaquePtr());
2990 ID.AddInteger(SizeMod);
2991 ID.AddInteger(TypeQuals);
2992 }
2993};
2994
2995/// Represents a C array with a specified size that is not an
2996/// integer-constant-expression. For example, 'int s[x+foo()]'.
2997/// Since the size expression is an arbitrary expression, we store it as such.
2998///
2999/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3000/// should not be: two lexically equivalent variable array types could mean
3001/// different things, for example, these variables do not have the same type
3002/// dynamically:
3003///
3004/// void foo(int x) {
3005/// int Y[x];
3006/// ++x;
3007/// int Z[x];
3008/// }
3009class VariableArrayType : public ArrayType {
3010 friend class ASTContext; // ASTContext creates these.
3011
3012 /// An assignment-expression. VLA's are only permitted within
3013 /// a function block.
3014 Stmt *SizeExpr;
3015
3016 /// The range spanned by the left and right array brackets.
3017 SourceRange Brackets;
3018
3019 VariableArrayType(QualType et, QualType can, Expr *e,
3020 ArraySizeModifier sm, unsigned tq,
3021 SourceRange brackets)
3022 : ArrayType(VariableArray, et, can, sm, tq,
3023 et->containsUnexpandedParameterPack()),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const { return getCanonicalTypeInternal(); }
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
4
Assuming field 'CanonicalType' is a 'EnumType'
5
Returning the value 1, which participates in a condition later
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H