blob: a4218add4e7106b87e62a26bee0d7fb5ea6045f3 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006//
7//===----------------------------------------------------------------------===//
8//
Mike Stump11289f42009-09-09 15:08:12 +00009// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000010// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000016#include "clang/AST/Attr.h"
17#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000023#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000025#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000026#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000027#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000028#include "clang/AST/ExprOpenMP.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000029#include "clang/AST/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000031#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000032#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"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#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"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#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"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000087#include "llvm/Support/SaveAndRestore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#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>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// 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)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
John McCallbebede42011-02-26 05:39:39 +0000118
119 // Highlight all the excess arguments.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000121 call->getArg(argCount - 1)->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +0000122
John McCallbebede42011-02-26 05:39:39 +0000123 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
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000128/// 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000140 return true;
141 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000142
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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000149 return true;
150 }
151
152 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000153 return false;
154}
155
Reid Kleckner30701ed2017-09-05 20:27:35 +0000156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000160 << 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
Richard Smith6cbd65d2013-07-11 02:27:57 +0000178/// 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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000184 ExprResult Arg(TheCall->getArg(0));
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000186 if (ResultType.isNull())
187 return true;
188
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000189 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000190 TheCall->setType(ResultType);
191 return false;
192}
193
Yonghong Song91d5c2a2019-09-22 17:33:48 +0000194/// Check the number of arguments and set the result type to
Yonghong Song048493f2019-07-09 04:21:50 +0000195/// 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
John McCall03107a42015-10-29 20:48:01 +0000204static 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) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000210 ExprResult Arg = TheCall->getArg(I);
211 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000212 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000213 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
Erich Keane1d73d1a2018-06-13 13:25:11 +0000214 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000215 return true;
216 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000217 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());
John McCall03107a42015-10-29 20:48:01 +0000223 }
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 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 ExprResult Arg = TheCall->getArg(2);
230 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000231 const auto *PtrTy = Ty->getAs<PointerType>();
232 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233 !PtrTy->getPointeeType().isConstQualified())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000234 S.Diag(Arg.get()->getBeginLoc(),
Erich Keane1d73d1a2018-06-13 13:25:11 +0000235 diag::err_overflow_builtin_must_be_ptr_int)
236 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000237 return true;
238 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000239 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());
John McCall03107a42015-10-29 20:48:01 +0000245 }
John McCall03107a42015-10-29 20:48:01 +0000246 return false;
247}
248
Peter Collingbournef7706832014-12-12 23:41:25 +0000249static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250 if (checkArgCount(S, BuiltinCall, 2))
251 return true;
252
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000253 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000254 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
David Majnemerced8bdf2015-02-25 17:36:15 +0000294 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000295 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
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000312/// 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
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +0000321 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322 isConstantEvaluated())
Erik Pilkington233ff942019-03-29 19:53:41 +0000323 return;
324
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000325 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
Erik Pilkington81869802019-03-26 23:21:22 +0000449 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450 PDiag(DiagID)
451 << FunctionName << ObjectSize.toString(/*Radix=*/10)
452 << UsedSize.toString(/*Radix=*/10));
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000453}
454
Reid Kleckner1d59f992015-01-22 01:36:17 +0000455static 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.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000461 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000462 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
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000477static 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 =
Simon Pilgrimdc4d9082019-10-07 14:25:46 +0000487 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000488 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();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000503 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000504 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000505 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000506 }
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
Joey Gouly84ae3362017-07-31 15:15:59 +0000516static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000518 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000520 return true;
521 }
522 return false;
523}
524
Joey Goulyfa76b492017-08-01 13:27:09 +0000525static 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);
Yaxun Liub7318e02017-10-13 03:37:48 +0000534 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000535 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000536 << TheCall->getDirectCallee() << "'ndrange_t'";
537 return true;
538 }
539
540 Expr *BlockArg = TheCall->getArg(1);
541 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000542 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000543 << TheCall->getDirectCallee() << "block";
544 return true;
545 }
546 return checkOpenCLBlockArgs(S, BlockArg);
547}
548
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000549/// 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)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000558 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 return checkOpenCLBlockArgs(S, BlockArg);
563}
564
Simon Pilgrim2c518802017-03-30 14:13:19 +0000565/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000566static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567 const QualType &IntType);
568
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000569static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000570 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}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000577
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 =
Simon Pilgrimdc4d9082019-10-07 14:25:46 +0000586 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000587 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) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000592 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 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) {
Sven van Haastregta280b632019-08-29 10:21:06 +0000632 S.Diag(TheCall->getBeginLoc(),
633 diag::err_typecheck_call_too_few_args_at_least)
634 << 0 << 4 << NumArgs;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000635 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000645 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000646 diag::err_opencl_builtin_expected_type)
647 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000648 return true;
649 }
650
651 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000653 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000654 diag::err_opencl_builtin_expected_type)
655 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000656 return true;
657 }
658
659 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000660 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000661 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000662 diag::err_opencl_builtin_expected_type)
663 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000664 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)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000672 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000673 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000674 return true;
675 }
676 // we have a block type, check the prototype
677 const BlockPointerType *BPT =
678 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
Simon Pilgrimdc4d9082019-10-07 14:25:46 +0000679 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000680 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000681 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)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000695 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000696 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000697 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000704 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000705 diag::err_opencl_builtin_expected_type)
706 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000707 return true;
708 }
709 // check remaining common arguments.
710 Expr *Arg4 = TheCall->getArg(4);
711 Expr *Arg5 = TheCall->getArg(5);
712
Anastasia Stulova2b461202016-11-14 15:34:01 +0000713 // 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000717 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000718 diag::err_opencl_builtin_expected_type)
719 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000720 << S.Context.getPointerType(S.Context.OCLClkEventTy);
721 return true;
722 }
723
Anastasia Stulova2b461202016-11-14 15:34:01 +0000724 // 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() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000728 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000729 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000730 diag::err_opencl_builtin_expected_type)
731 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000732 << 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
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000743 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000744 diag::err_opencl_enqueue_kernel_incorrect_args);
745 return true;
746}
747
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000748/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000749static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000750 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751}
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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000758 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000759 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000760 return true;
761 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000762 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000763 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.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000768 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())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000777 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000778 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())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000791 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000792 diag::err_opencl_builtin_pipe_invalid_access_modifier)
793 << "write_only" << Arg0->getSourceRange();
794 return true;
795 }
796 break;
797 default:
798 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000799 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000800 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());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000808 const QualType EltTy = PipeTy->getElementType();
809 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000810 // 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.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000812 if (!ArgTy ||
813 !S.Context.hasSameType(
814 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000815 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000816 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000817 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000818 return true;
819 }
820 return false;
821}
822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000823// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000824// \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) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000828 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000830 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000831 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000832 if (checkOpenCLPipeArg(S, Call))
833 return true;
834 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000835 // read/write_pipe(pipe T, T*).
836 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000837 if (checkOpenCLPipePacketType(S, Call, 1))
838 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000839 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000840
841 case 4: {
842 if (checkOpenCLPipeArg(S, Call))
843 return true;
844 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000845 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000847 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000848 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000849 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000850 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000851 return true;
852 }
853
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000854 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000855 const Expr *Arg2 = Call->getArg(2);
856 if (!Arg2->getType()->isIntegerType() &&
857 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000858 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000859 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000860 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000861 return true;
862 }
863
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000864 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000865 if (checkOpenCLPipePacketType(S, Call, 3))
866 return true;
867 } break;
868 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000869 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000870 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000871 return true;
872 }
873
874 return false;
875}
876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000877// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000878// /_}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
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000889 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000890 if (!Call->getArg(1)->getType()->isIntegerType() &&
891 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000892 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000893 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000894 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000895 return true;
896 }
897
Joey Gouly922ca232017-08-09 14:52:47 +0000898 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000899 // 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000921 << 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000939 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000940 << 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) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000956 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000957 << 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) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000964 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000965 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966 return true;
967 }
968
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000969 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
Aaron Ballman68d50642018-06-19 14:53:20 +0000976 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");
990 }
991 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992 RT.getUnqualifiedType(), Qual)));
993
994 return false;
995}
996
Eric Fiselier26187502018-12-14 21:11:28 +0000997static 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() &&
1044 "Unhandled non-object pointer case");
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
Aaron Ballman68d50642018-06-19 14:53:20 +00001057// 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;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001066 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +00001067 << 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.
Fangrui Song6907ce22018-07-30 19:24:48 +00001082
Aaron Ballman68d50642018-06-19 14:53:20 +00001083 // 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;
Fangrui Song6907ce22018-07-30 19:24:48 +00001087
Aaron Ballman68d50642018-06-19 14:53:20 +00001088 llvm::APSInt Result;
1089 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090 return true;
1091 ICEArguments &= ~(1 << ArgNo);
1092 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001093
Aaron Ballman68d50642018-06-19 14:53:20 +00001094 switch (BuiltinID) {
1095 case Builtin::BI__builtin___CFStringMakeConstantString:
1096 assert(TheCall->getNumArgs() == 1 &&
1097 "Wrong # arguments to builtin CFStringMakeConstantString");
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()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +00001109 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +00001110 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:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00001167 case Builtin::BI__builtin_signbit:
1168 case Builtin::BI__builtin_signbitf:
1169 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +00001170 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();
George Burgess IV9d045a52019-07-25 22:23:40 +00001184 LLVM_FALLTHROUGH;
1185 case Builtin::BI__builtin_alloca:
1186 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187 << TheCall->getDirectCallee();
Aaron Ballman68d50642018-06-19 14:53:20 +00001188 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;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00001198 case Builtin::BI__builtin_dynamic_object_size:
Aaron Ballman68d50642018-06-19 14:53:20 +00001199 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;
Richard Smith31cfb312019-04-27 02:58:17 +00001220 case Builtin::BI__builtin_constant_p: {
Aaron Ballman68d50642018-06-19 14:53:20 +00001221 if (checkArgCount(*this, TheCall, 1)) return true;
Richard Smith31cfb312019-04-27 02:58:17 +00001222 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223 if (Arg.isInvalid()) return true;
1224 TheCall->setArg(0, Arg.get());
Aaron Ballman68d50642018-06-19 14:53:20 +00001225 TheCall->setType(Context.IntTy);
1226 break;
Richard Smith31cfb312019-04-27 02:58:17 +00001227 }
Eric Fiselier26187502018-12-14 21:11:28 +00001228 case Builtin::BI__builtin_launder:
1229 return SemaBuiltinLaunder(*this, TheCall);
Aaron Ballman68d50642018-06-19 14:53:20 +00001230 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);
JF Bastiene77b48b2018-09-10 20:42:56 +00001333 case Builtin::BI__sync_synchronize:
1334 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335 << TheCall->getCallee()->getSourceRange();
1336 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001337 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001381 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001382 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383 << "structure pointer";
1384 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001385 }
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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001394 return ExprError();
1395 }
1396
1397 const auto *FuncType =
1398 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399
1400 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001401 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001404 return ExprError();
1405 }
1406
1407 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001409 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001410 << 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001418 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001419 << 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 }
Yonghong Song048493f2019-07-09 04:21:50 +00001428 case Builtin::BI__builtin_preserve_access_index:
1429 if (SemaBuiltinPreserveAI(*this, TheCall))
1430 return ExprError();
1431 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001432 case Builtin::BI__builtin_call_with_static_chain:
1433 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434 return ExprError();
1435 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001436 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001437 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439 diag::err_seh___except_block))
1440 return ExprError();
1441 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001442 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001443 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001444 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445 diag::err_seh___except_filter))
1446 return ExprError();
1447 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001448 case Builtin::BI__GetExceptionInfo:
1449 if (checkArgCount(*this, TheCall, 1))
1450 return ExprError();
1451
1452 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001453 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001454 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455 TheCall))
1456 return ExprError();
1457
1458 TheCall->setType(Context.VoidPtrTy);
1459 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001460 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001461 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:
Joey Gouly84ae3362017-07-31 15:15:59 +00001472 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001474 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001475 case Builtin::BIsub_group_reserve_read_pipe:
1476 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001477 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001479 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001480 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:
Joey Gouly84ae3362017-07-31 15:15:59 +00001485 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486 return ExprError();
1487 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001488 case Builtin::BIsub_group_commit_read_pipe:
1489 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001490 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001492 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;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001499 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;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001505 // 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();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001514 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001515 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;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001520 case Builtin::BI__builtin_os_log_format:
1521 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001522 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001523 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001524 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001525 }
Richard Smith760520b2014-06-03 23:27:44 +00001526
Nate Begeman4904e322010-06-08 02:47:44 +00001527 // Since the target specific builtins for each arch overlap, only check those
1528 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001529 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001531 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001532 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001533 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001534 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001535 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536 return ExprError();
1537 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001538 case llvm::Triple::aarch64:
Tim Northover44e58792018-09-18 10:34:39 +01001539 case llvm::Triple::aarch64_32:
Tim Northover25e8a672014-05-24 12:51:25 +00001540 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001541 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001542 return ExprError();
1543 break;
Yonghong Song05e46972019-10-08 18:23:17 +00001544 case llvm::Triple::bpfeb:
1545 case llvm::Triple::bpfel:
1546 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1547 return ExprError();
1548 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001549 case llvm::Triple::hexagon:
1550 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1551 return ExprError();
1552 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001553 case llvm::Triple::mips:
1554 case llvm::Triple::mipsel:
1555 case llvm::Triple::mips64:
1556 case llvm::Triple::mips64el:
1557 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1558 return ExprError();
1559 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001560 case llvm::Triple::systemz:
1561 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1562 return ExprError();
1563 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001564 case llvm::Triple::x86:
1565 case llvm::Triple::x86_64:
1566 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1567 return ExprError();
1568 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001569 case llvm::Triple::ppc:
1570 case llvm::Triple::ppc64:
1571 case llvm::Triple::ppc64le:
1572 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1573 return ExprError();
1574 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001575 default:
1576 break;
1577 }
1578 }
1579
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001580 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001581}
1582
Nate Begeman91e1fea2010-06-14 05:21:25 +00001583// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001584static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001585 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001586 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001587 switch (Type.getEltType()) {
1588 case NeonTypeFlags::Int8:
1589 case NeonTypeFlags::Poly8:
1590 return shift ? 7 : (8 << IsQuad) - 1;
1591 case NeonTypeFlags::Int16:
1592 case NeonTypeFlags::Poly16:
1593 return shift ? 15 : (4 << IsQuad) - 1;
1594 case NeonTypeFlags::Int32:
1595 return shift ? 31 : (2 << IsQuad) - 1;
1596 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001597 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001598 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001599 case NeonTypeFlags::Poly128:
1600 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001601 case NeonTypeFlags::Float16:
1602 assert(!shift && "cannot shift float types!");
1603 return (4 << IsQuad) - 1;
1604 case NeonTypeFlags::Float32:
1605 assert(!shift && "cannot shift float types!");
1606 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001607 case NeonTypeFlags::Float64:
1608 assert(!shift && "cannot shift float types!");
1609 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001610 }
David Blaikie8a40f702012-01-17 06:56:22 +00001611 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001612}
1613
Bob Wilsone4d77232011-11-08 05:04:11 +00001614/// getNeonEltType - Return the QualType corresponding to the elements of
1615/// the vector type specified by the NeonTypeFlags. This is used to check
1616/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001617static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001618 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001619 switch (Flags.getEltType()) {
1620 case NeonTypeFlags::Int8:
1621 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1622 case NeonTypeFlags::Int16:
1623 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1624 case NeonTypeFlags::Int32:
1625 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1626 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001627 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001628 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1629 else
1630 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1631 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001632 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001633 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001634 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001635 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001636 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001637 if (IsInt64Long)
1638 return Context.UnsignedLongTy;
1639 else
1640 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001641 case NeonTypeFlags::Poly128:
1642 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001643 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001644 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001645 case NeonTypeFlags::Float32:
1646 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001647 case NeonTypeFlags::Float64:
1648 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001649 }
David Blaikie8a40f702012-01-17 06:56:22 +00001650 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001651}
1652
Tim Northover12670412014-02-19 10:37:05 +00001653bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001654 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001655 uint64_t mask = 0;
1656 unsigned TV = 0;
1657 int PtrArgNum = -1;
1658 bool HasConstPtr = false;
1659 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001660#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001661#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001662#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001663#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001664 }
1665
1666 // For NEON intrinsics which are overloaded on vector element type, validate
1667 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001668 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001669 if (mask) {
1670 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1671 return true;
1672
1673 TV = Result.getLimitedValue(64);
1674 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001675 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1676 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001677 }
1678
1679 if (PtrArgNum >= 0) {
1680 // Check that pointer arguments have the specified type.
1681 Expr *Arg = TheCall->getArg(PtrArgNum);
1682 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1683 Arg = ICE->getSubExpr();
1684 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1685 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001686
Tim Northovera2ee4332014-03-29 15:09:45 +00001687 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001688 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
Tim Northover44e58792018-09-18 10:34:39 +01001689 Arch == llvm::Triple::aarch64_32 ||
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001690 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001691 bool IsInt64Long =
1692 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1693 QualType EltTy =
1694 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001695 if (HasConstPtr)
1696 EltTy = EltTy.withConst();
1697 QualType LHSTy = Context.getPointerType(EltTy);
1698 AssignConvertType ConvTy;
1699 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1700 if (RHS.isInvalid())
1701 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001702 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001703 RHS.get(), AA_Assigning))
1704 return true;
1705 }
1706
1707 // For NEON intrinsics which take an immediate value as part of the
1708 // instruction, range check them here.
1709 unsigned i = 0, l = 0, u = 0;
1710 switch (BuiltinID) {
1711 default:
1712 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001713 #define GET_NEON_IMMEDIATE_CHECK
1714 #include "clang/Basic/arm_neon.inc"
1715 #include "clang/Basic/arm_fp16.inc"
1716 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001717 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001718
Richard Sandiford28940af2014-04-16 08:47:51 +00001719 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001720}
1721
Simon Tatham08074cc2019-09-02 15:50:50 +01001722bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1723 switch (BuiltinID) {
1724 default:
1725 return false;
1726 #include "clang/Basic/arm_mve_builtin_sema.inc"
1727 }
1728}
1729
Tim Northovera2ee4332014-03-29 15:09:45 +00001730bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1731 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001732 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001733 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001734 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001735 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001736 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001737 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1738 BuiltinID == AArch64::BI__builtin_arm_strex ||
1739 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001740 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001741 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001742 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1743 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1744 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001745
1746 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1747
1748 // Ensure that we have the proper number of arguments.
1749 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1750 return true;
1751
1752 // Inspect the pointer argument of the atomic builtin. This should always be
1753 // a pointer type, whose element is an integral scalar or pointer type.
1754 // Because it is a pointer type, we don't have to worry about any implicit
1755 // casts here.
1756 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1757 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1758 if (PointerArgRes.isInvalid())
1759 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001760 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001761
1762 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1763 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001764 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1765 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001766 return true;
1767 }
1768
1769 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1770 // task is to insert the appropriate casts into the AST. First work out just
1771 // what the appropriate type is.
1772 QualType ValType = pointerType->getPointeeType();
1773 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1774 if (IsLdrex)
1775 AddrType.addConst();
1776
1777 // Issue a warning if the cast is dodgy.
1778 CastKind CastNeeded = CK_NoOp;
1779 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1780 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001781 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1782 << PointerArg->getType() << Context.getPointerType(AddrType)
1783 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001784 }
1785
1786 // Finally, do the cast and replace the argument with the corrected version.
1787 AddrType = Context.getPointerType(AddrType);
1788 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1789 if (PointerArgRes.isInvalid())
1790 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001791 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001792
1793 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1794
1795 // In general, we allow ints, floats and pointers to be loaded and stored.
1796 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1797 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001798 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1799 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001800 return true;
1801 }
1802
1803 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001804 if (Context.getTypeSize(ValType) > MaxWidth) {
1805 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001806 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1807 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001808 return true;
1809 }
1810
1811 switch (ValType.getObjCLifetime()) {
1812 case Qualifiers::OCL_None:
1813 case Qualifiers::OCL_ExplicitNone:
1814 // okay
1815 break;
1816
1817 case Qualifiers::OCL_Weak:
1818 case Qualifiers::OCL_Strong:
1819 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001820 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1821 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001822 return true;
1823 }
1824
Tim Northover6aacd492013-07-16 09:47:53 +00001825 if (IsLdrex) {
1826 TheCall->setType(ValType);
1827 return false;
1828 }
1829
1830 // Initialize the argument to be stored.
1831 ExprResult ValArg = TheCall->getArg(0);
1832 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1833 Context, ValType, /*consume*/ false);
1834 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1835 if (ValArg.isInvalid())
1836 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001837 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001838
1839 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1840 // but the custom checker bypasses all default analysis.
1841 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001842 return false;
1843}
1844
Nate Begeman4904e322010-06-08 02:47:44 +00001845bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001846 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001847 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1848 BuiltinID == ARM::BI__builtin_arm_strex ||
1849 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001850 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001851 }
1852
Yi Kong26d104a2014-08-13 19:18:14 +00001853 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1854 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1855 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1856 }
1857
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001858 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1859 BuiltinID == ARM::BI__builtin_arm_wsr64)
1860 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1861
1862 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1863 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1864 BuiltinID == ARM::BI__builtin_arm_wsr ||
1865 BuiltinID == ARM::BI__builtin_arm_wsrp)
1866 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1867
Tim Northover12670412014-02-19 10:37:05 +00001868 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1869 return true;
Simon Tatham08074cc2019-09-02 15:50:50 +01001870 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
1871 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001872
Yi Kong4efadfb2014-07-03 16:01:25 +00001873 // For intrinsics which take an immediate value as part of the instruction,
1874 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001875 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001876 switch (BuiltinID) {
1877 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001878 case ARM::BI__builtin_arm_ssat:
1879 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1880 case ARM::BI__builtin_arm_usat:
1881 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1882 case ARM::BI__builtin_arm_ssat16:
1883 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1884 case ARM::BI__builtin_arm_usat16:
1885 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001886 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001887 case ARM::BI__builtin_arm_vcvtr_d:
1888 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001889 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001890 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001891 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001892 case ARM::BI__builtin_arm_dbg:
1893 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001894 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001895}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001896
Tim Northover573cbee2014-05-24 12:52:07 +00001897bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001898 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001899 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001900 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1901 BuiltinID == AArch64::BI__builtin_arm_strex ||
1902 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001903 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1904 }
1905
Yi Konga5548432014-08-13 19:18:20 +00001906 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1907 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1908 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1909 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1910 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1911 }
1912
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001913 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1914 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001915 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001916
Javed Absar18b0c402019-04-26 21:08:11 +00001917 // Memory Tagging Extensions (MTE) Intrinsics
1918 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1919 BuiltinID == AArch64::BI__builtin_arm_addg ||
1920 BuiltinID == AArch64::BI__builtin_arm_gmi ||
1921 BuiltinID == AArch64::BI__builtin_arm_ldg ||
1922 BuiltinID == AArch64::BI__builtin_arm_stg ||
1923 BuiltinID == AArch64::BI__builtin_arm_subp) {
1924 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1925 }
1926
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001927 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1928 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1929 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1930 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1931 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1932
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001933 // Only check the valid encoding range. Any constant in this range would be
1934 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1935 // an exception for incorrect registers. This matches MSVC behavior.
1936 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1937 BuiltinID == AArch64::BI_WriteStatusReg)
1938 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1939
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001940 if (BuiltinID == AArch64::BI__getReg)
1941 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1942
Tim Northovera2ee4332014-03-29 15:09:45 +00001943 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1944 return true;
1945
Yi Kong19a29ac2014-07-17 10:52:06 +00001946 // For intrinsics which take an immediate value as part of the instruction,
1947 // range check them here.
1948 unsigned i = 0, l = 0, u = 0;
1949 switch (BuiltinID) {
1950 default: return false;
1951 case AArch64::BI__builtin_arm_dmb:
1952 case AArch64::BI__builtin_arm_dsb:
1953 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
Momchil Velikova36d3142019-07-31 12:52:17 +00001954 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
Yi Kong19a29ac2014-07-17 10:52:06 +00001955 }
1956
Yi Kong19a29ac2014-07-17 10:52:06 +00001957 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001958}
1959
Yonghong Song05e46972019-10-08 18:23:17 +00001960bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
1961 CallExpr *TheCall) {
1962 assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
1963 "unexpected ARM builtin");
1964
1965 if (checkArgCount(*this, TheCall, 2))
1966 return true;
1967
1968 // The first argument needs to be a record field access.
1969 // If it is an array element access, we delay decision
1970 // to BPF backend to check whether the access is a
1971 // field access or not.
1972 Expr *Arg = TheCall->getArg(0);
1973 if (Arg->getType()->getAsPlaceholderType() ||
1974 (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
1975 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
1976 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
1977 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
1978 << 1 << Arg->getSourceRange();
1979 return true;
1980 }
1981
1982 // The second argument needs to be a constant int
1983 llvm::APSInt Value;
1984 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
1985 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
1986 << 2 << Arg->getSourceRange();
1987 return true;
1988 }
1989
1990 TheCall->setType(Context.UnsignedIntTy);
1991 return false;
1992}
1993
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001994bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001995 struct BuiltinAndString {
1996 unsigned BuiltinID;
1997 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001998 };
1999
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002000 static BuiltinAndString ValidCPU[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002001 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
2004 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
2005 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
2006 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
2009 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2012 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2013 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002024 };
2025
2026 static BuiltinAndString ValidHVX[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002027 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2544 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2545 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2546 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2547 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2548 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2549 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2550 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2551 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2552 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2553 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2554 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2555 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2556 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2557 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2558 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2559 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2560 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2561 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2562 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2563 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2564 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2565 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2566 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2567 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2568 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2569 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2570 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2571 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2572 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2573 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2574 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2575 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2576 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2577 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2578 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2579 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2580 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2581 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2582 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2583 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2584 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2585 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2586 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2587 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2588 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2589 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2590 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2591 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2592 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2593 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2594 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002595 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2596 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2597 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2598 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002599 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2600 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2601 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2602 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2603 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2604 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2605 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2606 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2607 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2608 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2609 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2610 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2611 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2612 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2613 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2614 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2615 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2616 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2617 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2618 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2619 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2620 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2621 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2622 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002623 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2624 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2625 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2626 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002627 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2628 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2629 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2630 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2631 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2632 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2633 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2634 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2635 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2636 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2637 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2638 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2639 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2640 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2641 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2642 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2643 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2644 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2645 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2646 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2647 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2648 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2649 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2650 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2651 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2652 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2653 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2654 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2655 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2656 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2657 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2658 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2659 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2660 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2661 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2662 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2663 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2664 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2665 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2666 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2667 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2668 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2669 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2670 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2671 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2672 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2673 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2674 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2675 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2676 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2677 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2678 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2679 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2680 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2681 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2682 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2683 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2684 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2685 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2686 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2687 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2688 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2689 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2690 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2691 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2692 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2693 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2694 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2695 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2696 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2697 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2698 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2699 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2700 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2701 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2702 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2703 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2704 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2705 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2706 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2707 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2708 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2709 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2710 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2711 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2712 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2713 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2714 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2715 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2716 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2717 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2718 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2719 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2720 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2721 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2722 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2723 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2724 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2725 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2726 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2727 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2728 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2729 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2730 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2731 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2732 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2733 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2734 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2735 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2736 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2737 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2738 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2739 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2740 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2741 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2742 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2743 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2744 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2745 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2746 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2747 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2748 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2749 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2750 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2751 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2752 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2753 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2754 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2755 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2756 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2757 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2758 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002759 };
2760
2761 // Sort the tables on first execution so we can binary search them.
2762 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2763 return LHS.BuiltinID < RHS.BuiltinID;
2764 };
2765 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002766 (llvm::sort(ValidCPU, SortCmp),
2767 llvm::sort(ValidHVX, SortCmp), true);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002768 (void)SortOnce;
2769 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2770 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002771 };
2772
2773 const TargetInfo &TI = Context.getTargetInfo();
2774
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002775 const BuiltinAndString *FC =
Fangrui Song7264a472019-07-03 08:13:17 +00002776 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002777 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002778 const TargetOptions &Opts = TI.getTargetOpts();
2779 StringRef CPU = Opts.CPU;
2780 if (!CPU.empty()) {
2781 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2782 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002783 SmallVector<StringRef, 3> CPUs;
2784 StringRef(FC->Str).split(CPUs, ',');
2785 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002786 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002787 diag::err_hexagon_builtin_unsupported_cpu);
2788 }
2789 }
2790
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002791 const BuiltinAndString *FH =
Fangrui Song7264a472019-07-03 08:13:17 +00002792 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002793 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002794 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002795 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002796 diag::err_hexagon_builtin_requires_hvx);
2797
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002798 SmallVector<StringRef, 3> HVXs;
2799 StringRef(FH->Str).split(HVXs, ',');
2800 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002801 [&TI] (StringRef V) {
2802 std::string F = "hvx" + V.str();
2803 return TI.hasFeature(F);
2804 });
2805 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002806 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002807 diag::err_hexagon_builtin_unsupported_hvx);
2808 }
2809
2810 return false;
2811}
2812
2813bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002814 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002815 uint8_t OpNum;
2816 bool IsSigned;
2817 uint8_t BitWidth;
2818 uint8_t Align;
2819 };
2820 struct BuiltinInfo {
2821 unsigned BuiltinID;
2822 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002823 };
2824
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002825 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002826 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2827 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2828 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2829 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2830 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2831 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2832 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2833 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2834 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2835 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2836 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2837
2838 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2841 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2842 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2843 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2845 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2846 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2847 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2848 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2849
2850 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2851 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2852 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2859 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2864 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2865 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2866 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2867 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2868 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2870 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2871 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2872 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2873 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2874 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2875 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2876 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2878 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2879 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2881 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2882 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2886 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2888 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2889 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2890 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2892 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2893 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2894 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2895 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2896 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2898 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2899 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2900 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2901 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2902 {{ 1, false, 6, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2905 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2906 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2909 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2910 {{ 1, false, 5, 0 }} },
2911 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2912 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2913 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2914 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2915 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2916 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2917 { 2, false, 5, 0 }} },
2918 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2919 { 2, false, 6, 0 }} },
2920 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2921 { 3, false, 5, 0 }} },
2922 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2923 { 3, false, 6, 0 }} },
2924 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2925 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2926 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2927 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2928 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2929 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2930 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2931 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2932 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2933 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2934 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2935 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2936 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2937 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2938 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2939 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2940 {{ 2, false, 4, 0 },
2941 { 3, false, 5, 0 }} },
2942 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2943 {{ 2, false, 4, 0 },
2944 { 3, false, 5, 0 }} },
2945 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2946 {{ 2, false, 4, 0 },
2947 { 3, false, 5, 0 }} },
2948 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2949 {{ 2, false, 4, 0 },
2950 { 3, false, 5, 0 }} },
2951 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2952 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2953 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2954 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2955 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2956 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2957 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2958 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2959 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2960 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2961 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2962 { 2, false, 5, 0 }} },
2963 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2964 { 2, false, 6, 0 }} },
2965 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2966 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2967 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2968 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2969 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2970 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2971 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2972 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2973 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2974 {{ 1, false, 4, 0 }} },
2975 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2976 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2977 {{ 1, false, 4, 0 }} },
2978 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2979 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2980 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2981 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2982 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2983 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2984 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2985 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2986 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2987 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2988 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2989 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2990 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2991 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2992 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2993 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2994 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2995 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2996 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2997 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2998 {{ 3, false, 1, 0 }} },
2999 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
3000 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
3001 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
3002 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3003 {{ 3, false, 1, 0 }} },
3004 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
3005 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
3006 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
3007 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3008 {{ 3, false, 1, 0 }} },
3009 };
3010
Reid Kleckner9e9606e2018-10-25 22:37:30 +00003011 // Use a dynamically initialized static to sort the table exactly once on
3012 // first run.
3013 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00003014 (llvm::sort(Infos,
Reid Kleckner9e9606e2018-10-25 22:37:30 +00003015 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3016 return LHS.BuiltinID < RHS.BuiltinID;
3017 }),
3018 true);
3019 (void)SortOnce;
3020
Fangrui Song7264a472019-07-03 08:13:17 +00003021 const BuiltinInfo *F = llvm::partition_point(
3022 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
Reid Kleckner9e9606e2018-10-25 22:37:30 +00003023 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00003024 return false;
3025
3026 bool Error = false;
3027
Reid Kleckner9e9606e2018-10-25 22:37:30 +00003028 for (const ArgInfo &A : F->Infos) {
3029 // Ignore empty ArgInfo elements.
3030 if (A.BitWidth == 0)
3031 continue;
3032
3033 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3034 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00003035 if (!A.Align) {
3036 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3037 } else {
3038 unsigned M = 1 << A.Align;
3039 Min *= M;
3040 Max *= M;
3041 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3042 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3043 }
3044 }
3045 return Error;
3046}
3047
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00003048bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3049 CallExpr *TheCall) {
3050 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3051 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3052}
3053
3054
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003055// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3056// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3057// ordering for DSP is unspecified. MSA is ordered by the data format used
3058// by the underlying instruction i.e., df/m, df/n and then by size.
3059//
3060// FIXME: The size tests here should instead be tablegen'd along with the
3061// definitions from include/clang/Basic/BuiltinsMips.def.
3062// FIXME: GCC is strict on signedness for some of these intrinsics, we should
3063// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003064bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003065 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003066 switch (BuiltinID) {
3067 default: return false;
3068 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3069 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00003070 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3071 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3072 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3073 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3074 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003075 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003076 // df/m field.
3077 // These intrinsics take an unsigned 3 bit immediate.
3078 case Mips::BI__builtin_msa_bclri_b:
3079 case Mips::BI__builtin_msa_bnegi_b:
3080 case Mips::BI__builtin_msa_bseti_b:
3081 case Mips::BI__builtin_msa_sat_s_b:
3082 case Mips::BI__builtin_msa_sat_u_b:
3083 case Mips::BI__builtin_msa_slli_b:
3084 case Mips::BI__builtin_msa_srai_b:
3085 case Mips::BI__builtin_msa_srari_b:
3086 case Mips::BI__builtin_msa_srli_b:
3087 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3088 case Mips::BI__builtin_msa_binsli_b:
3089 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3090 // These intrinsics take an unsigned 4 bit immediate.
3091 case Mips::BI__builtin_msa_bclri_h:
3092 case Mips::BI__builtin_msa_bnegi_h:
3093 case Mips::BI__builtin_msa_bseti_h:
3094 case Mips::BI__builtin_msa_sat_s_h:
3095 case Mips::BI__builtin_msa_sat_u_h:
3096 case Mips::BI__builtin_msa_slli_h:
3097 case Mips::BI__builtin_msa_srai_h:
3098 case Mips::BI__builtin_msa_srari_h:
3099 case Mips::BI__builtin_msa_srli_h:
3100 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3101 case Mips::BI__builtin_msa_binsli_h:
3102 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003103 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003104 // The first block of intrinsics actually have an unsigned 5 bit field,
3105 // not a df/n field.
Simon Atanasyanc7f0b332019-05-29 14:59:32 +00003106 case Mips::BI__builtin_msa_cfcmsa:
3107 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003108 case Mips::BI__builtin_msa_clei_u_b:
3109 case Mips::BI__builtin_msa_clei_u_h:
3110 case Mips::BI__builtin_msa_clei_u_w:
3111 case Mips::BI__builtin_msa_clei_u_d:
3112 case Mips::BI__builtin_msa_clti_u_b:
3113 case Mips::BI__builtin_msa_clti_u_h:
3114 case Mips::BI__builtin_msa_clti_u_w:
3115 case Mips::BI__builtin_msa_clti_u_d:
3116 case Mips::BI__builtin_msa_maxi_u_b:
3117 case Mips::BI__builtin_msa_maxi_u_h:
3118 case Mips::BI__builtin_msa_maxi_u_w:
3119 case Mips::BI__builtin_msa_maxi_u_d:
3120 case Mips::BI__builtin_msa_mini_u_b:
3121 case Mips::BI__builtin_msa_mini_u_h:
3122 case Mips::BI__builtin_msa_mini_u_w:
3123 case Mips::BI__builtin_msa_mini_u_d:
3124 case Mips::BI__builtin_msa_addvi_b:
3125 case Mips::BI__builtin_msa_addvi_h:
3126 case Mips::BI__builtin_msa_addvi_w:
3127 case Mips::BI__builtin_msa_addvi_d:
3128 case Mips::BI__builtin_msa_bclri_w:
3129 case Mips::BI__builtin_msa_bnegi_w:
3130 case Mips::BI__builtin_msa_bseti_w:
3131 case Mips::BI__builtin_msa_sat_s_w:
3132 case Mips::BI__builtin_msa_sat_u_w:
3133 case Mips::BI__builtin_msa_slli_w:
3134 case Mips::BI__builtin_msa_srai_w:
3135 case Mips::BI__builtin_msa_srari_w:
3136 case Mips::BI__builtin_msa_srli_w:
3137 case Mips::BI__builtin_msa_srlri_w:
3138 case Mips::BI__builtin_msa_subvi_b:
3139 case Mips::BI__builtin_msa_subvi_h:
3140 case Mips::BI__builtin_msa_subvi_w:
3141 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3142 case Mips::BI__builtin_msa_binsli_w:
3143 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3144 // These intrinsics take an unsigned 6 bit immediate.
3145 case Mips::BI__builtin_msa_bclri_d:
3146 case Mips::BI__builtin_msa_bnegi_d:
3147 case Mips::BI__builtin_msa_bseti_d:
3148 case Mips::BI__builtin_msa_sat_s_d:
3149 case Mips::BI__builtin_msa_sat_u_d:
3150 case Mips::BI__builtin_msa_slli_d:
3151 case Mips::BI__builtin_msa_srai_d:
3152 case Mips::BI__builtin_msa_srari_d:
3153 case Mips::BI__builtin_msa_srli_d:
3154 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3155 case Mips::BI__builtin_msa_binsli_d:
3156 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3157 // These intrinsics take a signed 5 bit immediate.
3158 case Mips::BI__builtin_msa_ceqi_b:
3159 case Mips::BI__builtin_msa_ceqi_h:
3160 case Mips::BI__builtin_msa_ceqi_w:
3161 case Mips::BI__builtin_msa_ceqi_d:
3162 case Mips::BI__builtin_msa_clti_s_b:
3163 case Mips::BI__builtin_msa_clti_s_h:
3164 case Mips::BI__builtin_msa_clti_s_w:
3165 case Mips::BI__builtin_msa_clti_s_d:
3166 case Mips::BI__builtin_msa_clei_s_b:
3167 case Mips::BI__builtin_msa_clei_s_h:
3168 case Mips::BI__builtin_msa_clei_s_w:
3169 case Mips::BI__builtin_msa_clei_s_d:
3170 case Mips::BI__builtin_msa_maxi_s_b:
3171 case Mips::BI__builtin_msa_maxi_s_h:
3172 case Mips::BI__builtin_msa_maxi_s_w:
3173 case Mips::BI__builtin_msa_maxi_s_d:
3174 case Mips::BI__builtin_msa_mini_s_b:
3175 case Mips::BI__builtin_msa_mini_s_h:
3176 case Mips::BI__builtin_msa_mini_s_w:
3177 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3178 // These intrinsics take an unsigned 8 bit immediate.
3179 case Mips::BI__builtin_msa_andi_b:
3180 case Mips::BI__builtin_msa_nori_b:
3181 case Mips::BI__builtin_msa_ori_b:
3182 case Mips::BI__builtin_msa_shf_b:
3183 case Mips::BI__builtin_msa_shf_h:
3184 case Mips::BI__builtin_msa_shf_w:
3185 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3186 case Mips::BI__builtin_msa_bseli_b:
3187 case Mips::BI__builtin_msa_bmnzi_b:
3188 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3189 // df/n format
3190 // These intrinsics take an unsigned 4 bit immediate.
3191 case Mips::BI__builtin_msa_copy_s_b:
3192 case Mips::BI__builtin_msa_copy_u_b:
3193 case Mips::BI__builtin_msa_insve_b:
3194 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003195 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3196 // These intrinsics take an unsigned 3 bit immediate.
3197 case Mips::BI__builtin_msa_copy_s_h:
3198 case Mips::BI__builtin_msa_copy_u_h:
3199 case Mips::BI__builtin_msa_insve_h:
3200 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003201 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3202 // These intrinsics take an unsigned 2 bit immediate.
3203 case Mips::BI__builtin_msa_copy_s_w:
3204 case Mips::BI__builtin_msa_copy_u_w:
3205 case Mips::BI__builtin_msa_insve_w:
3206 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003207 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3208 // These intrinsics take an unsigned 1 bit immediate.
3209 case Mips::BI__builtin_msa_copy_s_d:
3210 case Mips::BI__builtin_msa_copy_u_d:
3211 case Mips::BI__builtin_msa_insve_d:
3212 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003213 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3214 // Memory offsets and immediate loads.
3215 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00003216 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003217 case Mips::BI__builtin_msa_ldi_h:
3218 case Mips::BI__builtin_msa_ldi_w:
3219 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
Aleksandar Beserminjie5921162018-11-07 11:37:05 +00003220 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3221 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3222 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3223 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3224 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3225 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3226 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3227 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003228 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003229
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003230 if (!m)
3231 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3232
3233 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3234 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003235}
3236
Kit Bartone50adcb2015-03-30 19:40:59 +00003237bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3238 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003239 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3240 BuiltinID == PPC::BI__builtin_divdeu ||
3241 BuiltinID == PPC::BI__builtin_bpermd;
3242 bool IsTarget64Bit = Context.getTargetInfo()
3243 .getTypeWidth(Context
3244 .getTargetInfo()
3245 .getIntPtrType()) == 64;
3246 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3247 BuiltinID == PPC::BI__builtin_divweu ||
3248 BuiltinID == PPC::BI__builtin_divde ||
3249 BuiltinID == PPC::BI__builtin_divdeu;
3250
3251 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003252 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3253 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003254
3255 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3256 (BuiltinID == PPC::BI__builtin_bpermd &&
3257 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003258 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003259 << TheCall->getSourceRange();
3260
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003261 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3262 if (!Context.getTargetInfo().hasFeature("vsx"))
3263 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3264 << TheCall->getSourceRange();
3265 return false;
3266 };
3267
Kit Bartone50adcb2015-03-30 19:40:59 +00003268 switch (BuiltinID) {
3269 default: return false;
3270 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3271 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3272 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3273 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Jinsong Ji53091892019-09-04 14:01:47 +00003274 case PPC::BI__builtin_altivec_dss:
3275 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
Kit Bartone50adcb2015-03-30 19:40:59 +00003276 case PPC::BI__builtin_tbegin:
3277 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3278 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3279 case PPC::BI__builtin_tabortwc:
3280 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3281 case PPC::BI__builtin_tabortwci:
3282 case PPC::BI__builtin_tabortdci:
3283 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3284 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Jinsong Jia71c1992019-09-04 15:22:26 +00003285 case PPC::BI__builtin_altivec_dst:
3286 case PPC::BI__builtin_altivec_dstt:
3287 case PPC::BI__builtin_altivec_dstst:
3288 case PPC::BI__builtin_altivec_dststt:
3289 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003290 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003291 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003292 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003293 case PPC::BI__builtin_unpack_vector_int128:
3294 return SemaVSXCheck(TheCall) ||
3295 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3296 case PPC::BI__builtin_pack_vector_int128:
3297 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003298 }
3299 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3300}
3301
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003302bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3303 CallExpr *TheCall) {
3304 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3305 Expr *Arg = TheCall->getArg(0);
3306 llvm::APSInt AbortCode(32);
3307 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3308 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003309 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003310 << Arg->getSourceRange();
3311 }
3312
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003313 // For intrinsics which take an immediate value as part of the instruction,
3314 // range check them here.
3315 unsigned i = 0, l = 0, u = 0;
3316 switch (BuiltinID) {
3317 default: return false;
3318 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3319 case SystemZ::BI__builtin_s390_verimb:
3320 case SystemZ::BI__builtin_s390_verimh:
3321 case SystemZ::BI__builtin_s390_verimf:
3322 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3323 case SystemZ::BI__builtin_s390_vfaeb:
3324 case SystemZ::BI__builtin_s390_vfaeh:
3325 case SystemZ::BI__builtin_s390_vfaef:
3326 case SystemZ::BI__builtin_s390_vfaebs:
3327 case SystemZ::BI__builtin_s390_vfaehs:
3328 case SystemZ::BI__builtin_s390_vfaefs:
3329 case SystemZ::BI__builtin_s390_vfaezb:
3330 case SystemZ::BI__builtin_s390_vfaezh:
3331 case SystemZ::BI__builtin_s390_vfaezf:
3332 case SystemZ::BI__builtin_s390_vfaezbs:
3333 case SystemZ::BI__builtin_s390_vfaezhs:
3334 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003335 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003336 case SystemZ::BI__builtin_s390_vfidb:
3337 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3338 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003339 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003340 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3341 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3342 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3343 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3344 case SystemZ::BI__builtin_s390_vstrcb:
3345 case SystemZ::BI__builtin_s390_vstrch:
3346 case SystemZ::BI__builtin_s390_vstrcf:
3347 case SystemZ::BI__builtin_s390_vstrczb:
3348 case SystemZ::BI__builtin_s390_vstrczh:
3349 case SystemZ::BI__builtin_s390_vstrczf:
3350 case SystemZ::BI__builtin_s390_vstrcbs:
3351 case SystemZ::BI__builtin_s390_vstrchs:
3352 case SystemZ::BI__builtin_s390_vstrcfs:
3353 case SystemZ::BI__builtin_s390_vstrczbs:
3354 case SystemZ::BI__builtin_s390_vstrczhs:
3355 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003356 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3357 case SystemZ::BI__builtin_s390_vfminsb:
3358 case SystemZ::BI__builtin_s390_vfmaxsb:
3359 case SystemZ::BI__builtin_s390_vfmindb:
3360 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigandb98bf602019-07-12 18:14:51 +00003361 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3362 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003363 }
3364 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003365}
3366
Craig Topper5ba2c502015-11-07 08:08:31 +00003367/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3368/// This checks that the target supports __builtin_cpu_supports and
3369/// that the string argument is constant and valid.
3370static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3371 Expr *Arg = TheCall->getArg(0);
3372
3373 // Check if the argument is a string literal.
3374 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003375 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003376 << Arg->getSourceRange();
3377
3378 // Check the contents of the string.
3379 StringRef Feature =
3380 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3381 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003382 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003383 << Arg->getSourceRange();
3384 return false;
3385}
3386
Craig Topper699ae0c2017-08-10 20:28:30 +00003387/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3388/// This checks that the target supports __builtin_cpu_is and
3389/// that the string argument is constant and valid.
3390static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3391 Expr *Arg = TheCall->getArg(0);
3392
3393 // Check if the argument is a string literal.
3394 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003395 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003396 << Arg->getSourceRange();
3397
3398 // Check the contents of the string.
3399 StringRef Feature =
3400 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3401 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003402 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003403 << Arg->getSourceRange();
3404 return false;
3405}
3406
Craig Toppera7e253e2016-09-23 04:48:31 +00003407// Check if the rounding mode is legal.
3408bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3409 // Indicates if this instruction has rounding control or just SAE.
3410 bool HasRC = false;
3411
3412 unsigned ArgNum = 0;
3413 switch (BuiltinID) {
3414 default:
3415 return false;
3416 case X86::BI__builtin_ia32_vcvttsd2si32:
3417 case X86::BI__builtin_ia32_vcvttsd2si64:
3418 case X86::BI__builtin_ia32_vcvttsd2usi32:
3419 case X86::BI__builtin_ia32_vcvttsd2usi64:
3420 case X86::BI__builtin_ia32_vcvttss2si32:
3421 case X86::BI__builtin_ia32_vcvttss2si64:
3422 case X86::BI__builtin_ia32_vcvttss2usi32:
3423 case X86::BI__builtin_ia32_vcvttss2usi64:
3424 ArgNum = 1;
3425 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003426 case X86::BI__builtin_ia32_maxpd512:
3427 case X86::BI__builtin_ia32_maxps512:
3428 case X86::BI__builtin_ia32_minpd512:
3429 case X86::BI__builtin_ia32_minps512:
3430 ArgNum = 2;
3431 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003432 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3433 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3434 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3435 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3436 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3437 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3438 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3439 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3440 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3441 case X86::BI__builtin_ia32_exp2pd_mask:
3442 case X86::BI__builtin_ia32_exp2ps_mask:
3443 case X86::BI__builtin_ia32_getexppd512_mask:
3444 case X86::BI__builtin_ia32_getexpps512_mask:
3445 case X86::BI__builtin_ia32_rcp28pd_mask:
3446 case X86::BI__builtin_ia32_rcp28ps_mask:
3447 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3448 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3449 case X86::BI__builtin_ia32_vcomisd:
3450 case X86::BI__builtin_ia32_vcomiss:
3451 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3452 ArgNum = 3;
3453 break;
3454 case X86::BI__builtin_ia32_cmppd512_mask:
3455 case X86::BI__builtin_ia32_cmpps512_mask:
3456 case X86::BI__builtin_ia32_cmpsd_mask:
3457 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003458 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003459 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3460 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper902f6492019-05-28 23:26:22 +00003461 case X86::BI__builtin_ia32_getmantpd512_mask:
3462 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003463 case X86::BI__builtin_ia32_maxsd_round_mask:
3464 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003465 case X86::BI__builtin_ia32_minsd_round_mask:
3466 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003467 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3468 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3469 case X86::BI__builtin_ia32_reducepd512_mask:
3470 case X86::BI__builtin_ia32_reduceps512_mask:
3471 case X86::BI__builtin_ia32_rndscalepd_mask:
3472 case X86::BI__builtin_ia32_rndscaleps_mask:
3473 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3474 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3475 ArgNum = 4;
3476 break;
3477 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003478 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003479 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003480 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003481 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003482 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003483 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003484 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Topper902f6492019-05-28 23:26:22 +00003485 case X86::BI__builtin_ia32_getmantsd_round_mask:
3486 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003487 case X86::BI__builtin_ia32_rangepd512_mask:
3488 case X86::BI__builtin_ia32_rangeps512_mask:
3489 case X86::BI__builtin_ia32_rangesd128_round_mask:
3490 case X86::BI__builtin_ia32_rangess128_round_mask:
3491 case X86::BI__builtin_ia32_reducesd_mask:
3492 case X86::BI__builtin_ia32_reducess_mask:
3493 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3494 case X86::BI__builtin_ia32_rndscaless_round_mask:
3495 ArgNum = 5;
3496 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003497 case X86::BI__builtin_ia32_vcvtsd2si64:
3498 case X86::BI__builtin_ia32_vcvtsd2si32:
3499 case X86::BI__builtin_ia32_vcvtsd2usi32:
3500 case X86::BI__builtin_ia32_vcvtsd2usi64:
3501 case X86::BI__builtin_ia32_vcvtss2si32:
3502 case X86::BI__builtin_ia32_vcvtss2si64:
3503 case X86::BI__builtin_ia32_vcvtss2usi32:
3504 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003505 case X86::BI__builtin_ia32_sqrtpd512:
3506 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003507 ArgNum = 1;
3508 HasRC = true;
3509 break;
Craig Topper3614b412018-06-10 06:01:42 +00003510 case X86::BI__builtin_ia32_addpd512:
3511 case X86::BI__builtin_ia32_addps512:
3512 case X86::BI__builtin_ia32_divpd512:
3513 case X86::BI__builtin_ia32_divps512:
3514 case X86::BI__builtin_ia32_mulpd512:
3515 case X86::BI__builtin_ia32_mulps512:
3516 case X86::BI__builtin_ia32_subpd512:
3517 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003518 case X86::BI__builtin_ia32_cvtsi2sd64:
3519 case X86::BI__builtin_ia32_cvtsi2ss32:
3520 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003521 case X86::BI__builtin_ia32_cvtusi2sd64:
3522 case X86::BI__builtin_ia32_cvtusi2ss32:
3523 case X86::BI__builtin_ia32_cvtusi2ss64:
3524 ArgNum = 2;
3525 HasRC = true;
3526 break;
3527 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3528 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3529 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003530 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003531 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003532 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003533 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003534 case X86::BI__builtin_ia32_cvtps2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003535 case X86::BI__builtin_ia32_cvtps2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003536 case X86::BI__builtin_ia32_cvtps2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003537 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3538 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3539 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3540 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3541 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3542 ArgNum = 3;
3543 HasRC = true;
3544 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003545 case X86::BI__builtin_ia32_addss_round_mask:
3546 case X86::BI__builtin_ia32_addsd_round_mask:
3547 case X86::BI__builtin_ia32_divss_round_mask:
3548 case X86::BI__builtin_ia32_divsd_round_mask:
3549 case X86::BI__builtin_ia32_mulss_round_mask:
3550 case X86::BI__builtin_ia32_mulsd_round_mask:
3551 case X86::BI__builtin_ia32_subss_round_mask:
3552 case X86::BI__builtin_ia32_subsd_round_mask:
3553 case X86::BI__builtin_ia32_scalefpd512_mask:
3554 case X86::BI__builtin_ia32_scalefps512_mask:
3555 case X86::BI__builtin_ia32_scalefsd_round_mask:
3556 case X86::BI__builtin_ia32_scalefss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003557 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3558 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3559 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003560 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3561 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3562 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3563 case X86::BI__builtin_ia32_vfmaddss3_mask:
3564 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3565 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003566 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3567 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3568 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3569 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3570 case X86::BI__builtin_ia32_vfmaddps512_mask:
3571 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3572 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3573 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3574 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3575 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3576 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3577 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3578 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3579 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3580 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3581 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003582 ArgNum = 4;
3583 HasRC = true;
3584 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003585 }
3586
3587 llvm::APSInt Result;
3588
3589 // We can't check the value of a dependent argument.
3590 Expr *Arg = TheCall->getArg(ArgNum);
3591 if (Arg->isTypeDependent() || Arg->isValueDependent())
3592 return false;
3593
3594 // Check constant-ness first.
3595 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3596 return true;
3597
3598 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3599 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
Craig Topperce2cb0f2019-09-09 17:48:05 +00003600 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3601 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
Craig Toppera7e253e2016-09-23 04:48:31 +00003602 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3603 Result == 8/*ROUND_NO_EXC*/ ||
Craig Topperce2cb0f2019-09-09 17:48:05 +00003604 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
Craig Toppera7e253e2016-09-23 04:48:31 +00003605 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3606 return false;
3607
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003608 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3609 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003610}
3611
Craig Topperdf5beb22017-03-13 17:16:50 +00003612// Check if the gather/scatter scale is legal.
3613bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3614 CallExpr *TheCall) {
3615 unsigned ArgNum = 0;
3616 switch (BuiltinID) {
3617 default:
3618 return false;
3619 case X86::BI__builtin_ia32_gatherpfdpd:
3620 case X86::BI__builtin_ia32_gatherpfdps:
3621 case X86::BI__builtin_ia32_gatherpfqpd:
3622 case X86::BI__builtin_ia32_gatherpfqps:
3623 case X86::BI__builtin_ia32_scatterpfdpd:
3624 case X86::BI__builtin_ia32_scatterpfdps:
3625 case X86::BI__builtin_ia32_scatterpfqpd:
3626 case X86::BI__builtin_ia32_scatterpfqps:
3627 ArgNum = 3;
3628 break;
3629 case X86::BI__builtin_ia32_gatherd_pd:
3630 case X86::BI__builtin_ia32_gatherd_pd256:
3631 case X86::BI__builtin_ia32_gatherq_pd:
3632 case X86::BI__builtin_ia32_gatherq_pd256:
3633 case X86::BI__builtin_ia32_gatherd_ps:
3634 case X86::BI__builtin_ia32_gatherd_ps256:
3635 case X86::BI__builtin_ia32_gatherq_ps:
3636 case X86::BI__builtin_ia32_gatherq_ps256:
3637 case X86::BI__builtin_ia32_gatherd_q:
3638 case X86::BI__builtin_ia32_gatherd_q256:
3639 case X86::BI__builtin_ia32_gatherq_q:
3640 case X86::BI__builtin_ia32_gatherq_q256:
3641 case X86::BI__builtin_ia32_gatherd_d:
3642 case X86::BI__builtin_ia32_gatherd_d256:
3643 case X86::BI__builtin_ia32_gatherq_d:
3644 case X86::BI__builtin_ia32_gatherq_d256:
3645 case X86::BI__builtin_ia32_gather3div2df:
3646 case X86::BI__builtin_ia32_gather3div2di:
3647 case X86::BI__builtin_ia32_gather3div4df:
3648 case X86::BI__builtin_ia32_gather3div4di:
3649 case X86::BI__builtin_ia32_gather3div4sf:
3650 case X86::BI__builtin_ia32_gather3div4si:
3651 case X86::BI__builtin_ia32_gather3div8sf:
3652 case X86::BI__builtin_ia32_gather3div8si:
3653 case X86::BI__builtin_ia32_gather3siv2df:
3654 case X86::BI__builtin_ia32_gather3siv2di:
3655 case X86::BI__builtin_ia32_gather3siv4df:
3656 case X86::BI__builtin_ia32_gather3siv4di:
3657 case X86::BI__builtin_ia32_gather3siv4sf:
3658 case X86::BI__builtin_ia32_gather3siv4si:
3659 case X86::BI__builtin_ia32_gather3siv8sf:
3660 case X86::BI__builtin_ia32_gather3siv8si:
3661 case X86::BI__builtin_ia32_gathersiv8df:
3662 case X86::BI__builtin_ia32_gathersiv16sf:
3663 case X86::BI__builtin_ia32_gatherdiv8df:
3664 case X86::BI__builtin_ia32_gatherdiv16sf:
3665 case X86::BI__builtin_ia32_gathersiv8di:
3666 case X86::BI__builtin_ia32_gathersiv16si:
3667 case X86::BI__builtin_ia32_gatherdiv8di:
3668 case X86::BI__builtin_ia32_gatherdiv16si:
3669 case X86::BI__builtin_ia32_scatterdiv2df:
3670 case X86::BI__builtin_ia32_scatterdiv2di:
3671 case X86::BI__builtin_ia32_scatterdiv4df:
3672 case X86::BI__builtin_ia32_scatterdiv4di:
3673 case X86::BI__builtin_ia32_scatterdiv4sf:
3674 case X86::BI__builtin_ia32_scatterdiv4si:
3675 case X86::BI__builtin_ia32_scatterdiv8sf:
3676 case X86::BI__builtin_ia32_scatterdiv8si:
3677 case X86::BI__builtin_ia32_scattersiv2df:
3678 case X86::BI__builtin_ia32_scattersiv2di:
3679 case X86::BI__builtin_ia32_scattersiv4df:
3680 case X86::BI__builtin_ia32_scattersiv4di:
3681 case X86::BI__builtin_ia32_scattersiv4sf:
3682 case X86::BI__builtin_ia32_scattersiv4si:
3683 case X86::BI__builtin_ia32_scattersiv8sf:
3684 case X86::BI__builtin_ia32_scattersiv8si:
3685 case X86::BI__builtin_ia32_scattersiv8df:
3686 case X86::BI__builtin_ia32_scattersiv16sf:
3687 case X86::BI__builtin_ia32_scatterdiv8df:
3688 case X86::BI__builtin_ia32_scatterdiv16sf:
3689 case X86::BI__builtin_ia32_scattersiv8di:
3690 case X86::BI__builtin_ia32_scattersiv16si:
3691 case X86::BI__builtin_ia32_scatterdiv8di:
3692 case X86::BI__builtin_ia32_scatterdiv16si:
3693 ArgNum = 4;
3694 break;
3695 }
3696
3697 llvm::APSInt Result;
3698
3699 // We can't check the value of a dependent argument.
3700 Expr *Arg = TheCall->getArg(ArgNum);
3701 if (Arg->isTypeDependent() || Arg->isValueDependent())
3702 return false;
3703
3704 // Check constant-ness first.
3705 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3706 return true;
3707
3708 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3709 return false;
3710
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003711 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3712 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003713}
3714
Craig Topper51738f82018-04-26 20:14:46 +00003715static bool isX86_32Builtin(unsigned BuiltinID) {
3716 // These builtins only work on x86-32 targets.
3717 switch (BuiltinID) {
3718 case X86::BI__builtin_ia32_readeflags_u32:
3719 case X86::BI__builtin_ia32_writeeflags_u32:
3720 return true;
3721 }
3722
3723 return false;
3724}
3725
Craig Topperf0ddc892016-09-23 04:48:27 +00003726bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3727 if (BuiltinID == X86::BI__builtin_cpu_supports)
3728 return SemaBuiltinCpuSupports(*this, TheCall);
3729
Craig Topper699ae0c2017-08-10 20:28:30 +00003730 if (BuiltinID == X86::BI__builtin_cpu_is)
3731 return SemaBuiltinCpuIs(*this, TheCall);
3732
Craig Topper51738f82018-04-26 20:14:46 +00003733 // Check for 32-bit only builtins on a 64-bit target.
3734 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3735 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003736 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003737 diag::err_32_bit_builtin_64_bit_tgt);
3738
Craig Toppera7e253e2016-09-23 04:48:31 +00003739 // If the intrinsic has rounding or SAE make sure its valid.
3740 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3741 return true;
3742
Craig Topperdf5beb22017-03-13 17:16:50 +00003743 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3744 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3745 return true;
3746
Craig Topperf0ddc892016-09-23 04:48:27 +00003747 // For intrinsics which take an immediate value as part of the instruction,
3748 // range check them here.
3749 int i = 0, l = 0, u = 0;
3750 switch (BuiltinID) {
3751 default:
3752 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003753 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003754 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003755 case X86::BI__builtin_ia32_vextractf128_pd256:
3756 case X86::BI__builtin_ia32_vextractf128_ps256:
3757 case X86::BI__builtin_ia32_vextractf128_si256:
3758 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003759 case X86::BI__builtin_ia32_extractf64x4_mask:
3760 case X86::BI__builtin_ia32_extracti64x4_mask:
3761 case X86::BI__builtin_ia32_extractf32x8_mask:
3762 case X86::BI__builtin_ia32_extracti32x8_mask:
3763 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3764 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3765 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3766 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003767 i = 1; l = 0; u = 1;
3768 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003769 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003770 case X86::BI__builtin_ia32_vinsertf128_pd256:
3771 case X86::BI__builtin_ia32_vinsertf128_ps256:
3772 case X86::BI__builtin_ia32_vinsertf128_si256:
3773 case X86::BI__builtin_ia32_insert128i256:
3774 case X86::BI__builtin_ia32_insertf32x8:
3775 case X86::BI__builtin_ia32_inserti32x8:
3776 case X86::BI__builtin_ia32_insertf64x4:
3777 case X86::BI__builtin_ia32_inserti64x4:
3778 case X86::BI__builtin_ia32_insertf64x2_256:
3779 case X86::BI__builtin_ia32_inserti64x2_256:
3780 case X86::BI__builtin_ia32_insertf32x4_256:
3781 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003782 i = 2; l = 0; u = 1;
3783 break;
Craig Topperacf56012018-06-08 00:59:27 +00003784 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003785 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003786 case X86::BI__builtin_ia32_vec_ext_v4si:
3787 case X86::BI__builtin_ia32_vec_ext_v4sf:
3788 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003789 case X86::BI__builtin_ia32_extractf32x4_mask:
3790 case X86::BI__builtin_ia32_extracti32x4_mask:
3791 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3792 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003793 i = 1; l = 0; u = 3;
3794 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003795 case X86::BI_mm_prefetch:
3796 case X86::BI__builtin_ia32_vec_ext_v8hi:
3797 case X86::BI__builtin_ia32_vec_ext_v8si:
3798 i = 1; l = 0; u = 7;
3799 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003800 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003801 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003802 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003803 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003804 case X86::BI__builtin_ia32_vec_set_v4si:
3805 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003806 case X86::BI__builtin_ia32_shuf_f32x4_256:
3807 case X86::BI__builtin_ia32_shuf_f64x2_256:
3808 case X86::BI__builtin_ia32_shuf_i32x4_256:
3809 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003810 case X86::BI__builtin_ia32_insertf64x2_512:
3811 case X86::BI__builtin_ia32_inserti64x2_512:
3812 case X86::BI__builtin_ia32_insertf32x4:
3813 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003814 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003815 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003816 case X86::BI__builtin_ia32_vpermil2pd:
3817 case X86::BI__builtin_ia32_vpermil2pd256:
3818 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003819 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003820 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003821 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003822 case X86::BI__builtin_ia32_cmpb128_mask:
3823 case X86::BI__builtin_ia32_cmpw128_mask:
3824 case X86::BI__builtin_ia32_cmpd128_mask:
3825 case X86::BI__builtin_ia32_cmpq128_mask:
3826 case X86::BI__builtin_ia32_cmpb256_mask:
3827 case X86::BI__builtin_ia32_cmpw256_mask:
3828 case X86::BI__builtin_ia32_cmpd256_mask:
3829 case X86::BI__builtin_ia32_cmpq256_mask:
3830 case X86::BI__builtin_ia32_cmpb512_mask:
3831 case X86::BI__builtin_ia32_cmpw512_mask:
3832 case X86::BI__builtin_ia32_cmpd512_mask:
3833 case X86::BI__builtin_ia32_cmpq512_mask:
3834 case X86::BI__builtin_ia32_ucmpb128_mask:
3835 case X86::BI__builtin_ia32_ucmpw128_mask:
3836 case X86::BI__builtin_ia32_ucmpd128_mask:
3837 case X86::BI__builtin_ia32_ucmpq128_mask:
3838 case X86::BI__builtin_ia32_ucmpb256_mask:
3839 case X86::BI__builtin_ia32_ucmpw256_mask:
3840 case X86::BI__builtin_ia32_ucmpd256_mask:
3841 case X86::BI__builtin_ia32_ucmpq256_mask:
3842 case X86::BI__builtin_ia32_ucmpb512_mask:
3843 case X86::BI__builtin_ia32_ucmpw512_mask:
3844 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003845 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003846 case X86::BI__builtin_ia32_vpcomub:
3847 case X86::BI__builtin_ia32_vpcomuw:
3848 case X86::BI__builtin_ia32_vpcomud:
3849 case X86::BI__builtin_ia32_vpcomuq:
3850 case X86::BI__builtin_ia32_vpcomb:
3851 case X86::BI__builtin_ia32_vpcomw:
3852 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003853 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003854 case X86::BI__builtin_ia32_vec_set_v8hi:
3855 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003856 i = 2; l = 0; u = 7;
3857 break;
Craig Topperacf56012018-06-08 00:59:27 +00003858 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003859 case X86::BI__builtin_ia32_roundps:
3860 case X86::BI__builtin_ia32_roundpd:
3861 case X86::BI__builtin_ia32_roundps256:
3862 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003863 case X86::BI__builtin_ia32_getmantpd128_mask:
3864 case X86::BI__builtin_ia32_getmantpd256_mask:
3865 case X86::BI__builtin_ia32_getmantps128_mask:
3866 case X86::BI__builtin_ia32_getmantps256_mask:
3867 case X86::BI__builtin_ia32_getmantpd512_mask:
3868 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003869 case X86::BI__builtin_ia32_vec_ext_v16qi:
3870 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003871 i = 1; l = 0; u = 15;
3872 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003873 case X86::BI__builtin_ia32_pblendd128:
3874 case X86::BI__builtin_ia32_blendps:
3875 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003876 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003877 case X86::BI__builtin_ia32_roundss:
3878 case X86::BI__builtin_ia32_roundsd:
3879 case X86::BI__builtin_ia32_rangepd128_mask:
3880 case X86::BI__builtin_ia32_rangepd256_mask:
3881 case X86::BI__builtin_ia32_rangepd512_mask:
3882 case X86::BI__builtin_ia32_rangeps128_mask:
3883 case X86::BI__builtin_ia32_rangeps256_mask:
3884 case X86::BI__builtin_ia32_rangeps512_mask:
3885 case X86::BI__builtin_ia32_getmantsd_round_mask:
3886 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003887 case X86::BI__builtin_ia32_vec_set_v16qi:
3888 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003889 i = 2; l = 0; u = 15;
3890 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003891 case X86::BI__builtin_ia32_vec_ext_v32qi:
3892 i = 1; l = 0; u = 31;
3893 break;
Craig Topper39c87102016-05-18 03:18:12 +00003894 case X86::BI__builtin_ia32_cmpps:
3895 case X86::BI__builtin_ia32_cmpss:
3896 case X86::BI__builtin_ia32_cmppd:
3897 case X86::BI__builtin_ia32_cmpsd:
3898 case X86::BI__builtin_ia32_cmpps256:
3899 case X86::BI__builtin_ia32_cmppd256:
3900 case X86::BI__builtin_ia32_cmpps128_mask:
3901 case X86::BI__builtin_ia32_cmppd128_mask:
3902 case X86::BI__builtin_ia32_cmpps256_mask:
3903 case X86::BI__builtin_ia32_cmppd256_mask:
3904 case X86::BI__builtin_ia32_cmpps512_mask:
3905 case X86::BI__builtin_ia32_cmppd512_mask:
3906 case X86::BI__builtin_ia32_cmpsd_mask:
3907 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003908 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003909 i = 2; l = 0; u = 31;
3910 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003911 case X86::BI__builtin_ia32_permdf256:
3912 case X86::BI__builtin_ia32_permdi256:
3913 case X86::BI__builtin_ia32_permdf512:
3914 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003915 case X86::BI__builtin_ia32_vpermilps:
3916 case X86::BI__builtin_ia32_vpermilps256:
3917 case X86::BI__builtin_ia32_vpermilpd512:
3918 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003919 case X86::BI__builtin_ia32_pshufd:
3920 case X86::BI__builtin_ia32_pshufd256:
3921 case X86::BI__builtin_ia32_pshufd512:
3922 case X86::BI__builtin_ia32_pshufhw:
3923 case X86::BI__builtin_ia32_pshufhw256:
3924 case X86::BI__builtin_ia32_pshufhw512:
3925 case X86::BI__builtin_ia32_pshuflw:
3926 case X86::BI__builtin_ia32_pshuflw256:
3927 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003928 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003929 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003930 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003931 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3932 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003933 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3934 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3935 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3936 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3937 case X86::BI__builtin_ia32_rndscaleps_mask:
3938 case X86::BI__builtin_ia32_rndscalepd_mask:
3939 case X86::BI__builtin_ia32_reducepd128_mask:
3940 case X86::BI__builtin_ia32_reducepd256_mask:
3941 case X86::BI__builtin_ia32_reducepd512_mask:
3942 case X86::BI__builtin_ia32_reduceps128_mask:
3943 case X86::BI__builtin_ia32_reduceps256_mask:
3944 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003945 case X86::BI__builtin_ia32_prold512:
3946 case X86::BI__builtin_ia32_prolq512:
3947 case X86::BI__builtin_ia32_prold128:
3948 case X86::BI__builtin_ia32_prold256:
3949 case X86::BI__builtin_ia32_prolq128:
3950 case X86::BI__builtin_ia32_prolq256:
3951 case X86::BI__builtin_ia32_prord512:
3952 case X86::BI__builtin_ia32_prorq512:
3953 case X86::BI__builtin_ia32_prord128:
3954 case X86::BI__builtin_ia32_prord256:
3955 case X86::BI__builtin_ia32_prorq128:
3956 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003957 case X86::BI__builtin_ia32_fpclasspd128_mask:
3958 case X86::BI__builtin_ia32_fpclasspd256_mask:
3959 case X86::BI__builtin_ia32_fpclassps128_mask:
3960 case X86::BI__builtin_ia32_fpclassps256_mask:
3961 case X86::BI__builtin_ia32_fpclassps512_mask:
3962 case X86::BI__builtin_ia32_fpclasspd512_mask:
3963 case X86::BI__builtin_ia32_fpclasssd_mask:
3964 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003965 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3966 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3967 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3968 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3969 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3970 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003971 case X86::BI__builtin_ia32_kshiftliqi:
3972 case X86::BI__builtin_ia32_kshiftlihi:
3973 case X86::BI__builtin_ia32_kshiftlisi:
3974 case X86::BI__builtin_ia32_kshiftlidi:
3975 case X86::BI__builtin_ia32_kshiftriqi:
3976 case X86::BI__builtin_ia32_kshiftrihi:
3977 case X86::BI__builtin_ia32_kshiftrisi:
3978 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003979 i = 1; l = 0; u = 255;
3980 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003981 case X86::BI__builtin_ia32_vperm2f128_pd256:
3982 case X86::BI__builtin_ia32_vperm2f128_ps256:
3983 case X86::BI__builtin_ia32_vperm2f128_si256:
3984 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003985 case X86::BI__builtin_ia32_pblendw128:
3986 case X86::BI__builtin_ia32_pblendw256:
3987 case X86::BI__builtin_ia32_blendps256:
3988 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003989 case X86::BI__builtin_ia32_palignr128:
3990 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003991 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003992 case X86::BI__builtin_ia32_alignq512:
3993 case X86::BI__builtin_ia32_alignd512:
3994 case X86::BI__builtin_ia32_alignd128:
3995 case X86::BI__builtin_ia32_alignd256:
3996 case X86::BI__builtin_ia32_alignq128:
3997 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003998 case X86::BI__builtin_ia32_vcomisd:
3999 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00004000 case X86::BI__builtin_ia32_shuf_f32x4:
4001 case X86::BI__builtin_ia32_shuf_f64x2:
4002 case X86::BI__builtin_ia32_shuf_i32x4:
4003 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00004004 case X86::BI__builtin_ia32_shufpd512:
4005 case X86::BI__builtin_ia32_shufps:
4006 case X86::BI__builtin_ia32_shufps256:
4007 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00004008 case X86::BI__builtin_ia32_dbpsadbw128:
4009 case X86::BI__builtin_ia32_dbpsadbw256:
4010 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00004011 case X86::BI__builtin_ia32_vpshldd128:
4012 case X86::BI__builtin_ia32_vpshldd256:
4013 case X86::BI__builtin_ia32_vpshldd512:
4014 case X86::BI__builtin_ia32_vpshldq128:
4015 case X86::BI__builtin_ia32_vpshldq256:
4016 case X86::BI__builtin_ia32_vpshldq512:
4017 case X86::BI__builtin_ia32_vpshldw128:
4018 case X86::BI__builtin_ia32_vpshldw256:
4019 case X86::BI__builtin_ia32_vpshldw512:
4020 case X86::BI__builtin_ia32_vpshrdd128:
4021 case X86::BI__builtin_ia32_vpshrdd256:
4022 case X86::BI__builtin_ia32_vpshrdd512:
4023 case X86::BI__builtin_ia32_vpshrdq128:
4024 case X86::BI__builtin_ia32_vpshrdq256:
4025 case X86::BI__builtin_ia32_vpshrdq512:
4026 case X86::BI__builtin_ia32_vpshrdw128:
4027 case X86::BI__builtin_ia32_vpshrdw256:
4028 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00004029 i = 2; l = 0; u = 255;
4030 break;
4031 case X86::BI__builtin_ia32_fixupimmpd512_mask:
4032 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4033 case X86::BI__builtin_ia32_fixupimmps512_mask:
4034 case X86::BI__builtin_ia32_fixupimmps512_maskz:
4035 case X86::BI__builtin_ia32_fixupimmsd_mask:
4036 case X86::BI__builtin_ia32_fixupimmsd_maskz:
4037 case X86::BI__builtin_ia32_fixupimmss_mask:
4038 case X86::BI__builtin_ia32_fixupimmss_maskz:
4039 case X86::BI__builtin_ia32_fixupimmpd128_mask:
4040 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4041 case X86::BI__builtin_ia32_fixupimmpd256_mask:
4042 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4043 case X86::BI__builtin_ia32_fixupimmps128_mask:
4044 case X86::BI__builtin_ia32_fixupimmps128_maskz:
4045 case X86::BI__builtin_ia32_fixupimmps256_mask:
4046 case X86::BI__builtin_ia32_fixupimmps256_maskz:
4047 case X86::BI__builtin_ia32_pternlogd512_mask:
4048 case X86::BI__builtin_ia32_pternlogd512_maskz:
4049 case X86::BI__builtin_ia32_pternlogq512_mask:
4050 case X86::BI__builtin_ia32_pternlogq512_maskz:
4051 case X86::BI__builtin_ia32_pternlogd128_mask:
4052 case X86::BI__builtin_ia32_pternlogd128_maskz:
4053 case X86::BI__builtin_ia32_pternlogd256_mask:
4054 case X86::BI__builtin_ia32_pternlogd256_maskz:
4055 case X86::BI__builtin_ia32_pternlogq128_mask:
4056 case X86::BI__builtin_ia32_pternlogq128_maskz:
4057 case X86::BI__builtin_ia32_pternlogq256_mask:
4058 case X86::BI__builtin_ia32_pternlogq256_maskz:
4059 i = 3; l = 0; u = 255;
4060 break;
Craig Topper9625db02017-03-12 22:19:10 +00004061 case X86::BI__builtin_ia32_gatherpfdpd:
4062 case X86::BI__builtin_ia32_gatherpfdps:
4063 case X86::BI__builtin_ia32_gatherpfqpd:
4064 case X86::BI__builtin_ia32_gatherpfqps:
4065 case X86::BI__builtin_ia32_scatterpfdpd:
4066 case X86::BI__builtin_ia32_scatterpfdps:
4067 case X86::BI__builtin_ia32_scatterpfqpd:
4068 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00004069 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00004070 break;
Craig Topper9967a6c2019-06-14 23:23:19 +00004071 case X86::BI__builtin_ia32_reducesd_mask:
4072 case X86::BI__builtin_ia32_reducess_mask:
Craig Topper39c87102016-05-18 03:18:12 +00004073 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4074 case X86::BI__builtin_ia32_rndscaless_round_mask:
4075 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00004076 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004077 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00004078
4079 // Note that we don't force a hard error on the range check here, allowing
4080 // template-generated or macro-generated dead code to potentially have out-of-
4081 // range values. These need to code generate, but don't need to necessarily
4082 // make any sense. We use a warning that defaults to an error.
4083 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004084}
4085
Richard Smith55ce3522012-06-25 20:30:08 +00004086/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4087/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4088/// Returns true when the format fits the function and the FormatStringInfo has
4089/// been populated.
4090bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4091 FormatStringInfo *FSI) {
4092 FSI->HasVAListArg = Format->getFirstArg() == 0;
4093 FSI->FormatIdx = Format->getFormatIdx() - 1;
4094 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004095
Richard Smith55ce3522012-06-25 20:30:08 +00004096 // The way the format attribute works in GCC, the implicit this argument
4097 // of member functions is counted. However, it doesn't appear in our own
4098 // lists, so decrement format_idx in that case.
4099 if (IsCXXMember) {
4100 if(FSI->FormatIdx == 0)
4101 return false;
4102 --FSI->FormatIdx;
4103 if (FSI->FirstDataArg != 0)
4104 --FSI->FirstDataArg;
4105 }
4106 return true;
4107}
Mike Stump11289f42009-09-09 15:08:12 +00004108
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004109/// Checks if a the given expression evaluates to null.
4110///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004111/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00004112static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004113 // If the expression has non-null type, it doesn't evaluate to null.
4114 if (auto nullability
4115 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4116 if (*nullability == NullabilityKind::NonNull)
4117 return false;
4118 }
4119
Ted Kremeneka146db32014-01-17 06:24:47 +00004120 // As a special case, transparent unions initialized with zero are
4121 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004122 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00004123 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4124 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004125 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00004126 if (const InitListExpr *ILE =
4127 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004128 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00004129 }
4130
4131 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00004132 return (!Expr->isValueDependent() &&
4133 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4134 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004135}
4136
4137static void CheckNonNullArgument(Sema &S,
4138 const Expr *ArgExpr,
4139 SourceLocation CallSiteLoc) {
4140 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00004141 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004142 S.PDiag(diag::warn_null_arg)
4143 << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00004144}
4145
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004146bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4147 FormatStringInfo FSI;
4148 if ((GetFormatStringType(Format) == FST_NSString) &&
4149 getFormatStringInfo(Format, false, &FSI)) {
4150 Idx = FSI.FormatIdx;
4151 return true;
4152 }
4153 return false;
4154}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004155
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004156/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004157/// as formatting string to formatting method.
4158static void
4159DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4160 const NamedDecl *FDecl,
4161 Expr **Args,
4162 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004163 unsigned Idx = 0;
4164 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004165 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4166 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004167 Idx = 2;
4168 Format = true;
4169 }
4170 else
4171 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4172 if (S.GetFormatNSStringIdx(I, Idx)) {
4173 Format = true;
4174 break;
4175 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004176 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004177 if (!Format || NumArgs <= Idx)
4178 return;
4179 const Expr *FormatExpr = Args[Idx];
4180 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4181 FormatExpr = CSCE->getSubExpr();
4182 const StringLiteral *FormatString;
4183 if (const ObjCStringLiteral *OSL =
4184 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4185 FormatString = OSL->getString();
4186 else
4187 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4188 if (!FormatString)
4189 return;
4190 if (S.FormatStringHasSArg(FormatString)) {
4191 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4192 << "%s" << 1 << 1;
4193 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4194 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004195 }
4196}
4197
Douglas Gregorb4866e82015-06-19 18:13:19 +00004198/// Determine whether the given type has a non-null nullability annotation.
4199static bool isNonNullType(ASTContext &ctx, QualType type) {
4200 if (auto nullability = type->getNullability(ctx))
4201 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00004202
Douglas Gregorb4866e82015-06-19 18:13:19 +00004203 return false;
4204}
4205
Ted Kremenek2bc73332014-01-17 06:24:43 +00004206static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00004207 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004208 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00004209 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00004210 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004211 assert((FDecl || Proto) && "Need a function declaration or prototype");
4212
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004213 // Already checked by by constant evaluator.
4214 if (S.isConstantEvaluated())
4215 return;
Ted Kremenek9aedc152014-01-17 06:24:56 +00004216 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00004217 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00004218 if (FDecl) {
4219 // Handle the nonnull attribute on the function/method declaration itself.
4220 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4221 if (!NonNull->args_size()) {
4222 // Easy case: all pointer arguments are nonnull.
4223 for (const auto *Arg : Args)
4224 if (S.isValidPointerAttrType(Arg->getType()))
4225 CheckNonNullArgument(S, Arg, CallSiteLoc);
4226 return;
4227 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004228
Joel E. Denny81508102018-03-13 14:51:22 +00004229 for (const ParamIdx &Idx : NonNull->args()) {
4230 unsigned IdxAST = Idx.getASTIndex();
4231 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00004232 continue;
4233 if (NonNullArgs.empty())
4234 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00004235 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004236 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004237 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004238 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004239
Douglas Gregorb4866e82015-06-19 18:13:19 +00004240 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4241 // Handle the nonnull attribute on the parameters of the
4242 // function/method.
4243 ArrayRef<ParmVarDecl*> parms;
4244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4245 parms = FD->parameters();
4246 else
4247 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004248
Douglas Gregorb4866e82015-06-19 18:13:19 +00004249 unsigned ParamIndex = 0;
4250 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4251 I != E; ++I, ++ParamIndex) {
4252 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004253 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004254 isNonNullType(S.Context, PVD->getType())) {
4255 if (NonNullArgs.empty())
4256 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004257
Douglas Gregorb4866e82015-06-19 18:13:19 +00004258 NonNullArgs.set(ParamIndex);
4259 }
4260 }
4261 } else {
4262 // If we have a non-function, non-method declaration but no
4263 // function prototype, try to dig out the function prototype.
4264 if (!Proto) {
4265 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4266 QualType type = VD->getType().getNonReferenceType();
4267 if (auto pointerType = type->getAs<PointerType>())
4268 type = pointerType->getPointeeType();
4269 else if (auto blockType = type->getAs<BlockPointerType>())
4270 type = blockType->getPointeeType();
4271 // FIXME: data member pointers?
4272
4273 // Dig out the function prototype, if there is one.
4274 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004275 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004276 }
4277
4278 // Fill in non-null argument information from the nullability
4279 // information on the parameter types (if we have them).
4280 if (Proto) {
4281 unsigned Index = 0;
4282 for (auto paramType : Proto->getParamTypes()) {
4283 if (isNonNullType(S.Context, paramType)) {
4284 if (NonNullArgs.empty())
4285 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004286
Douglas Gregorb4866e82015-06-19 18:13:19 +00004287 NonNullArgs.set(Index);
4288 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004289
Douglas Gregorb4866e82015-06-19 18:13:19 +00004290 ++Index;
4291 }
4292 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004293 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004294
Douglas Gregorb4866e82015-06-19 18:13:19 +00004295 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004296 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004297 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004298 if (NonNullArgs[ArgIndex])
4299 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004300 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004301}
4302
Richard Smith55ce3522012-06-25 20:30:08 +00004303/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004304/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4305/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004306void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004307 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4308 bool IsMemberFunction, SourceLocation Loc,
4309 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004310 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004311 if (CurContext->isDependentContext())
4312 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004313
Ted Kremenekb8176da2010-09-09 04:33:05 +00004314 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004315 llvm::SmallBitVector CheckedVarArgs;
4316 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004317 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004318 // Only create vector if there are format attributes.
4319 CheckedVarArgs.resize(Args.size());
4320
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004321 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004322 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004323 }
Richard Smithd7293d72013-08-05 18:49:43 +00004324 }
Richard Smith55ce3522012-06-25 20:30:08 +00004325
4326 // Refuse POD arguments that weren't caught by the format string
4327 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004328 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4329 if (CallType != VariadicDoesNotApply &&
4330 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004331 unsigned NumParams = Proto ? Proto->getNumParams()
4332 : FDecl && isa<FunctionDecl>(FDecl)
4333 ? cast<FunctionDecl>(FDecl)->getNumParams()
4334 : FDecl && isa<ObjCMethodDecl>(FDecl)
4335 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4336 : 0;
4337
Alp Toker9cacbab2014-01-20 20:26:09 +00004338 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004339 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004340 if (const Expr *Arg = Args[ArgIdx]) {
4341 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4342 checkVariadicArgument(Arg, CallType);
4343 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004344 }
Richard Smithd7293d72013-08-05 18:49:43 +00004345 }
Mike Stump11289f42009-09-09 15:08:12 +00004346
Douglas Gregorb4866e82015-06-19 18:13:19 +00004347 if (FDecl || Proto) {
4348 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004349
Richard Trieu41bc0992013-06-22 00:20:41 +00004350 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004351 if (FDecl) {
4352 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004353 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004354 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004355 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004356
4357 if (FD)
4358 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004359}
4360
4361/// CheckConstructorCall - Check a constructor call for correctness and safety
4362/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004363void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4364 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004365 const FunctionProtoType *Proto,
4366 SourceLocation Loc) {
4367 VariadicCallType CallType =
4368 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004369 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4370 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004371}
4372
4373/// CheckFunctionCall - Check a direct function call for various correctness
4374/// and safety properties not strictly enforced by the C type system.
4375bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4376 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004377 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4378 isa<CXXMethodDecl>(FDecl);
4379 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4380 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004381 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4382 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004383 Expr** Args = TheCall->getArgs();
4384 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004385
4386 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004387 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004388 // If this is a call to a member operator, hide the first argument
4389 // from checkCall.
4390 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004391 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004392 ++Args;
4393 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004394 } else if (IsMemberFunction)
4395 ImplicitThis =
4396 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4397
4398 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004399 IsMemberFunction, TheCall->getRParenLoc(),
4400 TheCall->getCallee()->getSourceRange(), CallType);
4401
4402 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4403 // None of the checks below are needed for functions that don't have
4404 // simple names (e.g., C++ conversion functions).
4405 if (!FnInfo)
4406 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004407
Richard Trieua7f30b12016-12-06 01:42:28 +00004408 CheckAbsoluteValueFunction(TheCall, FDecl);
4409 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004410
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004411 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004412 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004413
Anna Zaks22122702012-01-17 00:37:07 +00004414 unsigned CMId = FDecl->getMemoryFunctionKind();
4415 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004416 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004417
Anna Zaks201d4892012-01-13 21:52:01 +00004418 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004419 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004420 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004421 else if (CMId == Builtin::BIstrncat)
4422 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004423 else
Anna Zaks22122702012-01-17 00:37:07 +00004424 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004425
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004426 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004427}
4428
Fangrui Song6907ce22018-07-30 19:24:48 +00004429bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004430 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004431 VariadicCallType CallType =
4432 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004433
George Burgess IVce6284b2017-01-28 02:19:40 +00004434 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4435 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004436 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004437
4438 return false;
4439}
4440
Richard Trieu664c4c62013-06-20 21:03:13 +00004441bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4442 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004443 QualType Ty;
4444 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004445 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004446 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004447 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004448 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004449 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004450
Douglas Gregorb4866e82015-06-19 18:13:19 +00004451 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4452 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004453 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004454
Richard Trieu664c4c62013-06-20 21:03:13 +00004455 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004456 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004457 CallType = VariadicDoesNotApply;
4458 } else if (Ty->isBlockPointerType()) {
4459 CallType = VariadicBlock;
4460 } else { // Ty->isFunctionPointerType()
4461 CallType = VariadicFunction;
4462 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004463
George Burgess IVce6284b2017-01-28 02:19:40 +00004464 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004465 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4466 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004467 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004468
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004469 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004470}
4471
Richard Trieu41bc0992013-06-22 00:20:41 +00004472/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4473/// such as function pointers returned from functions.
4474bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004475 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004476 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004477 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004478 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004479 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004480 TheCall->getCallee()->getSourceRange(), CallType);
4481
4482 return false;
4483}
4484
Tim Northovere94a34c2014-03-11 10:49:14 +00004485static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004486 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004487 return false;
4488
JF Bastiendda2cb12016-04-18 18:01:49 +00004489 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004490 switch (Op) {
4491 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004492 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004493 llvm_unreachable("There is no ordering argument for an init");
4494
4495 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004496 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004497 case AtomicExpr::AO__atomic_load_n:
4498 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004499 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4500 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004501
4502 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004503 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004504 case AtomicExpr::AO__atomic_store:
4505 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004506 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4507 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4508 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004509
4510 default:
4511 return true;
4512 }
4513}
4514
Richard Smithfeea8832012-04-12 05:08:17 +00004515ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4516 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004517 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4518 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Erich Keane830909b2019-09-20 19:17:31 +00004519 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4520 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4521 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4522 Op);
4523}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004524
Erich Keane830909b2019-09-20 19:17:31 +00004525ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4526 SourceLocation RParenLoc, MultiExprArg Args,
Michael Liao566b3162019-09-23 18:48:06 +00004527 AtomicExpr::AtomicOp Op,
4528 AtomicArgumentOrder ArgOrder) {
Yaxun Liu39195062017-08-04 18:16:31 +00004529 // All the non-OpenCL operations take one of the following forms.
4530 // The OpenCL operations take the __c11 forms with one extra argument for
4531 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004532 enum {
4533 // C __c11_atomic_init(A *, C)
4534 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004535
Richard Smithfeea8832012-04-12 05:08:17 +00004536 // C __c11_atomic_load(A *, int)
4537 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004538
Richard Smithfeea8832012-04-12 05:08:17 +00004539 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004540 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004541
Eric Fiselier8d662442016-03-30 23:39:56 +00004542 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004543 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004544
Richard Smithfeea8832012-04-12 05:08:17 +00004545 // C __c11_atomic_add(A *, M, int)
4546 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004547
Richard Smithfeea8832012-04-12 05:08:17 +00004548 // C __atomic_exchange_n(A *, CP, int)
4549 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004550
Richard Smithfeea8832012-04-12 05:08:17 +00004551 // void __atomic_exchange(A *, C *, CP, int)
4552 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004553
Richard Smithfeea8832012-04-12 05:08:17 +00004554 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4555 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004556
Richard Smithfeea8832012-04-12 05:08:17 +00004557 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4558 GNUCmpXchg
4559 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004560
Yaxun Liu39195062017-08-04 18:16:31 +00004561 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004562 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4563 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004564 // where:
4565 // C is an appropriate type,
4566 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4567 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4568 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4569 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004570
Yaxun Liu39195062017-08-04 18:16:31 +00004571 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4572 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4573 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004574 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4575 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4576 AtomicExpr::AO__atomic_load,
4577 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004578 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4579 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4580 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4581 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4582 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004583 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4584 Op == AtomicExpr::AO__atomic_store_n ||
4585 Op == AtomicExpr::AO__atomic_exchange_n ||
4586 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4587 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004588 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004589
4590 switch (Op) {
4591 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004592 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004593 Form = Init;
4594 break;
4595
4596 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004597 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004598 case AtomicExpr::AO__atomic_load_n:
4599 Form = Load;
4600 break;
4601
Richard Smithfeea8832012-04-12 05:08:17 +00004602 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004603 Form = LoadCopy;
4604 break;
4605
4606 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004607 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004608 case AtomicExpr::AO__atomic_store:
4609 case AtomicExpr::AO__atomic_store_n:
4610 Form = Copy;
4611 break;
4612
4613 case AtomicExpr::AO__c11_atomic_fetch_add:
4614 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004615 case AtomicExpr::AO__opencl_atomic_fetch_add:
4616 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4617 case AtomicExpr::AO__opencl_atomic_fetch_min:
4618 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004619 case AtomicExpr::AO__atomic_fetch_add:
4620 case AtomicExpr::AO__atomic_fetch_sub:
4621 case AtomicExpr::AO__atomic_add_fetch:
4622 case AtomicExpr::AO__atomic_sub_fetch:
4623 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004624 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004625 case AtomicExpr::AO__c11_atomic_fetch_and:
4626 case AtomicExpr::AO__c11_atomic_fetch_or:
4627 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004628 case AtomicExpr::AO__opencl_atomic_fetch_and:
4629 case AtomicExpr::AO__opencl_atomic_fetch_or:
4630 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004631 case AtomicExpr::AO__atomic_fetch_and:
4632 case AtomicExpr::AO__atomic_fetch_or:
4633 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004634 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004635 case AtomicExpr::AO__atomic_and_fetch:
4636 case AtomicExpr::AO__atomic_or_fetch:
4637 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004638 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004639 Form = Arithmetic;
4640 break;
4641
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004642 case AtomicExpr::AO__atomic_fetch_min:
4643 case AtomicExpr::AO__atomic_fetch_max:
4644 IsMinMax = true;
4645 Form = Arithmetic;
4646 break;
4647
Richard Smithfeea8832012-04-12 05:08:17 +00004648 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004649 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004650 case AtomicExpr::AO__atomic_exchange_n:
4651 Form = Xchg;
4652 break;
4653
4654 case AtomicExpr::AO__atomic_exchange:
4655 Form = GNUXchg;
4656 break;
4657
4658 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4659 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004660 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4661 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004662 Form = C11CmpXchg;
4663 break;
4664
4665 case AtomicExpr::AO__atomic_compare_exchange:
4666 case AtomicExpr::AO__atomic_compare_exchange_n:
4667 Form = GNUCmpXchg;
4668 break;
4669 }
4670
Yaxun Liu39195062017-08-04 18:16:31 +00004671 unsigned AdjustedNumArgs = NumArgs[Form];
4672 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4673 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004674 // Check we have the right number of arguments.
Erich Keane830909b2019-09-20 19:17:31 +00004675 if (Args.size() < AdjustedNumArgs) {
4676 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4677 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4678 << ExprRange;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004679 return ExprError();
Erich Keane830909b2019-09-20 19:17:31 +00004680 } else if (Args.size() > AdjustedNumArgs) {
4681 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004682 diag::err_typecheck_call_too_many_args)
Erich Keane830909b2019-09-20 19:17:31 +00004683 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4684 << ExprRange;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004685 return ExprError();
4686 }
4687
Richard Smithfeea8832012-04-12 05:08:17 +00004688 // Inspect the first argument of the atomic operation.
Erich Keane830909b2019-09-20 19:17:31 +00004689 Expr *Ptr = Args[0];
George Burgess IV92b43a42016-07-21 03:28:13 +00004690 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4691 if (ConvertedPtr.isInvalid())
4692 return ExprError();
4693
4694 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004695 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4696 if (!pointerType) {
Erich Keane830909b2019-09-20 19:17:31 +00004697 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004698 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004699 return ExprError();
4700 }
4701
Richard Smithfeea8832012-04-12 05:08:17 +00004702 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4703 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4704 QualType ValType = AtomTy; // 'C'
4705 if (IsC11) {
4706 if (!AtomTy->isAtomicType()) {
Erich Keane830909b2019-09-20 19:17:31 +00004707 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004708 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004709 return ExprError();
4710 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004711 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004712 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Erich Keane830909b2019-09-20 19:17:31 +00004713 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004714 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4715 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004716 return ExprError();
4717 }
Simon Pilgrimdc4d9082019-10-07 14:25:46 +00004718 ValType = AtomTy->castAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004719 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004720 if (ValType.isConstQualified()) {
Erich Keane830909b2019-09-20 19:17:31 +00004721 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004722 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004723 return ExprError();
4724 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004725 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004726
Richard Smithfeea8832012-04-12 05:08:17 +00004727 // For an arithmetic operation, the implied arithmetic must be well-formed.
4728 if (Form == Arithmetic) {
4729 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004730 if (IsAddSub && !ValType->isIntegerType()
4731 && !ValType->isPointerType()) {
Erich Keane830909b2019-09-20 19:17:31 +00004732 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004733 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004734 return ExprError();
4735 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004736 if (IsMinMax) {
4737 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4738 if (!BT || (BT->getKind() != BuiltinType::Int &&
4739 BT->getKind() != BuiltinType::UInt)) {
Erich Keane830909b2019-09-20 19:17:31 +00004740 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004741 return ExprError();
4742 }
4743 }
4744 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Erich Keane830909b2019-09-20 19:17:31 +00004745 Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004746 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004747 return ExprError();
4748 }
David Majnemere85cff82015-01-28 05:48:06 +00004749 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004750 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004751 diag::err_incomplete_type)) {
4752 return ExprError();
4753 }
Richard Smithfeea8832012-04-12 05:08:17 +00004754 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4755 // For __atomic_*_n operations, the value type must be a scalar integral or
4756 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Erich Keane830909b2019-09-20 19:17:31 +00004757 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004758 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004759 return ExprError();
4760 }
4761
Eli Friedmanaa769812013-09-11 03:49:34 +00004762 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4763 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004764 // For GNU atomics, require a trivially-copyable type. This is not part of
4765 // the GNU atomics specification, but we enforce it for sanity.
Erich Keane830909b2019-09-20 19:17:31 +00004766 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004767 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004768 return ExprError();
4769 }
4770
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004771 switch (ValType.getObjCLifetime()) {
4772 case Qualifiers::OCL_None:
4773 case Qualifiers::OCL_ExplicitNone:
4774 // okay
4775 break;
4776
4777 case Qualifiers::OCL_Weak:
4778 case Qualifiers::OCL_Strong:
4779 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004780 // FIXME: Can this happen? By this point, ValType should be known
4781 // to be trivially copyable.
Erich Keane830909b2019-09-20 19:17:31 +00004782 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004783 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004784 return ExprError();
4785 }
4786
JF Bastien7f0a05a2018-05-25 00:07:09 +00004787 // All atomic operations have an overload which takes a pointer to a volatile
4788 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4789 // into the result or the other operands. Similarly atomic_load takes a
4790 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004791 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004792 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004793 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004794 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4795 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004796 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004797 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004798 ResultType = Context.BoolTy;
4799
Richard Smithfeea8832012-04-12 05:08:17 +00004800 // The type of a parameter passed 'by value'. In the GNU atomics, such
4801 // arguments are actually passed as pointers.
4802 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004803 bool IsPassedByAddress = false;
4804 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004805 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004806 IsPassedByAddress = true;
4807 }
Richard Smithfeea8832012-04-12 05:08:17 +00004808
Michael Liao566b3162019-09-23 18:48:06 +00004809 SmallVector<Expr *, 5> APIOrderedArgs;
4810 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4811 APIOrderedArgs.push_back(Args[0]);
4812 switch (Form) {
4813 case Init:
4814 case Load:
4815 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4816 break;
4817 case LoadCopy:
4818 case Copy:
4819 case Arithmetic:
4820 case Xchg:
4821 APIOrderedArgs.push_back(Args[2]); // Val1
4822 APIOrderedArgs.push_back(Args[1]); // Order
4823 break;
4824 case GNUXchg:
4825 APIOrderedArgs.push_back(Args[2]); // Val1
4826 APIOrderedArgs.push_back(Args[3]); // Val2
4827 APIOrderedArgs.push_back(Args[1]); // Order
4828 break;
4829 case C11CmpXchg:
4830 APIOrderedArgs.push_back(Args[2]); // Val1
4831 APIOrderedArgs.push_back(Args[4]); // Val2
4832 APIOrderedArgs.push_back(Args[1]); // Order
4833 APIOrderedArgs.push_back(Args[3]); // OrderFail
4834 break;
4835 case GNUCmpXchg:
4836 APIOrderedArgs.push_back(Args[2]); // Val1
4837 APIOrderedArgs.push_back(Args[4]); // Val2
4838 APIOrderedArgs.push_back(Args[5]); // Weak
4839 APIOrderedArgs.push_back(Args[1]); // Order
4840 APIOrderedArgs.push_back(Args[3]); // OrderFail
4841 break;
4842 }
4843 } else
4844 APIOrderedArgs.append(Args.begin(), Args.end());
4845
JF Bastien7f0a05a2018-05-25 00:07:09 +00004846 // The first argument's non-CV pointer type is used to deduce the type of
4847 // subsequent arguments, except for:
4848 // - weak flag (always converted to bool)
4849 // - memory order (always converted to int)
4850 // - scope (always converted to int)
Michael Liao566b3162019-09-23 18:48:06 +00004851 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004852 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004853 if (i < NumVals[Form] + 1) {
4854 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004855 case 0:
4856 // The first argument is always a pointer. It has a fixed type.
4857 // It is always dereferenced, a nullptr is undefined.
Michael Liao566b3162019-09-23 18:48:06 +00004858 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004859 // Nothing else to do: we already know all we want about this pointer.
4860 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004861 case 1:
4862 // The second argument is the non-atomic operand. For arithmetic, this
4863 // is always passed by value, and for a compare_exchange it is always
4864 // passed by address. For the rest, GNU uses by-address and C11 uses
4865 // by-value.
4866 assert(Form != Load);
4867 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4868 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004869 else if (Form == Copy || Form == Xchg) {
Michael Liao566b3162019-09-23 18:48:06 +00004870 if (IsPassedByAddress) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004871 // The value pointer is always dereferenced, a nullptr is undefined.
Michael Liao566b3162019-09-23 18:48:06 +00004872 CheckNonNullArgument(*this, APIOrderedArgs[i],
4873 ExprRange.getBegin());
4874 }
Richard Smithfeea8832012-04-12 05:08:17 +00004875 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004876 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004877 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004878 else {
Michael Liao566b3162019-09-23 18:48:06 +00004879 Expr *ValArg = APIOrderedArgs[i];
JF Bastien7f0a05a2018-05-25 00:07:09 +00004880 // The value pointer is always dereferenced, a nullptr is undefined.
Erich Keane830909b2019-09-20 19:17:31 +00004881 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
Alexander Richardson6d989432017-10-15 18:48:14 +00004882 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004883 // Keep address space of non-atomic pointer type.
4884 if (const PointerType *PtrTy =
4885 ValArg->getType()->getAs<PointerType>()) {
4886 AS = PtrTy->getPointeeType().getAddressSpace();
4887 }
4888 Ty = Context.getPointerType(
4889 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4890 }
Richard Smithfeea8832012-04-12 05:08:17 +00004891 break;
4892 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004893 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004894 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4895 if (IsPassedByAddress)
Michael Liao566b3162019-09-23 18:48:06 +00004896 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
Richard Smithfeea8832012-04-12 05:08:17 +00004897 Ty = ByValType;
4898 break;
4899 case 3:
4900 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4901 Ty = Context.BoolTy;
4902 break;
4903 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004904 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004905 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004906 Ty = Context.IntTy;
4907 }
Richard Smithfeea8832012-04-12 05:08:17 +00004908
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004909 InitializedEntity Entity =
4910 InitializedEntity::InitializeParameter(Context, Ty, false);
Michael Liao566b3162019-09-23 18:48:06 +00004911 ExprResult Arg = APIOrderedArgs[i];
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004912 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4913 if (Arg.isInvalid())
4914 return true;
Michael Liao566b3162019-09-23 18:48:06 +00004915 APIOrderedArgs[i] = Arg.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004916 }
4917
Richard Smithfeea8832012-04-12 05:08:17 +00004918 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004919 SmallVector<Expr*, 5> SubExprs;
4920 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004921 switch (Form) {
4922 case Init:
4923 // Note, AtomicExpr::getVal1() has a special case for this atomic.
Michael Liao566b3162019-09-23 18:48:06 +00004924 SubExprs.push_back(APIOrderedArgs[1]); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004925 break;
4926 case Load:
Michael Liao566b3162019-09-23 18:48:06 +00004927 SubExprs.push_back(APIOrderedArgs[1]); // Order
Richard Smithfeea8832012-04-12 05:08:17 +00004928 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004929 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004930 case Copy:
4931 case Arithmetic:
4932 case Xchg:
Michael Liao566b3162019-09-23 18:48:06 +00004933 SubExprs.push_back(APIOrderedArgs[2]); // Order
4934 SubExprs.push_back(APIOrderedArgs[1]); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004935 break;
4936 case GNUXchg:
4937 // Note, AtomicExpr::getVal2() has a special case for this atomic.
Michael Liao566b3162019-09-23 18:48:06 +00004938 SubExprs.push_back(APIOrderedArgs[3]); // Order
4939 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4940 SubExprs.push_back(APIOrderedArgs[2]); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004941 break;
4942 case C11CmpXchg:
Michael Liao566b3162019-09-23 18:48:06 +00004943 SubExprs.push_back(APIOrderedArgs[3]); // Order
4944 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4945 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4946 SubExprs.push_back(APIOrderedArgs[2]); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004947 break;
4948 case GNUCmpXchg:
Michael Liao566b3162019-09-23 18:48:06 +00004949 SubExprs.push_back(APIOrderedArgs[4]); // Order
4950 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4951 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4952 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4953 SubExprs.push_back(APIOrderedArgs[3]); // Weak
Richard Smithfeea8832012-04-12 05:08:17 +00004954 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004955 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004956
4957 if (SubExprs.size() >= 2 && Form != Init) {
4958 llvm::APSInt Result(32);
4959 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4960 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004961 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004962 diag::warn_atomic_op_has_invalid_memory_order)
4963 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004964 }
4965
Yaxun Liu30d652a2017-08-15 16:02:49 +00004966 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
Erich Keane830909b2019-09-20 19:17:31 +00004967 auto *Scope = Args[Args.size() - 1];
Yaxun Liu30d652a2017-08-15 16:02:49 +00004968 llvm::APSInt Result(32);
4969 if (Scope->isIntegerConstantExpr(Result, Context) &&
4970 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004971 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004972 << Scope->getSourceRange();
4973 }
4974 SubExprs.push_back(Scope);
4975 }
4976
Erich Keane830909b2019-09-20 19:17:31 +00004977 AtomicExpr *AE = new (Context)
4978 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00004979
Fariborz Jahanian615de762013-05-28 17:37:39 +00004980 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004981 Op == AtomicExpr::AO__c11_atomic_store ||
4982 Op == AtomicExpr::AO__opencl_atomic_load ||
4983 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004984 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004985 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004986 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004987 Op == AtomicExpr::AO__opencl_atomic_load)
4988 ? 0
4989 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004990
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004991 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004992}
4993
John McCall29ad95b2011-08-27 01:09:30 +00004994/// checkBuiltinArgument - Given a call to a builtin function, perform
4995/// normal type-checking on the given argument, updating the call in
4996/// place. This is useful when a builtin function requires custom
4997/// type-checking for some of its arguments but not necessarily all of
4998/// them.
4999///
5000/// Returns true on error.
5001static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5002 FunctionDecl *Fn = E->getDirectCallee();
5003 assert(Fn && "builtin call without direct callee!");
5004
5005 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5006 InitializedEntity Entity =
5007 InitializedEntity::InitializeParameter(S.Context, Param);
5008
5009 ExprResult Arg = E->getArg(0);
5010 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5011 if (Arg.isInvalid())
5012 return true;
5013
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005014 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00005015 return false;
5016}
5017
JF Bastiene77b48b2018-09-10 20:42:56 +00005018/// We have a call to a function like __sync_fetch_and_add, which is an
5019/// overloaded function based on the pointer type of its first argument.
Richard Smith255b85f2019-05-08 01:36:36 +00005020/// The main BuildCallExpr routines have already promoted the types of
JF Bastiene77b48b2018-09-10 20:42:56 +00005021/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00005022///
5023/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00005024/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00005025ExprResult
5026Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00005027 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5028 Expr *Callee = TheCall->getCallee();
5029 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00005030 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5031
5032 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005033 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005034 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00005035 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005036 return ExprError();
5037 }
Mike Stump11289f42009-09-09 15:08:12 +00005038
Chris Lattnerdc046542009-05-08 06:58:22 +00005039 // Inspect the first argument of the atomic builtin. This should always be
5040 // a pointer type, whose element is an integral scalar or pointer type.
5041 // Because it is a pointer type, we don't have to worry about any implicit
5042 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005043 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00005044 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00005045 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5046 if (FirstArgResult.isInvalid())
5047 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005048 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00005049 TheCall->setArg(0, FirstArg);
5050
John McCall31168b02011-06-15 23:02:42 +00005051 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5052 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005053 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5054 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005055 return ExprError();
5056 }
Mike Stump11289f42009-09-09 15:08:12 +00005057
John McCall31168b02011-06-15 23:02:42 +00005058 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00005059 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005060 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005061 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5062 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005063 return ExprError();
5064 }
Chris Lattnerdc046542009-05-08 06:58:22 +00005065
Aaron Ballmana383c942018-05-05 17:38:42 +00005066 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005067 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00005068 << FirstArg->getType() << FirstArg->getSourceRange();
5069 return ExprError();
5070 }
5071
John McCall31168b02011-06-15 23:02:42 +00005072 switch (ValType.getObjCLifetime()) {
5073 case Qualifiers::OCL_None:
5074 case Qualifiers::OCL_ExplicitNone:
5075 // okay
5076 break;
5077
5078 case Qualifiers::OCL_Weak:
5079 case Qualifiers::OCL_Strong:
5080 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005081 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5082 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00005083 return ExprError();
5084 }
5085
John McCallb50451a2011-10-05 07:41:44 +00005086 // Strip any qualifiers off ValType.
5087 ValType = ValType.getUnqualifiedType();
5088
Chandler Carruth3973af72010-07-18 20:54:12 +00005089 // The majority of builtins return a value, but a few have special return
5090 // types, so allow them to override appropriately below.
5091 QualType ResultType = ValType;
5092
Chris Lattnerdc046542009-05-08 06:58:22 +00005093 // We need to figure out which concrete builtin this maps onto. For example,
5094 // __sync_fetch_and_add with a 2 byte object turns into
5095 // __sync_fetch_and_add_2.
5096#define BUILTIN_ROW(x) \
5097 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5098 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00005099
Chris Lattnerdc046542009-05-08 06:58:22 +00005100 static const unsigned BuiltinIndices[][5] = {
5101 BUILTIN_ROW(__sync_fetch_and_add),
5102 BUILTIN_ROW(__sync_fetch_and_sub),
5103 BUILTIN_ROW(__sync_fetch_and_or),
5104 BUILTIN_ROW(__sync_fetch_and_and),
5105 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00005106 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00005107
Chris Lattnerdc046542009-05-08 06:58:22 +00005108 BUILTIN_ROW(__sync_add_and_fetch),
5109 BUILTIN_ROW(__sync_sub_and_fetch),
5110 BUILTIN_ROW(__sync_and_and_fetch),
5111 BUILTIN_ROW(__sync_or_and_fetch),
5112 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00005113 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00005114
Chris Lattnerdc046542009-05-08 06:58:22 +00005115 BUILTIN_ROW(__sync_val_compare_and_swap),
5116 BUILTIN_ROW(__sync_bool_compare_and_swap),
5117 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00005118 BUILTIN_ROW(__sync_lock_release),
5119 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00005120 };
Mike Stump11289f42009-09-09 15:08:12 +00005121#undef BUILTIN_ROW
5122
Chris Lattnerdc046542009-05-08 06:58:22 +00005123 // Determine the index of the size.
5124 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00005125 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00005126 case 1: SizeIndex = 0; break;
5127 case 2: SizeIndex = 1; break;
5128 case 4: SizeIndex = 2; break;
5129 case 8: SizeIndex = 3; break;
5130 case 16: SizeIndex = 4; break;
5131 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005132 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5133 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005134 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00005135 }
Mike Stump11289f42009-09-09 15:08:12 +00005136
Chris Lattnerdc046542009-05-08 06:58:22 +00005137 // Each of these builtins has one pointer argument, followed by some number of
5138 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5139 // that we ignore. Find out which row of BuiltinIndices to read from as well
5140 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005141 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00005142 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00005143 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00005144 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00005145 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00005146 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00005147 case Builtin::BI__sync_fetch_and_add_1:
5148 case Builtin::BI__sync_fetch_and_add_2:
5149 case Builtin::BI__sync_fetch_and_add_4:
5150 case Builtin::BI__sync_fetch_and_add_8:
5151 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005152 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00005153 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005154
5155 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00005156 case Builtin::BI__sync_fetch_and_sub_1:
5157 case Builtin::BI__sync_fetch_and_sub_2:
5158 case Builtin::BI__sync_fetch_and_sub_4:
5159 case Builtin::BI__sync_fetch_and_sub_8:
5160 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005161 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00005162 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005163
5164 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00005165 case Builtin::BI__sync_fetch_and_or_1:
5166 case Builtin::BI__sync_fetch_and_or_2:
5167 case Builtin::BI__sync_fetch_and_or_4:
5168 case Builtin::BI__sync_fetch_and_or_8:
5169 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005170 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00005171 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005172
5173 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00005174 case Builtin::BI__sync_fetch_and_and_1:
5175 case Builtin::BI__sync_fetch_and_and_2:
5176 case Builtin::BI__sync_fetch_and_and_4:
5177 case Builtin::BI__sync_fetch_and_and_8:
5178 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005179 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00005180 break;
Mike Stump11289f42009-09-09 15:08:12 +00005181
Fangrui Song6907ce22018-07-30 19:24:48 +00005182 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00005183 case Builtin::BI__sync_fetch_and_xor_1:
5184 case Builtin::BI__sync_fetch_and_xor_2:
5185 case Builtin::BI__sync_fetch_and_xor_4:
5186 case Builtin::BI__sync_fetch_and_xor_8:
5187 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005188 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00005189 break;
5190
Fangrui Song6907ce22018-07-30 19:24:48 +00005191 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00005192 case Builtin::BI__sync_fetch_and_nand_1:
5193 case Builtin::BI__sync_fetch_and_nand_2:
5194 case Builtin::BI__sync_fetch_and_nand_4:
5195 case Builtin::BI__sync_fetch_and_nand_8:
5196 case Builtin::BI__sync_fetch_and_nand_16:
5197 BuiltinIndex = 5;
5198 WarnAboutSemanticsChange = true;
5199 break;
5200
Fangrui Song6907ce22018-07-30 19:24:48 +00005201 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005202 case Builtin::BI__sync_add_and_fetch_1:
5203 case Builtin::BI__sync_add_and_fetch_2:
5204 case Builtin::BI__sync_add_and_fetch_4:
5205 case Builtin::BI__sync_add_and_fetch_8:
5206 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005207 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00005208 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005209
5210 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005211 case Builtin::BI__sync_sub_and_fetch_1:
5212 case Builtin::BI__sync_sub_and_fetch_2:
5213 case Builtin::BI__sync_sub_and_fetch_4:
5214 case Builtin::BI__sync_sub_and_fetch_8:
5215 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005216 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00005217 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005218
5219 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005220 case Builtin::BI__sync_and_and_fetch_1:
5221 case Builtin::BI__sync_and_and_fetch_2:
5222 case Builtin::BI__sync_and_and_fetch_4:
5223 case Builtin::BI__sync_and_and_fetch_8:
5224 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005225 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00005226 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005227
5228 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005229 case Builtin::BI__sync_or_and_fetch_1:
5230 case Builtin::BI__sync_or_and_fetch_2:
5231 case Builtin::BI__sync_or_and_fetch_4:
5232 case Builtin::BI__sync_or_and_fetch_8:
5233 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005234 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00005235 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005236
5237 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005238 case Builtin::BI__sync_xor_and_fetch_1:
5239 case Builtin::BI__sync_xor_and_fetch_2:
5240 case Builtin::BI__sync_xor_and_fetch_4:
5241 case Builtin::BI__sync_xor_and_fetch_8:
5242 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005243 BuiltinIndex = 10;
5244 break;
5245
Fangrui Song6907ce22018-07-30 19:24:48 +00005246 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00005247 case Builtin::BI__sync_nand_and_fetch_1:
5248 case Builtin::BI__sync_nand_and_fetch_2:
5249 case Builtin::BI__sync_nand_and_fetch_4:
5250 case Builtin::BI__sync_nand_and_fetch_8:
5251 case Builtin::BI__sync_nand_and_fetch_16:
5252 BuiltinIndex = 11;
5253 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00005254 break;
Mike Stump11289f42009-09-09 15:08:12 +00005255
Chris Lattnerdc046542009-05-08 06:58:22 +00005256 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005257 case Builtin::BI__sync_val_compare_and_swap_1:
5258 case Builtin::BI__sync_val_compare_and_swap_2:
5259 case Builtin::BI__sync_val_compare_and_swap_4:
5260 case Builtin::BI__sync_val_compare_and_swap_8:
5261 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005262 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00005263 NumFixed = 2;
5264 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005265
Chris Lattnerdc046542009-05-08 06:58:22 +00005266 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005267 case Builtin::BI__sync_bool_compare_and_swap_1:
5268 case Builtin::BI__sync_bool_compare_and_swap_2:
5269 case Builtin::BI__sync_bool_compare_and_swap_4:
5270 case Builtin::BI__sync_bool_compare_and_swap_8:
5271 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005272 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00005273 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00005274 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005275 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005276
JF Bastien7f0a05a2018-05-25 00:07:09 +00005277 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00005278 case Builtin::BI__sync_lock_test_and_set_1:
5279 case Builtin::BI__sync_lock_test_and_set_2:
5280 case Builtin::BI__sync_lock_test_and_set_4:
5281 case Builtin::BI__sync_lock_test_and_set_8:
5282 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005283 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00005284 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005285
Chris Lattnerdc046542009-05-08 06:58:22 +00005286 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00005287 case Builtin::BI__sync_lock_release_1:
5288 case Builtin::BI__sync_lock_release_2:
5289 case Builtin::BI__sync_lock_release_4:
5290 case Builtin::BI__sync_lock_release_8:
5291 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005292 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005293 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005294 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005295 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005296
5297 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005298 case Builtin::BI__sync_swap_1:
5299 case Builtin::BI__sync_swap_2:
5300 case Builtin::BI__sync_swap_4:
5301 case Builtin::BI__sync_swap_8:
5302 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005303 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005304 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Chris Lattnerdc046542009-05-08 06:58:22 +00005307 // Now that we know how many fixed arguments we expect, first check that we
5308 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005309 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005310 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5311 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005312 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005313 return ExprError();
5314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
JF Bastiene77b48b2018-09-10 20:42:56 +00005316 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5317 << Callee->getSourceRange();
5318
Hal Finkeld2208b52014-10-02 20:53:50 +00005319 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005320 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005321 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005322 }
5323
Chris Lattner5b9241b2009-05-08 15:36:58 +00005324 // Get the decl for the concrete builtin from this, we can tell what the
5325 // concrete integer type we should convert to is.
5326 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005327 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005328 FunctionDecl *NewBuiltinDecl;
5329 if (NewBuiltinID == BuiltinID)
5330 NewBuiltinDecl = FDecl;
5331 else {
5332 // Perform builtin lookup to avoid redeclaring it.
5333 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005334 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005335 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5336 assert(Res.getFoundDecl());
5337 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005338 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005339 return ExprError();
5340 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005341
John McCallcf142162010-08-07 06:22:56 +00005342 // The first argument --- the pointer --- has a fixed type; we
5343 // deduce the types of the rest of the arguments accordingly. Walk
5344 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005345 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005346 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005347
Chris Lattnerdc046542009-05-08 06:58:22 +00005348 // GCC does an implicit conversion to the pointer or integer ValType. This
5349 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005350 // Initialize the argument.
5351 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5352 ValType, /*consume*/ false);
5353 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005354 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005355 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005356
Chris Lattnerdc046542009-05-08 06:58:22 +00005357 // Okay, we have something that *can* be converted to the right type. Check
5358 // to see if there is a potentially weird extension going on here. This can
5359 // happen when you do an atomic operation on something like an char* and
5360 // pass in 42. The 42 gets converted to char. This is even more strange
5361 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005362 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005363 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005364 }
Mike Stump11289f42009-09-09 15:08:12 +00005365
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005366 // Create a new DeclRefExpr to refer to the new decl.
Richard Smith715f7a12019-06-11 17:50:32 +00005367 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5368 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5369 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5370 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
Mike Stump11289f42009-09-09 15:08:12 +00005371
Chris Lattnerdc046542009-05-08 06:58:22 +00005372 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005373 // FIXME: This loses syntactic information.
5374 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5375 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5376 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005378
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005379 // Change the result type of the call to match the original value type. This
5380 // is arbitrary, but the codegen for these builtins ins design to handle it
5381 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005382 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005383
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005384 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005385}
5386
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005387/// SemaBuiltinNontemporalOverloaded - We have a call to
5388/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5389/// overloaded function based on the pointer type of its last argument.
5390///
5391/// This function goes through and does final semantic checking for these
5392/// builtins.
5393ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5394 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5395 DeclRefExpr *DRE =
5396 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5397 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5398 unsigned BuiltinID = FDecl->getBuiltinID();
5399 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5400 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5401 "Unexpected nontemporal load/store builtin!");
5402 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5403 unsigned numArgs = isStore ? 2 : 1;
5404
5405 // Ensure that we have the proper number of arguments.
5406 if (checkArgCount(*this, TheCall, numArgs))
5407 return ExprError();
5408
5409 // Inspect the last argument of the nontemporal builtin. This should always
5410 // be a pointer type, from which we imply the type of the memory access.
5411 // Because it is a pointer type, we don't have to worry about any implicit
5412 // casts here.
5413 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5414 ExprResult PointerArgResult =
5415 DefaultFunctionArrayLvalueConversion(PointerArg);
5416
5417 if (PointerArgResult.isInvalid())
5418 return ExprError();
5419 PointerArg = PointerArgResult.get();
5420 TheCall->setArg(numArgs - 1, PointerArg);
5421
5422 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5423 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005424 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005425 << PointerArg->getType() << PointerArg->getSourceRange();
5426 return ExprError();
5427 }
5428
5429 QualType ValType = pointerType->getPointeeType();
5430
5431 // Strip any qualifiers off ValType.
5432 ValType = ValType.getUnqualifiedType();
5433 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5434 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5435 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005436 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005437 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5438 << PointerArg->getType() << PointerArg->getSourceRange();
5439 return ExprError();
5440 }
5441
5442 if (!isStore) {
5443 TheCall->setType(ValType);
5444 return TheCallResult;
5445 }
5446
5447 ExprResult ValArg = TheCall->getArg(0);
5448 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5449 Context, ValType, /*consume*/ false);
5450 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5451 if (ValArg.isInvalid())
5452 return ExprError();
5453
5454 TheCall->setArg(0, ValArg.get());
5455 TheCall->setType(Context.VoidTy);
5456 return TheCallResult;
5457}
5458
Chris Lattner6436fb62009-02-18 06:01:06 +00005459/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005460/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005461/// Note: It might also make sense to do the UTF-16 conversion here (would
5462/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005463bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005464 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005465 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5466
Douglas Gregorfb65e592011-07-27 05:40:30 +00005467 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005468 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5469 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005470 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005473 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005474 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005475 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005476 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5477 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5478 llvm::UTF16 *ToPtr = &ToBuf[0];
5479
5480 llvm::ConversionResult Result =
5481 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5482 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005483 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005484 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005485 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5486 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005487 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005488 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005489}
5490
Mehdi Amini06d367c2016-10-24 20:39:34 +00005491/// CheckObjCString - Checks that the format string argument to the os_log()
5492/// and os_trace() functions is correct, and converts it to const char *.
5493ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5494 Arg = Arg->IgnoreParenCasts();
5495 auto *Literal = dyn_cast<StringLiteral>(Arg);
5496 if (!Literal) {
5497 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5498 Literal = ObjcLiteral->getString();
5499 }
5500 }
5501
5502 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5503 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005504 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005505 << Arg->getSourceRange());
5506 }
5507
5508 ExprResult Result(Literal);
5509 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5510 InitializedEntity Entity =
5511 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5512 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5513 return Result;
5514}
5515
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005516/// Check that the user is calling the appropriate va_start builtin for the
5517/// target and calling convention.
5518static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5519 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5520 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Tim Northover44e58792018-09-18 10:34:39 +01005521 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5522 TT.getArch() == llvm::Triple::aarch64_32);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005523 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005524 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5525 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005526 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005527 if (const FunctionDecl *FD = S.getCurFunctionDecl())
Simon Pilgrimdc4d9082019-10-07 14:25:46 +00005528 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005529 if (IsMSVAStart) {
5530 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005531 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005532 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005533 diag::err_ms_va_start_used_in_sysv_function);
5534 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005535 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005536 // On x64 Windows, don't allow this in System V ABI functions.
5537 // (Yes, that means there's no corresponding way to support variadic
5538 // System V ABI functions on Windows.)
5539 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005540 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005541 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005542 diag::err_va_start_used_in_wrong_abi_function)
5543 << !IsWindows;
5544 }
5545 return false;
5546 }
5547
5548 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005549 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005550 return false;
5551}
5552
5553static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5554 ParmVarDecl **LastParam = nullptr) {
5555 // Determine whether the current function, block, or obj-c method is variadic
5556 // and get its parameter list.
5557 bool IsVariadic = false;
5558 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005559 DeclContext *Caller = S.CurContext;
5560 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5561 IsVariadic = Block->isVariadic();
5562 Params = Block->parameters();
5563 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005564 IsVariadic = FD->isVariadic();
5565 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005566 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005567 IsVariadic = MD->isVariadic();
5568 // FIXME: This isn't correct for methods (results in bogus warning).
5569 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005570 } else if (isa<CapturedDecl>(Caller)) {
5571 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005572 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005573 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005574 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005575 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005576 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005577 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005578 }
5579
5580 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005581 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005582 return true;
5583 }
5584
5585 if (LastParam)
5586 *LastParam = Params.empty() ? nullptr : Params.back();
5587
5588 return false;
5589}
5590
Aaron Ballman68d50642018-06-19 14:53:20 +00005591/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5592/// for validity. Emit an error and return true on failure; return false
5593/// on success.
5594bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5595 Expr *Fn = TheCall->getCallee();
5596
5597 if (checkVAStartABI(*this, BuiltinID, Fn))
5598 return true;
5599
5600 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005601 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005602 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005603 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5604 << Fn->getSourceRange()
5605 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005606 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005607 return true;
5608 }
5609
5610 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005611 return Diag(TheCall->getEndLoc(),
5612 diag::err_typecheck_call_too_few_args_at_least)
5613 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005614 }
5615
5616 // Type-check the first argument normally.
5617 if (checkBuiltinArgument(*this, TheCall, 0))
5618 return true;
5619
5620 // Check that the current function is variadic, and get its last parameter.
5621 ParmVarDecl *LastParam;
5622 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5623 return true;
5624
5625 // Verify that the second argument to the builtin is the last argument of the
5626 // current function or method.
5627 bool SecondArgIsLastNamedArgument = false;
5628 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5629
5630 // These are valid if SecondArgIsLastNamedArgument is false after the next
5631 // block.
5632 QualType Type;
5633 SourceLocation ParamLoc;
5634 bool IsCRegister = false;
5635
5636 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5637 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5638 SecondArgIsLastNamedArgument = PV == LastParam;
5639
5640 Type = PV->getType();
5641 ParamLoc = PV->getLocation();
5642 IsCRegister =
5643 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5644 }
5645 }
5646
5647 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005648 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005649 diag::warn_second_arg_of_va_start_not_last_named_param);
5650 else if (IsCRegister || Type->isReferenceType() ||
5651 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5652 // Promotable integers are UB, but enumerations need a bit of
5653 // extra checking to see what their promotable type actually is.
5654 if (!Type->isPromotableIntegerType())
5655 return false;
5656 if (!Type->isEnumeralType())
5657 return true;
Simon Pilgrimdc4d9082019-10-07 14:25:46 +00005658 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
Aaron Ballman68d50642018-06-19 14:53:20 +00005659 return !(ED &&
5660 Context.typesAreCompatible(ED->getPromotionType(), Type));
5661 }()) {
5662 unsigned Reason = 0;
5663 if (Type->isReferenceType()) Reason = 1;
5664 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005665 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005666 Diag(ParamLoc, diag::note_parameter_type) << Type;
5667 }
5668
5669 TheCall->setType(Context.VoidTy);
5670 return false;
5671}
5672
5673bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5674 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5675 // const char *named_addr);
5676
5677 Expr *Func = Call->getCallee();
5678
5679 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005680 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005681 diag::err_typecheck_call_too_few_args_at_least)
5682 << 0 /*function call*/ << 3 << Call->getNumArgs();
5683
5684 // Type-check the first argument normally.
5685 if (checkBuiltinArgument(*this, Call, 0))
5686 return true;
5687
5688 // Check that the current function is variadic.
5689 if (checkVAStartIsInVariadicFunction(*this, Func))
5690 return true;
5691
5692 // __va_start on Windows does not validate the parameter qualifiers
5693
5694 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5695 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5696
5697 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5698 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5699
5700 const QualType &ConstCharPtrTy =
5701 Context.getPointerType(Context.CharTy.withConst());
5702 if (!Arg1Ty->isPointerType() ||
5703 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005704 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5705 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5706 << 0 /* qualifier difference */
5707 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005708 << 2 << Arg1->getType() << ConstCharPtrTy;
5709
5710 const QualType SizeTy = Context.getSizeType();
5711 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005712 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5713 << Arg2->getType() << SizeTy << 1 /* different class */
5714 << 0 /* qualifier difference */
5715 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005716 << 3 << Arg2->getType() << SizeTy;
5717
5718 return false;
5719}
5720
5721/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5722/// friends. This is declared to take (...), so we have to check everything.
5723bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5724 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005725 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5726 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005727 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005728 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005729 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005730 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5731 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005732 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005733
5734 ExprResult OrigArg0 = TheCall->getArg(0);
5735 ExprResult OrigArg1 = TheCall->getArg(1);
5736
5737 // Do standard promotions between the two arguments, returning their common
5738 // type.
5739 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5740 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5741 return true;
5742
5743 // Make sure any conversions are pushed back into the call; this is
5744 // type safe since unordered compare builtins are declared as "_Bool
5745 // foo(...)".
5746 TheCall->setArg(0, OrigArg0.get());
5747 TheCall->setArg(1, OrigArg1.get());
5748
5749 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5750 return false;
5751
5752 // If the common type isn't a real floating type, then the arguments were
5753 // invalid for this operation.
5754 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005755 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005756 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005757 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5758 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005759 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005760
5761 return false;
5762}
5763
5764/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5765/// __builtin_isnan and friends. This is declared to take (...), so we have
5766/// to check everything. We expect the last argument to be a floating point
5767/// value.
5768bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5769 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005770 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5771 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005772 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005773 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005774 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005775 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5776 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005777 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005778
5779 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5780
5781 if (OrigArg->isTypeDependent())
5782 return false;
5783
5784 // This operation requires a non-_Complex floating-point number.
5785 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005786 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005787 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005788 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005789
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005790 // If this is an implicit conversion from float -> float, double, or
5791 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005792 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5793 // Only remove standard FloatCasts, leaving other casts inplace
5794 if (Cast->getCastKind() == CK_FloatingCast) {
5795 Expr *CastArg = Cast->getSubExpr();
5796 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005797 assert(
5798 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5799 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5800 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5801 "promotion from float to either float, double, or long double is "
5802 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005803 Cast->setSubExpr(nullptr);
5804 TheCall->setArg(NumArgs-1, CastArg);
5805 }
5806 }
5807 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005808
Aaron Ballman68d50642018-06-19 14:53:20 +00005809 return false;
5810}
5811
5812// Customized Sema Checking for VSX builtins that have the following signature:
5813// vector [...] builtinName(vector [...], vector [...], const int);
5814// Which takes the same type of vectors (any legal vector type) for the first
5815// two arguments and takes compile time constant for the third argument.
5816// Example builtins are :
5817// vector double vec_xxpermdi(vector double, vector double, int);
5818// vector short vec_xxsldwi(vector short, vector short, int);
5819bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5820 unsigned ExpectedNumArgs = 3;
5821 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005822 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005823 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005824 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005825 << TheCall->getSourceRange();
5826
5827 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005828 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005829 diag::err_typecheck_call_too_many_args_at_most)
5830 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5831 << TheCall->getSourceRange();
5832
5833 // Check the third argument is a compile time constant
5834 llvm::APSInt Value;
5835 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005836 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005837 diag::err_vsx_builtin_nonconstant_argument)
5838 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005839 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005840 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005841
5842 QualType Arg1Ty = TheCall->getArg(0)->getType();
5843 QualType Arg2Ty = TheCall->getArg(1)->getType();
5844
5845 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005846 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005847 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5848 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5849 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5850 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005851 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005852 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005853 }
5854
5855 // Check the first two arguments are the same type.
5856 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5857 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5858 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005859 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005860 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005861 }
5862
5863 // When default clang type checking is turned off and the customized type
5864 // checking is used, the returning type of the function must be explicitly
5865 // set. Otherwise it is _Bool by default.
5866 TheCall->setType(Arg1Ty);
5867
5868 return false;
5869}
5870
5871/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5872// This is declared to take (...), so we have to check everything.
5873ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5874 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005875 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005876 diag::err_typecheck_call_too_few_args_at_least)
5877 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5878 << TheCall->getSourceRange());
5879
5880 // Determine which of the following types of shufflevector we're checking:
5881 // 1) unary, vector mask: (lhs, mask)
5882 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5883 QualType resType = TheCall->getArg(0)->getType();
5884 unsigned numElements = 0;
5885
5886 if (!TheCall->getArg(0)->isTypeDependent() &&
5887 !TheCall->getArg(1)->isTypeDependent()) {
5888 QualType LHSType = TheCall->getArg(0)->getType();
5889 QualType RHSType = TheCall->getArg(1)->getType();
5890
5891 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005892 return ExprError(
5893 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5894 << TheCall->getDirectCallee()
5895 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005896 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005897
Simon Pilgrime0712012019-10-02 15:31:25 +00005898 numElements = LHSType->castAs<VectorType>()->getNumElements();
Aaron Ballman68d50642018-06-19 14:53:20 +00005899 unsigned numResElements = TheCall->getNumArgs() - 2;
5900
5901 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5902 // with mask. If so, verify that RHS is an integer vector type with the
5903 // same number of elts as lhs.
5904 if (TheCall->getNumArgs() == 2) {
5905 if (!RHSType->hasIntegerRepresentation() ||
Simon Pilgrime0712012019-10-02 15:31:25 +00005906 RHSType->castAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005907 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005908 diag::err_vec_builtin_incompatible_vector)
5909 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005910 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005911 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005912 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005913 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005914 diag::err_vec_builtin_incompatible_vector)
5915 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005916 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005917 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005918 } else if (numElements != numResElements) {
Simon Pilgrime0712012019-10-02 15:31:25 +00005919 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
Aaron Ballman68d50642018-06-19 14:53:20 +00005920 resType = Context.getVectorType(eltType, numResElements,
5921 VectorType::GenericVector);
5922 }
5923 }
5924
5925 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5926 if (TheCall->getArg(i)->isTypeDependent() ||
5927 TheCall->getArg(i)->isValueDependent())
5928 continue;
5929
5930 llvm::APSInt Result(32);
5931 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005932 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005933 diag::err_shufflevector_nonconstant_argument)
5934 << TheCall->getArg(i)->getSourceRange());
5935
5936 // Allow -1 which will be translated to undef in the IR.
5937 if (Result.isSigned() && Result.isAllOnesValue())
5938 continue;
5939
5940 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005941 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005942 diag::err_shufflevector_argument_too_large)
5943 << TheCall->getArg(i)->getSourceRange());
5944 }
5945
5946 SmallVector<Expr*, 32> exprs;
5947
5948 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5949 exprs.push_back(TheCall->getArg(i));
5950 TheCall->setArg(i, nullptr);
5951 }
5952
5953 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005954 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005955 TheCall->getRParenLoc());
5956}
5957
5958/// SemaConvertVectorExpr - Handle __builtin_convertvector
5959ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5960 SourceLocation BuiltinLoc,
5961 SourceLocation RParenLoc) {
5962 ExprValueKind VK = VK_RValue;
5963 ExprObjectKind OK = OK_Ordinary;
5964 QualType DstTy = TInfo->getType();
5965 QualType SrcTy = E->getType();
5966
5967 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5968 return ExprError(Diag(BuiltinLoc,
5969 diag::err_convertvector_non_vector)
5970 << E->getSourceRange());
5971 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5972 return ExprError(Diag(BuiltinLoc,
5973 diag::err_convertvector_non_vector_type));
5974
5975 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
Simon Pilgrime0712012019-10-02 15:31:25 +00005976 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5977 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
Aaron Ballman68d50642018-06-19 14:53:20 +00005978 if (SrcElts != DstElts)
5979 return ExprError(Diag(BuiltinLoc,
5980 diag::err_convertvector_incompatible_vector)
5981 << E->getSourceRange());
5982 }
5983
5984 return new (Context)
5985 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5986}
5987
5988/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5989// This is declared to take (const void*, ...) and can take two
5990// optional constant int args.
5991bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5992 unsigned NumArgs = TheCall->getNumArgs();
5993
5994 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005995 return Diag(TheCall->getEndLoc(),
5996 diag::err_typecheck_call_too_many_args_at_most)
5997 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005998
5999 // Argument 0 is checked for us and the remaining arguments must be
6000 // constant integers.
6001 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00006002 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00006003 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006004
Warren Hunt20e4a5d2014-02-21 23:08:53 +00006005 return false;
6006}
6007
Hal Finkelf0417332014-07-17 14:25:55 +00006008/// SemaBuiltinAssume - Handle __assume (MS Extension).
6009// __assume does not evaluate its arguments, and should warn if its argument
6010// has side effects.
6011bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6012 Expr *Arg = TheCall->getArg(0);
6013 if (Arg->isInstantiationDependent()) return false;
6014
6015 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006016 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6017 << Arg->getSourceRange()
6018 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00006019
6020 return false;
6021}
6022
David Majnemer86b1bfa2016-10-31 18:07:57 +00006023/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00006024/// as (size_t, size_t) where the second size_t must be a power of 2 greater
6025/// than 8.
6026bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6027 // The alignment must be a constant integer.
6028 Expr *Arg = TheCall->getArg(1);
6029
6030 // We can't check the value of a dependent argument.
6031 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00006032 if (const auto *UE =
6033 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00006034 if (UE->getKind() == UETT_AlignOf ||
6035 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006036 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6037 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00006038
David Majnemer51169932016-10-31 05:37:48 +00006039 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6040
6041 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006042 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6043 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00006044
6045 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006046 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6047 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00006048
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006049 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006050 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6051 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00006052 }
6053
6054 return false;
6055}
6056
6057/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00006058/// as (const void*, size_t, ...) and can take one optional constant int arg.
6059bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6060 unsigned NumArgs = TheCall->getNumArgs();
6061
6062 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006063 return Diag(TheCall->getEndLoc(),
6064 diag::err_typecheck_call_too_many_args_at_most)
6065 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00006066
6067 // The alignment must be a constant integer.
6068 Expr *Arg = TheCall->getArg(1);
6069
6070 // We can't check the value of a dependent argument.
6071 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6072 llvm::APSInt Result;
6073 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6074 return true;
6075
6076 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006077 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6078 << Arg->getSourceRange();
Erich Keanef7593952019-10-11 14:59:44 +00006079
6080 // Alignment calculations can wrap around if it's greater than 2**29.
6081 unsigned MaximumAlignment = 536870912;
6082 if (Result > MaximumAlignment)
6083 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6084 << Arg->getSourceRange() << MaximumAlignment;
Hal Finkelbcc06082014-09-07 22:58:14 +00006085 }
6086
6087 if (NumArgs > 2) {
6088 ExprResult Arg(TheCall->getArg(2));
6089 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6090 Context.getSizeType(), false);
6091 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6092 if (Arg.isInvalid()) return true;
6093 TheCall->setArg(2, Arg.get());
6094 }
Hal Finkelf0417332014-07-17 14:25:55 +00006095
6096 return false;
6097}
6098
Mehdi Amini06d367c2016-10-24 20:39:34 +00006099bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6100 unsigned BuiltinID =
6101 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6102 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6103
6104 unsigned NumArgs = TheCall->getNumArgs();
6105 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6106 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006107 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006108 << 0 /* function call */ << NumRequiredArgs << NumArgs
6109 << TheCall->getSourceRange();
6110 }
6111 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006112 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006113 diag::err_typecheck_call_too_many_args_at_most)
6114 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6115 << TheCall->getSourceRange();
6116 }
6117 unsigned i = 0;
6118
6119 // For formatting call, check buffer arg.
6120 if (!IsSizeCall) {
6121 ExprResult Arg(TheCall->getArg(i));
6122 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6123 Context, Context.VoidPtrTy, false);
6124 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6125 if (Arg.isInvalid())
6126 return true;
6127 TheCall->setArg(i, Arg.get());
6128 i++;
6129 }
6130
6131 // Check string literal arg.
6132 unsigned FormatIdx = i;
6133 {
6134 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6135 if (Arg.isInvalid())
6136 return true;
6137 TheCall->setArg(i, Arg.get());
6138 i++;
6139 }
6140
6141 // Make sure variadic args are scalar.
6142 unsigned FirstDataArg = i;
6143 while (i < NumArgs) {
6144 ExprResult Arg = DefaultVariadicArgumentPromotion(
6145 TheCall->getArg(i), VariadicFunction, nullptr);
6146 if (Arg.isInvalid())
6147 return true;
6148 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6149 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006150 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006151 << i << (int)ArgSize.getQuantity() << 0xff
6152 << TheCall->getSourceRange();
6153 }
6154 TheCall->setArg(i, Arg.get());
6155 i++;
6156 }
6157
6158 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6159 // call to avoid duplicate diagnostics.
6160 if (!IsSizeCall) {
6161 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6162 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6163 bool Success = CheckFormatArguments(
6164 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006165 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006166 CheckedVarArgs);
6167 if (!Success)
6168 return true;
6169 }
6170
6171 if (IsSizeCall) {
6172 TheCall->setType(Context.getSizeType());
6173 } else {
6174 TheCall->setType(Context.VoidPtrTy);
6175 }
6176 return false;
6177}
6178
Eric Christopher8d0c6212010-04-17 02:26:23 +00006179/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6180/// TheCall is a constant expression.
6181bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6182 llvm::APSInt &Result) {
6183 Expr *Arg = TheCall->getArg(ArgNum);
6184 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6185 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00006186
Eric Christopher8d0c6212010-04-17 02:26:23 +00006187 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006188
Eric Christopher8d0c6212010-04-17 02:26:23 +00006189 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006190 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6191 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00006192
Chris Lattnerd545ad12009-09-23 06:06:36 +00006193 return false;
6194}
6195
Richard Sandiford28940af2014-04-16 08:47:51 +00006196/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6197/// TheCall is a constant expression in the range [Low, High].
6198bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006199 int Low, int High, bool RangeIsError) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006200 if (isConstantEvaluated())
6201 return false;
Eric Christopher8d0c6212010-04-17 02:26:23 +00006202 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006203
6204 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00006205 Expr *Arg = TheCall->getArg(ArgNum);
6206 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006207 return false;
6208
Eric Christopher8d0c6212010-04-17 02:26:23 +00006209 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00006210 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00006211 return true;
6212
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006213 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6214 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006215 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006216 << Result.toString(10) << Low << High << Arg->getSourceRange();
6217 else
6218 // Defer the warning until we know if the code will be emitted so that
6219 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006220 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6221 PDiag(diag::warn_argument_invalid_range)
6222 << Result.toString(10) << Low << High
6223 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006224 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00006225
6226 return false;
6227}
6228
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006229/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6230/// TheCall is a constant expression is a multiple of Num..
6231bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6232 unsigned Num) {
6233 llvm::APSInt Result;
6234
6235 // We can't check the value of a dependent argument.
6236 Expr *Arg = TheCall->getArg(ArgNum);
6237 if (Arg->isTypeDependent() || Arg->isValueDependent())
6238 return false;
6239
6240 // Check constant-ness first.
6241 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6242 return true;
6243
6244 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006245 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6246 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006247
6248 return false;
6249}
6250
Simon Tatham08074cc2019-09-02 15:50:50 +01006251/// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6252/// constant expression representing a power of 2.
6253bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6254 llvm::APSInt Result;
6255
6256 // We can't check the value of a dependent argument.
6257 Expr *Arg = TheCall->getArg(ArgNum);
6258 if (Arg->isTypeDependent() || Arg->isValueDependent())
6259 return false;
6260
6261 // Check constant-ness first.
6262 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6263 return true;
6264
6265 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6266 // and only if x is a power of 2.
6267 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6268 return false;
6269
6270 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6271 << Arg->getSourceRange();
6272}
6273
6274static bool IsShiftedByte(llvm::APSInt Value) {
6275 if (Value.isNegative())
6276 return false;
6277
6278 // Check if it's a shifted byte, by shifting it down
6279 while (true) {
6280 // If the value fits in the bottom byte, the check passes.
6281 if (Value < 0x100)
6282 return true;
6283
6284 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6285 // fails.
6286 if ((Value & 0xFF) != 0)
6287 return false;
6288
6289 // If the bottom 8 bits are all 0, but something above that is nonzero,
6290 // then shifting the value right by 8 bits won't affect whether it's a
6291 // shifted byte or not. So do that, and go round again.
6292 Value >>= 8;
6293 }
6294}
6295
6296/// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6297/// a constant expression representing an arbitrary byte value shifted left by
6298/// a multiple of 8 bits.
6299bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) {
6300 llvm::APSInt Result;
6301
6302 // We can't check the value of a dependent argument.
6303 Expr *Arg = TheCall->getArg(ArgNum);
6304 if (Arg->isTypeDependent() || Arg->isValueDependent())
6305 return false;
6306
6307 // Check constant-ness first.
6308 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6309 return true;
6310
6311 if (IsShiftedByte(Result))
6312 return false;
6313
6314 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6315 << Arg->getSourceRange();
6316}
6317
6318/// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6319/// TheCall is a constant expression representing either a shifted byte value,
6320/// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6321/// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6322/// Arm MVE intrinsics.
6323bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6324 int ArgNum) {
6325 llvm::APSInt Result;
6326
6327 // We can't check the value of a dependent argument.
6328 Expr *Arg = TheCall->getArg(ArgNum);
6329 if (Arg->isTypeDependent() || Arg->isValueDependent())
6330 return false;
6331
6332 // Check constant-ness first.
6333 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6334 return true;
6335
6336 // Check to see if it's in either of the required forms.
6337 if (IsShiftedByte(Result) ||
6338 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6339 return false;
6340
6341 return Diag(TheCall->getBeginLoc(),
6342 diag::err_argument_not_shifted_byte_or_xxff)
6343 << Arg->getSourceRange();
6344}
6345
Javed Absar18b0c402019-04-26 21:08:11 +00006346/// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6347bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6348 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6349 if (checkArgCount(*this, TheCall, 2))
6350 return true;
6351 Expr *Arg0 = TheCall->getArg(0);
6352 Expr *Arg1 = TheCall->getArg(1);
6353
6354 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6355 if (FirstArg.isInvalid())
6356 return true;
6357 QualType FirstArgType = FirstArg.get()->getType();
6358 if (!FirstArgType->isAnyPointerType())
6359 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6360 << "first" << FirstArgType << Arg0->getSourceRange();
6361 TheCall->setArg(0, FirstArg.get());
6362
6363 ExprResult SecArg = DefaultLvalueConversion(Arg1);
6364 if (SecArg.isInvalid())
6365 return true;
6366 QualType SecArgType = SecArg.get()->getType();
6367 if (!SecArgType->isIntegerType())
6368 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6369 << "second" << SecArgType << Arg1->getSourceRange();
6370
6371 // Derive the return type from the pointer argument.
6372 TheCall->setType(FirstArgType);
6373 return false;
6374 }
6375
6376 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6377 if (checkArgCount(*this, TheCall, 2))
6378 return true;
6379
6380 Expr *Arg0 = TheCall->getArg(0);
6381 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6382 if (FirstArg.isInvalid())
6383 return true;
6384 QualType FirstArgType = FirstArg.get()->getType();
6385 if (!FirstArgType->isAnyPointerType())
6386 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6387 << "first" << FirstArgType << Arg0->getSourceRange();
6388 TheCall->setArg(0, FirstArg.get());
6389
6390 // Derive the return type from the pointer argument.
6391 TheCall->setType(FirstArgType);
6392
6393 // Second arg must be an constant in range [0,15]
6394 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6395 }
6396
6397 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6398 if (checkArgCount(*this, TheCall, 2))
6399 return true;
6400 Expr *Arg0 = TheCall->getArg(0);
6401 Expr *Arg1 = TheCall->getArg(1);
6402
6403 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6404 if (FirstArg.isInvalid())
6405 return true;
6406 QualType FirstArgType = FirstArg.get()->getType();
6407 if (!FirstArgType->isAnyPointerType())
6408 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6409 << "first" << FirstArgType << Arg0->getSourceRange();
6410
6411 QualType SecArgType = Arg1->getType();
6412 if (!SecArgType->isIntegerType())
6413 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6414 << "second" << SecArgType << Arg1->getSourceRange();
6415 TheCall->setType(Context.IntTy);
6416 return false;
6417 }
6418
6419 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6420 BuiltinID == AArch64::BI__builtin_arm_stg) {
6421 if (checkArgCount(*this, TheCall, 1))
6422 return true;
6423 Expr *Arg0 = TheCall->getArg(0);
6424 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6425 if (FirstArg.isInvalid())
6426 return true;
6427
6428 QualType FirstArgType = FirstArg.get()->getType();
6429 if (!FirstArgType->isAnyPointerType())
6430 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6431 << "first" << FirstArgType << Arg0->getSourceRange();
6432 TheCall->setArg(0, FirstArg.get());
6433
6434 // Derive the return type from the pointer argument.
6435 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6436 TheCall->setType(FirstArgType);
6437 return false;
6438 }
6439
6440 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6441 Expr *ArgA = TheCall->getArg(0);
6442 Expr *ArgB = TheCall->getArg(1);
6443
6444 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6445 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6446
6447 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6448 return true;
6449
6450 QualType ArgTypeA = ArgExprA.get()->getType();
6451 QualType ArgTypeB = ArgExprB.get()->getType();
6452
6453 auto isNull = [&] (Expr *E) -> bool {
6454 return E->isNullPointerConstant(
6455 Context, Expr::NPC_ValueDependentIsNotNull); };
6456
6457 // argument should be either a pointer or null
6458 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6459 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6460 << "first" << ArgTypeA << ArgA->getSourceRange();
6461
6462 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6463 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6464 << "second" << ArgTypeB << ArgB->getSourceRange();
6465
6466 // Ensure Pointee types are compatible
6467 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6468 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6469 QualType pointeeA = ArgTypeA->getPointeeType();
6470 QualType pointeeB = ArgTypeB->getPointeeType();
6471 if (!Context.typesAreCompatible(
6472 Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6473 Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6474 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6475 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6476 << ArgB->getSourceRange();
6477 }
6478 }
6479
6480 // at least one argument should be pointer type
6481 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6482 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6483 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6484
6485 if (isNull(ArgA)) // adopt type of the other pointer
6486 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6487
6488 if (isNull(ArgB))
6489 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6490
6491 TheCall->setArg(0, ArgExprA.get());
6492 TheCall->setArg(1, ArgExprB.get());
6493 TheCall->setType(Context.LongLongTy);
6494 return false;
6495 }
6496 assert(false && "Unhandled ARM MTE intrinsic");
6497 return true;
6498}
6499
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006500/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6501/// TheCall is an ARM/AArch64 special register string literal.
6502bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6503 int ArgNum, unsigned ExpectedFieldNum,
6504 bool AllowName) {
6505 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6506 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6507 BuiltinID == ARM::BI__builtin_arm_rsr ||
6508 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6509 BuiltinID == ARM::BI__builtin_arm_wsr ||
6510 BuiltinID == ARM::BI__builtin_arm_wsrp;
6511 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6512 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6513 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6514 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6515 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6516 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6517 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6518
6519 // We can't check the value of a dependent argument.
6520 Expr *Arg = TheCall->getArg(ArgNum);
6521 if (Arg->isTypeDependent() || Arg->isValueDependent())
6522 return false;
6523
6524 // Check if the argument is a string literal.
6525 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006526 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006527 << Arg->getSourceRange();
6528
6529 // Check the type of special register given.
6530 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6531 SmallVector<StringRef, 6> Fields;
6532 Reg.split(Fields, ":");
6533
6534 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006535 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006536 << Arg->getSourceRange();
6537
6538 // If the string is the name of a register then we cannot check that it is
6539 // valid here but if the string is of one the forms described in ACLE then we
6540 // can check that the supplied fields are integers and within the valid
6541 // ranges.
6542 if (Fields.size() > 1) {
6543 bool FiveFields = Fields.size() == 5;
6544
6545 bool ValidString = true;
6546 if (IsARMBuiltin) {
6547 ValidString &= Fields[0].startswith_lower("cp") ||
6548 Fields[0].startswith_lower("p");
6549 if (ValidString)
6550 Fields[0] =
6551 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6552
6553 ValidString &= Fields[2].startswith_lower("c");
6554 if (ValidString)
6555 Fields[2] = Fields[2].drop_front(1);
6556
6557 if (FiveFields) {
6558 ValidString &= Fields[3].startswith_lower("c");
6559 if (ValidString)
6560 Fields[3] = Fields[3].drop_front(1);
6561 }
6562 }
6563
6564 SmallVector<int, 5> Ranges;
6565 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006566 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006567 else
6568 Ranges.append({15, 7, 15});
6569
6570 for (unsigned i=0; i<Fields.size(); ++i) {
6571 int IntField;
6572 ValidString &= !Fields[i].getAsInteger(10, IntField);
6573 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6574 }
6575
6576 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006577 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006578 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006579 } else if (IsAArch64Builtin && Fields.size() == 1) {
6580 // If the register name is one of those that appear in the condition below
6581 // and the special register builtin being used is one of the write builtins,
6582 // then we require that the argument provided for writing to the register
6583 // is an integer constant expression. This is because it will be lowered to
6584 // an MSR (immediate) instruction, so we need to know the immediate at
6585 // compile time.
6586 if (TheCall->getNumArgs() != 2)
6587 return false;
6588
6589 std::string RegLower = Reg.lower();
6590 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6591 RegLower != "pan" && RegLower != "uao")
6592 return false;
6593
6594 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6595 }
6596
6597 return false;
6598}
6599
Eli Friedmanc97d0142009-05-03 06:04:26 +00006600/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006601/// This checks that the target supports __builtin_longjmp and
6602/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006603bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006604 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006605 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006606 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006607
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006608 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006609 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006610
Eric Christopher8d0c6212010-04-17 02:26:23 +00006611 // TODO: This is less than ideal. Overload this to take a value.
6612 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6613 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006614
Eric Christopher8d0c6212010-04-17 02:26:23 +00006615 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006616 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006617 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006618
6619 return false;
6620}
6621
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006622/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6623/// This checks that the target supports __builtin_setjmp.
6624bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6625 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006626 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006627 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006628 return false;
6629}
6630
Richard Smithd7293d72013-08-05 18:49:43 +00006631namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006632
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006633class UncoveredArgHandler {
6634 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006635
6636 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006637 SmallVector<const Expr *, 4> DiagnosticExprs;
6638
6639public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006640 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006641
6642 bool hasUncoveredArg() const {
6643 return (FirstUncoveredArg >= 0);
6644 }
6645
6646 unsigned getUncoveredArg() const {
6647 assert(hasUncoveredArg() && "no uncovered argument");
6648 return FirstUncoveredArg;
6649 }
6650
6651 void setAllCovered() {
6652 // A string has been found with all arguments covered, so clear out
6653 // the diagnostics.
6654 DiagnosticExprs.clear();
6655 FirstUncoveredArg = AllCovered;
6656 }
6657
6658 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6659 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6660
6661 // Don't update if a previous string covers all arguments.
6662 if (FirstUncoveredArg == AllCovered)
6663 return;
6664
6665 // UncoveredArgHandler tracks the highest uncovered argument index
6666 // and with it all the strings that match this index.
6667 if (NewFirstUncoveredArg == FirstUncoveredArg)
6668 DiagnosticExprs.push_back(StrExpr);
6669 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6670 DiagnosticExprs.clear();
6671 DiagnosticExprs.push_back(StrExpr);
6672 FirstUncoveredArg = NewFirstUncoveredArg;
6673 }
6674 }
6675
6676 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6677};
6678
Richard Smithd7293d72013-08-05 18:49:43 +00006679enum StringLiteralCheckType {
6680 SLCT_NotALiteral,
6681 SLCT_UncheckedLiteral,
6682 SLCT_CheckedLiteral
6683};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006684
6685} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006686
Stephen Hines648c3692016-09-16 01:07:04 +00006687static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6688 BinaryOperatorKind BinOpKind,
6689 bool AddendIsRight) {
6690 unsigned BitWidth = Offset.getBitWidth();
6691 unsigned AddendBitWidth = Addend.getBitWidth();
6692 // There might be negative interim results.
6693 if (Addend.isUnsigned()) {
6694 Addend = Addend.zext(++AddendBitWidth);
6695 Addend.setIsSigned(true);
6696 }
6697 // Adjust the bit width of the APSInts.
6698 if (AddendBitWidth > BitWidth) {
6699 Offset = Offset.sext(AddendBitWidth);
6700 BitWidth = AddendBitWidth;
6701 } else if (BitWidth > AddendBitWidth) {
6702 Addend = Addend.sext(BitWidth);
6703 }
6704
6705 bool Ov = false;
6706 llvm::APSInt ResOffset = Offset;
6707 if (BinOpKind == BO_Add)
6708 ResOffset = Offset.sadd_ov(Addend, Ov);
6709 else {
6710 assert(AddendIsRight && BinOpKind == BO_Sub &&
6711 "operator must be add or sub with addend on the right");
6712 ResOffset = Offset.ssub_ov(Addend, Ov);
6713 }
6714
6715 // We add an offset to a pointer here so we should support an offset as big as
6716 // possible.
6717 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006718 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6719 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006720 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006721 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6722 return;
6723 }
6724
6725 Offset = ResOffset;
6726}
6727
6728namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006729
Stephen Hines648c3692016-09-16 01:07:04 +00006730// This is a wrapper class around StringLiteral to support offsetted string
6731// literals as format strings. It takes the offset into account when returning
6732// the string and its length or the source locations to display notes correctly.
6733class FormatStringLiteral {
6734 const StringLiteral *FExpr;
6735 int64_t Offset;
6736
6737 public:
6738 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6739 : FExpr(fexpr), Offset(Offset) {}
6740
6741 StringRef getString() const {
6742 return FExpr->getString().drop_front(Offset);
6743 }
6744
6745 unsigned getByteLength() const {
6746 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6747 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006748
Stephen Hines648c3692016-09-16 01:07:04 +00006749 unsigned getLength() const { return FExpr->getLength() - Offset; }
6750 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6751
6752 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6753
6754 QualType getType() const { return FExpr->getType(); }
6755
6756 bool isAscii() const { return FExpr->isAscii(); }
6757 bool isWide() const { return FExpr->isWide(); }
6758 bool isUTF8() const { return FExpr->isUTF8(); }
6759 bool isUTF16() const { return FExpr->isUTF16(); }
6760 bool isUTF32() const { return FExpr->isUTF32(); }
6761 bool isPascal() const { return FExpr->isPascal(); }
6762
6763 SourceLocation getLocationOfByte(
6764 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6765 const TargetInfo &Target, unsigned *StartToken = nullptr,
6766 unsigned *StartTokenByteOffset = nullptr) const {
6767 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6768 StartToken, StartTokenByteOffset);
6769 }
6770
Stephen Kelly724e9e52018-08-09 20:05:03 +00006771 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006772 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006773 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006774
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006775 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006776};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006777
6778} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006779
6780static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006781 const Expr *OrigFormatExpr,
6782 ArrayRef<const Expr *> Args,
6783 bool HasVAListArg, unsigned format_idx,
6784 unsigned firstDataArg,
6785 Sema::FormatStringType Type,
6786 bool inFunctionCall,
6787 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006788 llvm::SmallBitVector &CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006789 UncoveredArgHandler &UncoveredArg,
6790 bool IgnoreStringsWithoutSpecifiers);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006791
Richard Smith55ce3522012-06-25 20:30:08 +00006792// Determine if an expression is a string literal or constant string.
6793// If this function returns false on the arguments to a function expecting a
6794// format string, we will usually need to emit a warning.
6795// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006796static StringLiteralCheckType
6797checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6798 bool HasVAListArg, unsigned format_idx,
6799 unsigned firstDataArg, Sema::FormatStringType Type,
6800 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006801 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006802 UncoveredArgHandler &UncoveredArg,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006803 llvm::APSInt Offset,
6804 bool IgnoreStringsWithoutSpecifiers = false) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006805 if (S.isConstantEvaluated())
6806 return SLCT_NotALiteral;
Ted Kremenek808829352010-09-09 03:51:39 +00006807 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006808 assert(Offset.isSigned() && "invalid offset");
6809
Douglas Gregorc25f7662009-05-19 22:10:17 +00006810 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006811 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006812
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006813 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006814
Richard Smithd7293d72013-08-05 18:49:43 +00006815 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006816 // Technically -Wformat-nonliteral does not warn about this case.
6817 // The behavior of printf and friends in this case is implementation
6818 // dependent. Ideally if the format string cannot be null then
6819 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006820 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006821
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006822 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006823 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006824 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006825 // The expression is a literal if both sub-expressions were, and it was
6826 // completely checked only if both sub-expressions were checked.
6827 const AbstractConditionalOperator *C =
6828 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006829
6830 // Determine whether it is necessary to check both sub-expressions, for
6831 // example, because the condition expression is a constant that can be
6832 // evaluated at compile time.
6833 bool CheckLeft = true, CheckRight = true;
6834
6835 bool Cond;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006836 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6837 S.isConstantEvaluated())) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006838 if (Cond)
6839 CheckRight = false;
6840 else
6841 CheckLeft = false;
6842 }
6843
Stephen Hines648c3692016-09-16 01:07:04 +00006844 // We need to maintain the offsets for the right and the left hand side
6845 // separately to check if every possible indexed expression is a valid
6846 // string literal. They might have different offsets for different string
6847 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006848 StringLiteralCheckType Left;
6849 if (!CheckLeft)
6850 Left = SLCT_UncheckedLiteral;
6851 else {
6852 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6853 HasVAListArg, format_idx, firstDataArg,
6854 Type, CallType, InFunctionCall,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006855 CheckedVarArgs, UncoveredArg, Offset,
6856 IgnoreStringsWithoutSpecifiers);
Stephen Hines648c3692016-09-16 01:07:04 +00006857 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006858 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006859 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006860 }
6861
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006862 StringLiteralCheckType Right = checkFormatStringExpr(
6863 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6864 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6865 IgnoreStringsWithoutSpecifiers);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006866
6867 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006868 }
6869
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006870 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006871 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6872 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006873
John McCallc07a0c72011-02-17 10:25:35 +00006874 case Stmt::OpaqueValueExprClass:
6875 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6876 E = src;
6877 goto tryAgain;
6878 }
Richard Smith55ce3522012-06-25 20:30:08 +00006879 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006880
Ted Kremeneka8890832011-02-24 23:03:04 +00006881 case Stmt::PredefinedExprClass:
6882 // While __func__, etc., are technically not string literals, they
6883 // cannot contain format specifiers and thus are not a security
6884 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006885 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006886
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006887 case Stmt::DeclRefExprClass: {
6888 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006889
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006890 // As an exception, do not flag errors for variables binding to
6891 // const string literals.
6892 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6893 bool isConstant = false;
6894 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006895
Richard Smithd7293d72013-08-05 18:49:43 +00006896 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6897 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006898 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006899 isConstant = T.isConstant(S.Context) &&
6900 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006901 } else if (T->isObjCObjectPointerType()) {
6902 // In ObjC, there is usually no "const ObjectPointer" type,
6903 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006904 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006905 }
Mike Stump11289f42009-09-09 15:08:12 +00006906
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006907 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006908 if (const Expr *Init = VD->getAnyInitializer()) {
6909 // Look through initializers like const char c[] = { "foo" }
6910 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6911 if (InitList->isStringLiteralInit())
6912 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6913 }
Richard Smithd7293d72013-08-05 18:49:43 +00006914 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006915 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006916 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006917 /*InFunctionCall*/ false, CheckedVarArgs,
6918 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006919 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006920 }
Mike Stump11289f42009-09-09 15:08:12 +00006921
Anders Carlssonb012ca92009-06-28 19:55:58 +00006922 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6923 // special check to see if the format string is a function parameter
6924 // of the function calling the printf function. If the function
6925 // has an attribute indicating it is a printf-like function, then we
6926 // should suppress warnings concerning non-literals being used in a call
6927 // to a vprintf function. For example:
6928 //
6929 // void
6930 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6931 // va_list ap;
6932 // va_start(ap, fmt);
6933 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6934 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006935 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006936 if (HasVAListArg) {
6937 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6938 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6939 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006940 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006941 // adjust for implicit parameter
6942 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6943 if (MD->isInstance())
6944 ++PVIndex;
6945 // We also check if the formats are compatible.
6946 // We can't pass a 'scanf' string to a 'printf' function.
6947 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006948 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006949 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006950 }
6951 }
6952 }
6953 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006954 }
Mike Stump11289f42009-09-09 15:08:12 +00006955
Richard Smith55ce3522012-06-25 20:30:08 +00006956 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006957 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006958
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006959 case Stmt::CallExprClass:
6960 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006961 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006962 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006963 bool IsFirst = true;
6964 StringLiteralCheckType CommonResult;
6965 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006966 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006967 StringLiteralCheckType Result = checkFormatStringExpr(
6968 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006969 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6970 IgnoreStringsWithoutSpecifiers);
Michael Krusef18adbb2018-07-04 01:37:11 +00006971 if (IsFirst) {
6972 CommonResult = Result;
6973 IsFirst = false;
6974 }
6975 }
6976 if (!IsFirst)
6977 return CommonResult;
6978
6979 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006980 unsigned BuiltinID = FD->getBuiltinID();
6981 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6982 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6983 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006984 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006985 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006986 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006987 InFunctionCall, CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006988 UncoveredArg, Offset,
6989 IgnoreStringsWithoutSpecifiers);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006990 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006991 }
6992 }
Mike Stump11289f42009-09-09 15:08:12 +00006993
Richard Smith55ce3522012-06-25 20:30:08 +00006994 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006995 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006996 case Stmt::ObjCMessageExprClass: {
6997 const auto *ME = cast<ObjCMessageExpr>(E);
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006998 if (const auto *MD = ME->getMethodDecl()) {
6999 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7000 // As a special case heuristic, if we're using the method -[NSBundle
7001 // localizedStringForKey:value:table:], ignore any key strings that lack
7002 // format specifiers. The idea is that if the key doesn't have any
7003 // format specifiers then its probably just a key to map to the
7004 // localized strings. If it does have format specifiers though, then its
7005 // likely that the text of the key is the format string in the
7006 // programmer's language, and should be checked.
7007 const ObjCInterfaceDecl *IFace;
7008 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7009 IFace->getIdentifier()->isStr("NSBundle") &&
7010 MD->getSelector().isKeywordSelector(
7011 {"localizedStringForKey", "value", "table"})) {
7012 IgnoreStringsWithoutSpecifiers = true;
7013 }
7014
Joel E. Denny81508102018-03-13 14:51:22 +00007015 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00007016 return checkFormatStringExpr(
7017 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00007018 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7019 IgnoreStringsWithoutSpecifiers);
Alex Lorenzd9007142016-10-24 09:42:34 +00007020 }
7021 }
7022
7023 return SLCT_NotALiteral;
7024 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00007025 case Stmt::ObjCStringLiteralClass:
7026 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00007027 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007028
Ted Kremenekdfd72c22009-03-20 21:35:28 +00007029 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007030 StrE = ObjCFExpr->getString();
7031 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00007032 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007033
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007034 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00007035 if (Offset.isNegative() || Offset > StrE->getLength()) {
7036 // TODO: It would be better to have an explicit warning for out of
7037 // bounds literals.
7038 return SLCT_NotALiteral;
7039 }
7040 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7041 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007042 firstDataArg, Type, InFunctionCall, CallType,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00007043 CheckedVarArgs, UncoveredArg,
7044 IgnoreStringsWithoutSpecifiers);
Richard Smith55ce3522012-06-25 20:30:08 +00007045 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007046 }
Mike Stump11289f42009-09-09 15:08:12 +00007047
Richard Smith55ce3522012-06-25 20:30:08 +00007048 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007049 }
Stephen Hines648c3692016-09-16 01:07:04 +00007050 case Stmt::BinaryOperatorClass: {
Stephen Hines648c3692016-09-16 01:07:04 +00007051 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7052
7053 // A string literal + an int offset is still a string literal.
7054 if (BinOp->isAdditiveOp()) {
Fangrui Song407659a2018-11-30 23:41:18 +00007055 Expr::EvalResult LResult, RResult;
7056
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00007057 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7058 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7059 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7060 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
Stephen Hines648c3692016-09-16 01:07:04 +00007061
7062 if (LIsInt != RIsInt) {
7063 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7064
7065 if (LIsInt) {
7066 if (BinOpKind == BO_Add) {
Fangrui Song407659a2018-11-30 23:41:18 +00007067 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00007068 E = BinOp->getRHS();
7069 goto tryAgain;
7070 }
7071 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00007072 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00007073 E = BinOp->getLHS();
7074 goto tryAgain;
7075 }
7076 }
Stephen Hines648c3692016-09-16 01:07:04 +00007077 }
George Burgess IVd273aab2016-09-22 00:00:26 +00007078
7079 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00007080 }
7081 case Stmt::UnaryOperatorClass: {
7082 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7083 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007084 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Fangrui Song407659a2018-11-30 23:41:18 +00007085 Expr::EvalResult IndexResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00007086 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7087 Expr::SE_NoSideEffects,
7088 S.isConstantEvaluated())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007089 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7090 /*RHS is int*/ true);
Stephen Hines648c3692016-09-16 01:07:04 +00007091 E = ASE->getBase();
7092 goto tryAgain;
7093 }
7094 }
7095
7096 return SLCT_NotALiteral;
7097 }
Mike Stump11289f42009-09-09 15:08:12 +00007098
Ted Kremenekdfd72c22009-03-20 21:35:28 +00007099 default:
Richard Smith55ce3522012-06-25 20:30:08 +00007100 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007101 }
7102}
7103
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007104Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00007105 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00007106 .Case("scanf", FST_Scanf)
7107 .Cases("printf", "printf0", FST_Printf)
7108 .Cases("NSString", "CFString", FST_NSString)
7109 .Case("strftime", FST_Strftime)
7110 .Case("strfmon", FST_Strfmon)
7111 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7112 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7113 .Case("os_trace", FST_OSLog)
7114 .Case("os_log", FST_OSLog)
7115 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007116}
7117
Jordan Rose3e0ec582012-07-19 18:10:23 +00007118/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00007119/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00007120/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007121bool Sema::CheckFormatArguments(const FormatAttr *Format,
7122 ArrayRef<const Expr *> Args,
7123 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007124 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00007125 SourceLocation Loc, SourceRange Range,
7126 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00007127 FormatStringInfo FSI;
7128 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007129 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00007130 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00007131 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00007132 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007133}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00007134
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007135bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007136 bool HasVAListArg, unsigned format_idx,
7137 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007138 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00007139 SourceLocation Loc, SourceRange Range,
7140 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00007141 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007142 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007143 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00007144 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00007145 }
Mike Stump11289f42009-09-09 15:08:12 +00007146
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007147 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007148
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007149 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00007150 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00007151 // Dynamically generated format strings are difficult to
7152 // automatically vet at compile time. Requiring that format strings
7153 // are string literals: (1) permits the checking of format strings by
7154 // the compiler and thereby (2) can practically remove the source of
7155 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00007156
Mike Stump11289f42009-09-09 15:08:12 +00007157 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00007158 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00007159 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00007160 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007161 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00007162 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00007163 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7164 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00007165 /*IsFunctionCall*/ true, CheckedVarArgs,
7166 UncoveredArg,
7167 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007168
7169 // Generate a diagnostic where an uncovered argument is detected.
7170 if (UncoveredArg.hasUncoveredArg()) {
7171 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7172 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7173 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7174 }
7175
Richard Smith55ce3522012-06-25 20:30:08 +00007176 if (CT != SLCT_NotALiteral)
7177 // Literal format string found, check done!
7178 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00007179
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00007180 // Strftime is particular as it always uses a single 'time' argument,
7181 // so it is safe to pass a non-literal string.
7182 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00007183 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00007184
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00007185 // Do not emit diag when the string param is a macro expansion and the
7186 // format is either NSString or CFString. This is a hack to prevent
7187 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7188 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007189 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007190 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00007191 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00007192
Chris Lattnercc5d1c22009-04-29 04:59:47 +00007193 // If there are no arguments specified, warn with -Wformat-security, otherwise
7194 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007195 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00007196 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7197 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007198 switch (Type) {
7199 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007200 break;
7201 case FST_Kprintf:
7202 case FST_FreeBSDKPrintf:
7203 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00007204 Diag(FormatLoc, diag::note_format_security_fixit)
7205 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007206 break;
7207 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00007208 Diag(FormatLoc, diag::note_format_security_fixit)
7209 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007210 break;
7211 }
7212 } else {
7213 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00007214 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007215 }
Richard Smith55ce3522012-06-25 20:30:08 +00007216 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007217}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00007218
Ted Kremenekab278de2010-01-28 23:39:18 +00007219namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007220
Ted Kremenek02087932010-07-16 02:11:22 +00007221class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7222protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00007223 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00007224 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00007225 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00007226 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00007227 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00007228 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00007229 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00007230 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007231 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00007232 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00007233 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007234 bool usesPositionalArgs = false;
7235 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007236 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00007237 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00007238 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007239 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007240
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007241public:
Stephen Hines648c3692016-09-16 01:07:04 +00007242 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007243 const Expr *origFormatExpr,
7244 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00007245 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007246 ArrayRef<const Expr *> Args, unsigned formatIdx,
7247 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007248 llvm::SmallBitVector &CheckedVarArgs,
7249 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007250 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7251 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7252 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00007253 inFunctionCall(inFunctionCall), CallType(callType),
7254 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00007255 CoveredArgs.resize(numDataArgs);
7256 CoveredArgs.reset();
7257 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007258
Ted Kremenek019d2242010-01-29 01:50:07 +00007259 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007260
Ted Kremenek02087932010-07-16 02:11:22 +00007261 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007262 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007263
Jordan Rose92303592012-09-08 04:00:03 +00007264 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007265 const analyze_format_string::FormatSpecifier &FS,
7266 const analyze_format_string::ConversionSpecifier &CS,
7267 const char *startSpecifier, unsigned specifierLen,
7268 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00007269
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007270 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007271 const analyze_format_string::FormatSpecifier &FS,
7272 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007273
7274 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007275 const analyze_format_string::ConversionSpecifier &CS,
7276 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007277
Craig Toppere14c0f82014-03-12 04:55:44 +00007278 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007279
Craig Toppere14c0f82014-03-12 04:55:44 +00007280 void HandleInvalidPosition(const char *startSpecifier,
7281 unsigned specifierLen,
7282 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007283
Craig Toppere14c0f82014-03-12 04:55:44 +00007284 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007285
Craig Toppere14c0f82014-03-12 04:55:44 +00007286 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007287
Richard Trieu03cf7b72011-10-28 00:41:25 +00007288 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00007289 static void
7290 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7291 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7292 bool IsStringLocation, Range StringRange,
7293 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007294
Ted Kremenek02087932010-07-16 02:11:22 +00007295protected:
Ted Kremenekce815422010-07-19 21:25:57 +00007296 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7297 const char *startSpec,
7298 unsigned specifierLen,
7299 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007300
7301 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7302 const char *startSpec,
7303 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00007304
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007305 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00007306 CharSourceRange getSpecifierRange(const char *startSpecifier,
7307 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00007308 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007309
Ted Kremenek5739de72010-01-29 01:06:55 +00007310 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00007311
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007312 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7313 const analyze_format_string::ConversionSpecifier &CS,
7314 const char *startSpecifier, unsigned specifierLen,
7315 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007316
7317 template <typename Range>
7318 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7319 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007320 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00007321};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007322
7323} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007324
Ted Kremenek02087932010-07-16 02:11:22 +00007325SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00007326 return OrigFormatExpr->getSourceRange();
7327}
7328
Ted Kremenek02087932010-07-16 02:11:22 +00007329CharSourceRange CheckFormatHandler::
7330getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00007331 SourceLocation Start = getLocationOfByte(startSpecifier);
7332 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7333
7334 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007335 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00007336
7337 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007338}
7339
Ted Kremenek02087932010-07-16 02:11:22 +00007340SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00007341 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7342 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00007343}
7344
Ted Kremenek02087932010-07-16 02:11:22 +00007345void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7346 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00007347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7348 getLocationOfByte(startSpecifier),
7349 /*IsStringLocation*/true,
7350 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00007351}
7352
Jordan Rose92303592012-09-08 04:00:03 +00007353void CheckFormatHandler::HandleInvalidLengthModifier(
7354 const analyze_format_string::FormatSpecifier &FS,
7355 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00007356 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00007357 using namespace analyze_format_string;
7358
7359 const LengthModifier &LM = FS.getLengthModifier();
7360 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7361
7362 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007363 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00007364 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007365 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007366 getLocationOfByte(LM.getStart()),
7367 /*IsStringLocation*/true,
7368 getSpecifierRange(startSpecifier, specifierLen));
7369
7370 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7371 << FixedLM->toString()
7372 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7373
7374 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007375 FixItHint Hint;
7376 if (DiagID == diag::warn_format_nonsensical_length)
7377 Hint = FixItHint::CreateRemoval(LMRange);
7378
7379 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007380 getLocationOfByte(LM.getStart()),
7381 /*IsStringLocation*/true,
7382 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00007383 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00007384 }
7385}
7386
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007387void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00007388 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007389 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007390 using namespace analyze_format_string;
7391
7392 const LengthModifier &LM = FS.getLengthModifier();
7393 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7394
7395 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007396 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00007397 if (FixedLM) {
7398 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7399 << LM.toString() << 0,
7400 getLocationOfByte(LM.getStart()),
7401 /*IsStringLocation*/true,
7402 getSpecifierRange(startSpecifier, specifierLen));
7403
7404 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7405 << FixedLM->toString()
7406 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7407
7408 } else {
7409 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7410 << LM.toString() << 0,
7411 getLocationOfByte(LM.getStart()),
7412 /*IsStringLocation*/true,
7413 getSpecifierRange(startSpecifier, specifierLen));
7414 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007415}
7416
7417void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7418 const analyze_format_string::ConversionSpecifier &CS,
7419 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00007420 using namespace analyze_format_string;
7421
7422 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00007423 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00007424 if (FixedCS) {
7425 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7426 << CS.toString() << /*conversion specifier*/1,
7427 getLocationOfByte(CS.getStart()),
7428 /*IsStringLocation*/true,
7429 getSpecifierRange(startSpecifier, specifierLen));
7430
7431 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7432 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7433 << FixedCS->toString()
7434 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7435 } else {
7436 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7437 << CS.toString() << /*conversion specifier*/1,
7438 getLocationOfByte(CS.getStart()),
7439 /*IsStringLocation*/true,
7440 getSpecifierRange(startSpecifier, specifierLen));
7441 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007442}
7443
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007444void CheckFormatHandler::HandlePosition(const char *startPos,
7445 unsigned posLen) {
7446 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7447 getLocationOfByte(startPos),
7448 /*IsStringLocation*/true,
7449 getSpecifierRange(startPos, posLen));
7450}
7451
Ted Kremenekd1668192010-02-27 01:41:03 +00007452void
Ted Kremenek02087932010-07-16 02:11:22 +00007453CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7454 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007455 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7456 << (unsigned) p,
7457 getLocationOfByte(startPos), /*IsStringLocation*/true,
7458 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007459}
7460
Ted Kremenek02087932010-07-16 02:11:22 +00007461void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00007462 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007463 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7464 getLocationOfByte(startPos),
7465 /*IsStringLocation*/true,
7466 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007467}
7468
Ted Kremenek02087932010-07-16 02:11:22 +00007469void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00007470 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007471 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007472 EmitFormatDiagnostic(
7473 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7474 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7475 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007476 }
Ted Kremenek02087932010-07-16 02:11:22 +00007477}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007478
Jordan Rose58bbe422012-07-19 18:10:08 +00007479// Note that this may return NULL if there was an error parsing or building
7480// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00007481const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007482 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00007483}
7484
7485void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007486 // Does the number of data arguments exceed the number of
7487 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00007488 if (!HasVAListArg) {
7489 // Find any arguments that weren't covered.
7490 CoveredArgs.flip();
7491 signed notCoveredArg = CoveredArgs.find_first();
7492 if (notCoveredArg >= 0) {
7493 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007494 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7495 } else {
7496 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00007497 }
7498 }
7499}
7500
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007501void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7502 const Expr *ArgExpr) {
7503 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7504 "Invalid state");
7505
7506 if (!ArgExpr)
7507 return;
7508
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007509 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007510
7511 if (S.getSourceManager().isInSystemMacro(Loc))
7512 return;
7513
7514 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7515 for (auto E : DiagnosticExprs)
7516 PDiag << E->getSourceRange();
7517
7518 CheckFormatHandler::EmitFormatDiagnostic(
7519 S, IsFunctionCall, DiagnosticExprs[0],
7520 PDiag, Loc, /*IsStringLocation*/false,
7521 DiagnosticExprs[0]->getSourceRange());
7522}
7523
Ted Kremenekce815422010-07-19 21:25:57 +00007524bool
7525CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7526 SourceLocation Loc,
7527 const char *startSpec,
7528 unsigned specifierLen,
7529 const char *csStart,
7530 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00007531 bool keepGoing = true;
7532 if (argIndex < NumDataArgs) {
7533 // Consider the argument coverered, even though the specifier doesn't
7534 // make sense.
7535 CoveredArgs.set(argIndex);
7536 }
7537 else {
7538 // If argIndex exceeds the number of data arguments we
7539 // don't issue a warning because that is just a cascade of warnings (and
7540 // they may have intended '%%' anyway). We don't want to continue processing
7541 // the format string after this point, however, as we will like just get
7542 // gibberish when trying to match arguments.
7543 keepGoing = false;
7544 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007545
7546 StringRef Specifier(csStart, csLen);
7547
7548 // If the specifier in non-printable, it could be the first byte of a UTF-8
7549 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7550 // hex value.
7551 std::string CodePointStr;
7552 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00007553 llvm::UTF32 CodePoint;
7554 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7555 const llvm::UTF8 *E =
7556 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7557 llvm::ConversionResult Result =
7558 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007559
Justin Lebar90910552016-09-30 00:38:45 +00007560 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007561 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00007562 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007563 }
7564
7565 llvm::raw_string_ostream OS(CodePointStr);
7566 if (CodePoint < 256)
7567 OS << "\\x" << llvm::format("%02x", CodePoint);
7568 else if (CodePoint <= 0xFFFF)
7569 OS << "\\u" << llvm::format("%04x", CodePoint);
7570 else
7571 OS << "\\U" << llvm::format("%08x", CodePoint);
7572 OS.flush();
7573 Specifier = CodePointStr;
7574 }
7575
7576 EmitFormatDiagnostic(
7577 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7578 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7579
Ted Kremenekce815422010-07-19 21:25:57 +00007580 return keepGoing;
7581}
7582
Richard Trieu03cf7b72011-10-28 00:41:25 +00007583void
7584CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7585 const char *startSpec,
7586 unsigned specifierLen) {
7587 EmitFormatDiagnostic(
7588 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7589 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7590}
7591
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007592bool
7593CheckFormatHandler::CheckNumArgs(
7594 const analyze_format_string::FormatSpecifier &FS,
7595 const analyze_format_string::ConversionSpecifier &CS,
7596 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7597
7598 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007599 PartialDiagnostic PDiag = FS.usesPositionalArg()
7600 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7601 << (argIndex+1) << NumDataArgs)
7602 : S.PDiag(diag::warn_printf_insufficient_data_args);
7603 EmitFormatDiagnostic(
7604 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7605 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007606
7607 // Since more arguments than conversion tokens are given, by extension
7608 // all arguments are covered, so mark this as so.
7609 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007610 return false;
7611 }
7612 return true;
7613}
7614
Richard Trieu03cf7b72011-10-28 00:41:25 +00007615template<typename Range>
7616void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7617 SourceLocation Loc,
7618 bool IsStringLocation,
7619 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007620 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007621 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007622 Loc, IsStringLocation, StringRange, FixIt);
7623}
7624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007625/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007626/// so that the function call and string are in diagnostic messages.
7627///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007628/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007629/// call and only one diagnostic message will be produced. Otherwise, an
7630/// extra note will be emitted pointing to location of the format string.
7631///
7632/// \param ArgumentExpr the expression that is passed as the format string
7633/// argument in the function call. Used for getting locations when two
7634/// diagnostics are emitted.
7635///
7636/// \param PDiag the callee should already have provided any strings for the
7637/// diagnostic message. This function only adds locations and fixits
7638/// to diagnostics.
7639///
7640/// \param Loc primary location for diagnostic. If two diagnostics are
7641/// required, one will be at Loc and a new SourceLocation will be created for
7642/// the other one.
7643///
7644/// \param IsStringLocation if true, Loc points to the format string should be
7645/// used for the note. Otherwise, Loc points to the argument list and will
7646/// be used with PDiag.
7647///
7648/// \param StringRange some or all of the string to highlight. This is
7649/// templated so it can accept either a CharSourceRange or a SourceRange.
7650///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007651/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007652template <typename Range>
7653void CheckFormatHandler::EmitFormatDiagnostic(
7654 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7655 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7656 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007657 if (InFunctionCall) {
7658 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7659 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007660 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007661 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007662 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7663 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007664
7665 const Sema::SemaDiagnosticBuilder &Note =
7666 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7667 diag::note_format_string_defined);
7668
7669 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007670 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007671 }
7672}
7673
Ted Kremenek02087932010-07-16 02:11:22 +00007674//===--- CHECK: Printf format string checking ------------------------------===//
7675
7676namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007677
Ted Kremenek02087932010-07-16 02:11:22 +00007678class CheckPrintfHandler : public CheckFormatHandler {
7679public:
Stephen Hines648c3692016-09-16 01:07:04 +00007680 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007681 const Expr *origFormatExpr,
7682 const Sema::FormatStringType type, unsigned firstDataArg,
7683 unsigned numDataArgs, bool isObjC, const char *beg,
7684 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007685 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007686 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007687 llvm::SmallBitVector &CheckedVarArgs,
7688 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007689 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7690 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7691 inFunctionCall, CallType, CheckedVarArgs,
7692 UncoveredArg) {}
7693
7694 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7695
7696 /// Returns true if '%@' specifiers are allowed in the format string.
7697 bool allowsObjCArg() const {
7698 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7699 FSType == Sema::FST_OSTrace;
7700 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007701
Ted Kremenek02087932010-07-16 02:11:22 +00007702 bool HandleInvalidPrintfConversionSpecifier(
7703 const analyze_printf::PrintfSpecifier &FS,
7704 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007705 unsigned specifierLen) override;
7706
Akira Hatanakad572cf42018-11-06 07:05:14 +00007707 void handleInvalidMaskType(StringRef MaskType) override;
7708
Ted Kremenek02087932010-07-16 02:11:22 +00007709 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7710 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007711 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007712 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7713 const char *StartSpecifier,
7714 unsigned SpecifierLen,
7715 const Expr *E);
7716
Ted Kremenek02087932010-07-16 02:11:22 +00007717 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7718 const char *startSpecifier, unsigned specifierLen);
7719 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7720 const analyze_printf::OptionalAmount &Amt,
7721 unsigned type,
7722 const char *startSpecifier, unsigned specifierLen);
7723 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7724 const analyze_printf::OptionalFlag &flag,
7725 const char *startSpecifier, unsigned specifierLen);
7726 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7727 const analyze_printf::OptionalFlag &ignoredFlag,
7728 const analyze_printf::OptionalFlag &flag,
7729 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007730 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007731 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007732
Ted Kremenek2b417712015-07-02 05:39:16 +00007733 void HandleEmptyObjCModifierFlag(const char *startFlag,
7734 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007735
Ted Kremenek2b417712015-07-02 05:39:16 +00007736 void HandleInvalidObjCModifierFlag(const char *startFlag,
7737 unsigned flagLen) override;
7738
7739 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7740 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007741 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007742 override;
7743};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007744
7745} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007746
7747bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7748 const analyze_printf::PrintfSpecifier &FS,
7749 const char *startSpecifier,
7750 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007751 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007752 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007753
Ted Kremenekce815422010-07-19 21:25:57 +00007754 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7755 getLocationOfByte(CS.getStart()),
7756 startSpecifier, specifierLen,
7757 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007758}
7759
Akira Hatanakad572cf42018-11-06 07:05:14 +00007760void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7761 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7762}
7763
Ted Kremenek02087932010-07-16 02:11:22 +00007764bool CheckPrintfHandler::HandleAmount(
7765 const analyze_format_string::OptionalAmount &Amt,
7766 unsigned k, const char *startSpecifier,
7767 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007768 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007769 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007770 unsigned argIndex = Amt.getArgIndex();
7771 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007772 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7773 << k,
7774 getLocationOfByte(Amt.getStart()),
7775 /*IsStringLocation*/true,
7776 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007777 // Don't do any more checking. We will just emit
7778 // spurious errors.
7779 return false;
7780 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007781
Ted Kremenek5739de72010-01-29 01:06:55 +00007782 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007783 // Although not in conformance with C99, we also allow the argument to be
7784 // an 'unsigned int' as that is a reasonably safe case. GCC also
7785 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007786 CoveredArgs.set(argIndex);
7787 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007788 if (!Arg)
7789 return false;
7790
Ted Kremenek5739de72010-01-29 01:06:55 +00007791 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007792
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007793 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7794 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007795
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007796 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007798 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007799 << T << Arg->getSourceRange(),
7800 getLocationOfByte(Amt.getStart()),
7801 /*IsStringLocation*/true,
7802 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007803 // Don't do any more checking. We will just emit
7804 // spurious errors.
7805 return false;
7806 }
7807 }
7808 }
7809 return true;
7810}
Ted Kremenek5739de72010-01-29 01:06:55 +00007811
Tom Careb49ec692010-06-17 19:00:27 +00007812void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007813 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007814 const analyze_printf::OptionalAmount &Amt,
7815 unsigned type,
7816 const char *startSpecifier,
7817 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007818 const analyze_printf::PrintfConversionSpecifier &CS =
7819 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007820
Richard Trieu03cf7b72011-10-28 00:41:25 +00007821 FixItHint fixit =
7822 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7823 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7824 Amt.getConstantLength()))
7825 : FixItHint();
7826
7827 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7828 << type << CS.toString(),
7829 getLocationOfByte(Amt.getStart()),
7830 /*IsStringLocation*/true,
7831 getSpecifierRange(startSpecifier, specifierLen),
7832 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007833}
7834
Ted Kremenek02087932010-07-16 02:11:22 +00007835void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007836 const analyze_printf::OptionalFlag &flag,
7837 const char *startSpecifier,
7838 unsigned specifierLen) {
7839 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007840 const analyze_printf::PrintfConversionSpecifier &CS =
7841 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7843 << flag.toString() << CS.toString(),
7844 getLocationOfByte(flag.getPosition()),
7845 /*IsStringLocation*/true,
7846 getSpecifierRange(startSpecifier, specifierLen),
7847 FixItHint::CreateRemoval(
7848 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007849}
7850
7851void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007852 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007853 const analyze_printf::OptionalFlag &ignoredFlag,
7854 const analyze_printf::OptionalFlag &flag,
7855 const char *startSpecifier,
7856 unsigned specifierLen) {
7857 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007858 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7859 << ignoredFlag.toString() << flag.toString(),
7860 getLocationOfByte(ignoredFlag.getPosition()),
7861 /*IsStringLocation*/true,
7862 getSpecifierRange(startSpecifier, specifierLen),
7863 FixItHint::CreateRemoval(
7864 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007865}
7866
Ted Kremenek2b417712015-07-02 05:39:16 +00007867void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7868 unsigned flagLen) {
7869 // Warn about an empty flag.
7870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7871 getLocationOfByte(startFlag),
7872 /*IsStringLocation*/true,
7873 getSpecifierRange(startFlag, flagLen));
7874}
7875
7876void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7877 unsigned flagLen) {
7878 // Warn about an invalid flag.
7879 auto Range = getSpecifierRange(startFlag, flagLen);
7880 StringRef flag(startFlag, flagLen);
7881 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7882 getLocationOfByte(startFlag),
7883 /*IsStringLocation*/true,
7884 Range, FixItHint::CreateRemoval(Range));
7885}
7886
7887void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7888 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7889 // Warn about using '[...]' without a '@' conversion.
7890 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7891 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7892 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7893 getLocationOfByte(conversionPosition),
7894 /*IsStringLocation*/true,
7895 Range, FixItHint::CreateRemoval(Range));
7896}
7897
Richard Smith55ce3522012-06-25 20:30:08 +00007898// Determines if the specified is a C++ class or struct containing
7899// a member with the specified name and kind (e.g. a CXXMethodDecl named
7900// "c_str()").
7901template<typename MemberKind>
7902static llvm::SmallPtrSet<MemberKind*, 1>
7903CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7904 const RecordType *RT = Ty->getAs<RecordType>();
7905 llvm::SmallPtrSet<MemberKind*, 1> Results;
7906
7907 if (!RT)
7908 return Results;
7909 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007910 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007911 return Results;
7912
Alp Tokerb6cc5922014-05-03 03:45:55 +00007913 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007914 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007915 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007916
7917 // We just need to include all members of the right kind turned up by the
7918 // filter, at this point.
7919 if (S.LookupQualifiedName(R, RT->getDecl()))
7920 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7921 NamedDecl *decl = (*I)->getUnderlyingDecl();
7922 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7923 Results.insert(FK);
7924 }
7925 return Results;
7926}
7927
Richard Smith2868a732014-02-28 01:36:39 +00007928/// Check if we could call '.c_str()' on an object.
7929///
7930/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7931/// allow the call, or if it would be ambiguous).
7932bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007933 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7934
Richard Smith2868a732014-02-28 01:36:39 +00007935 MethodSet Results =
7936 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7937 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7938 MI != ME; ++MI)
7939 if ((*MI)->getMinRequiredArguments() == 0)
7940 return true;
7941 return false;
7942}
7943
Richard Smith55ce3522012-06-25 20:30:08 +00007944// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007945// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007946// Returns true when a c_str() conversion method is found.
7947bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007948 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007949 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007950
7951 MethodSet Results =
7952 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7953
7954 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7955 MI != ME; ++MI) {
7956 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007957 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007958 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007959 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007960 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007961 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7962 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007963 return true;
7964 }
7965 }
7966
7967 return false;
7968}
7969
Ted Kremenekab278de2010-01-28 23:39:18 +00007970bool
Ted Kremenek02087932010-07-16 02:11:22 +00007971CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007972 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007973 const char *startSpecifier,
7974 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007975 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007976 using namespace analyze_printf;
7977
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007978 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007979
Ted Kremenek6cd69422010-07-19 22:01:06 +00007980 if (FS.consumesDataArgument()) {
7981 if (atFirstArg) {
7982 atFirstArg = false;
7983 usesPositionalArgs = FS.usesPositionalArg();
7984 }
7985 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007986 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7987 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007988 return false;
7989 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007990 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007991
Ted Kremenekd1668192010-02-27 01:41:03 +00007992 // First check if the field width, precision, and conversion specifier
7993 // have matching data arguments.
7994 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7995 startSpecifier, specifierLen)) {
7996 return false;
7997 }
7998
7999 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8000 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00008001 return false;
8002 }
8003
Ted Kremenek8d9842d2010-01-29 20:55:36 +00008004 if (!CS.consumesDataArgument()) {
8005 // FIXME: Technically specifying a precision or field width here
8006 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00008007 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00008008 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008009
Ted Kremenek4a49d982010-02-26 19:18:41 +00008010 // Consume the argument.
8011 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00008012 if (argIndex < NumDataArgs) {
8013 // The check to see if the argIndex is valid will come later.
8014 // We set the bit here because we may exit early from this
8015 // function if we encounter some other error.
8016 CoveredArgs.set(argIndex);
8017 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00008018
Dimitry Andric6b5ed342015-02-19 22:32:33 +00008019 // FreeBSD kernel extensions.
8020 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8021 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8022 // We need at least two arguments.
8023 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8024 return false;
8025
8026 // Claim the second argument.
8027 CoveredArgs.set(argIndex + 1);
8028
8029 // Type check the first argument (int for %b, pointer for %D)
8030 const Expr *Ex = getDataArg(argIndex);
8031 const analyze_printf::ArgType &AT =
8032 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8033 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8034 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8035 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008036 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8037 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8038 << false << Ex->getSourceRange(),
8039 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8040 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00008041
8042 // Type check the second argument (char * for both %b and %D)
8043 Ex = getDataArg(argIndex + 1);
8044 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8045 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8046 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008047 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8048 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8049 << false << Ex->getSourceRange(),
8050 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8051 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00008052
8053 return true;
8054 }
8055
Ted Kremenek4a49d982010-02-26 19:18:41 +00008056 // Check for using an Objective-C specific conversion specifier
8057 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00008058 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00008059 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8060 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00008061 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008062
Mehdi Amini06d367c2016-10-24 20:39:34 +00008063 // %P can only be used with os_log.
8064 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8065 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8066 specifierLen);
8067 }
8068
8069 // %n is not allowed with os_log.
8070 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8071 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8072 getLocationOfByte(CS.getStart()),
8073 /*IsStringLocation*/ false,
8074 getSpecifierRange(startSpecifier, specifierLen));
8075
8076 return true;
8077 }
8078
8079 // Only scalars are allowed for os_trace.
8080 if (FSType == Sema::FST_OSTrace &&
8081 (CS.getKind() == ConversionSpecifier::PArg ||
8082 CS.getKind() == ConversionSpecifier::sArg ||
8083 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8084 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8085 specifierLen);
8086 }
8087
8088 // Check for use of public/private annotation outside of os_log().
8089 if (FSType != Sema::FST_OSLog) {
8090 if (FS.isPublic().isSet()) {
8091 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8092 << "public",
8093 getLocationOfByte(FS.isPublic().getPosition()),
8094 /*IsStringLocation*/ false,
8095 getSpecifierRange(startSpecifier, specifierLen));
8096 }
8097 if (FS.isPrivate().isSet()) {
8098 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8099 << "private",
8100 getLocationOfByte(FS.isPrivate().getPosition()),
8101 /*IsStringLocation*/ false,
8102 getSpecifierRange(startSpecifier, specifierLen));
8103 }
8104 }
8105
Tom Careb49ec692010-06-17 19:00:27 +00008106 // Check for invalid use of field width
8107 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00008108 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00008109 startSpecifier, specifierLen);
8110 }
8111
8112 // Check for invalid use of precision
8113 if (!FS.hasValidPrecision()) {
8114 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8115 startSpecifier, specifierLen);
8116 }
8117
Mehdi Amini06d367c2016-10-24 20:39:34 +00008118 // Precision is mandatory for %P specifier.
8119 if (CS.getKind() == ConversionSpecifier::PArg &&
8120 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8121 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8122 getLocationOfByte(startSpecifier),
8123 /*IsStringLocation*/ false,
8124 getSpecifierRange(startSpecifier, specifierLen));
8125 }
8126
Tom Careb49ec692010-06-17 19:00:27 +00008127 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00008128 if (!FS.hasValidThousandsGroupingPrefix())
8129 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00008130 if (!FS.hasValidLeadingZeros())
8131 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8132 if (!FS.hasValidPlusPrefix())
8133 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00008134 if (!FS.hasValidSpacePrefix())
8135 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00008136 if (!FS.hasValidAlternativeForm())
8137 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8138 if (!FS.hasValidLeftJustified())
8139 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8140
8141 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00008142 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8143 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8144 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00008145 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8146 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8147 startSpecifier, specifierLen);
8148
8149 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00008150 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8151 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008152 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8153 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008154 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008155 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008156 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008157 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8158 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00008159
Jordan Rose92303592012-09-08 04:00:03 +00008160 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8161 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8162
Ted Kremenek9fcd8302010-01-29 01:43:31 +00008163 // The remaining checks depend on the data arguments.
8164 if (HasVAListArg)
8165 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008166
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008167 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00008168 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008169
Jordan Rose58bbe422012-07-19 18:10:08 +00008170 const Expr *Arg = getDataArg(argIndex);
8171 if (!Arg)
8172 return true;
8173
8174 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00008175}
8176
Jordan Roseaee34382012-09-05 22:56:26 +00008177static bool requiresParensToAddCast(const Expr *E) {
8178 // FIXME: We should have a general way to reason about operator
8179 // precedence and whether parens are actually needed here.
8180 // Take care of a few common cases where they aren't.
8181 const Expr *Inside = E->IgnoreImpCasts();
8182 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8183 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8184
8185 switch (Inside->getStmtClass()) {
8186 case Stmt::ArraySubscriptExprClass:
8187 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008188 case Stmt::CharacterLiteralClass:
8189 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008190 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008191 case Stmt::FloatingLiteralClass:
8192 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008193 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008194 case Stmt::ObjCArrayLiteralClass:
8195 case Stmt::ObjCBoolLiteralExprClass:
8196 case Stmt::ObjCBoxedExprClass:
8197 case Stmt::ObjCDictionaryLiteralClass:
8198 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008199 case Stmt::ObjCIvarRefExprClass:
8200 case Stmt::ObjCMessageExprClass:
8201 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008202 case Stmt::ObjCStringLiteralClass:
8203 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008204 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008205 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008206 case Stmt::UnaryOperatorClass:
8207 return false;
8208 default:
8209 return true;
8210 }
8211}
8212
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008213static std::pair<QualType, StringRef>
8214shouldNotPrintDirectly(const ASTContext &Context,
8215 QualType IntendedTy,
8216 const Expr *E) {
8217 // Use a 'while' to peel off layers of typedefs.
8218 QualType TyTy = IntendedTy;
8219 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8220 StringRef Name = UserTy->getDecl()->getName();
8221 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00008222 .Case("CFIndex", Context.getNSIntegerType())
8223 .Case("NSInteger", Context.getNSIntegerType())
8224 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008225 .Case("SInt32", Context.IntTy)
8226 .Case("UInt32", Context.UnsignedIntTy)
8227 .Default(QualType());
8228
8229 if (!CastTy.isNull())
8230 return std::make_pair(CastTy, Name);
8231
8232 TyTy = UserTy->desugar();
8233 }
8234
8235 // Strip parens if necessary.
8236 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8237 return shouldNotPrintDirectly(Context,
8238 PE->getSubExpr()->getType(),
8239 PE->getSubExpr());
8240
8241 // If this is a conditional expression, then its result type is constructed
8242 // via usual arithmetic conversions and thus there might be no necessary
8243 // typedef sugar there. Recurse to operands to check for NSInteger &
8244 // Co. usage condition.
8245 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8246 QualType TrueTy, FalseTy;
8247 StringRef TrueName, FalseName;
8248
8249 std::tie(TrueTy, TrueName) =
8250 shouldNotPrintDirectly(Context,
8251 CO->getTrueExpr()->getType(),
8252 CO->getTrueExpr());
8253 std::tie(FalseTy, FalseName) =
8254 shouldNotPrintDirectly(Context,
8255 CO->getFalseExpr()->getType(),
8256 CO->getFalseExpr());
8257
8258 if (TrueTy == FalseTy)
8259 return std::make_pair(TrueTy, TrueName);
8260 else if (TrueTy.isNull())
8261 return std::make_pair(FalseTy, FalseName);
8262 else if (FalseTy.isNull())
8263 return std::make_pair(TrueTy, TrueName);
8264 }
8265
8266 return std::make_pair(QualType(), StringRef());
8267}
8268
Aaron Ballman94d2d092018-12-18 15:54:38 +00008269/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8270/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8271/// type do not count.
8272static bool
8273isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8274 QualType From = ICE->getSubExpr()->getType();
8275 QualType To = ICE->getType();
8276 // It's an integer promotion if the destination type is the promoted
8277 // source type.
8278 if (ICE->getCastKind() == CK_IntegralCast &&
8279 From->isPromotableIntegerType() &&
8280 S.Context.getPromotedIntegerType(From) == To)
8281 return true;
8282 // Look through vector types, since we do default argument promotion for
8283 // those in OpenCL.
8284 if (const auto *VecTy = From->getAs<ExtVectorType>())
8285 From = VecTy->getElementType();
8286 if (const auto *VecTy = To->getAs<ExtVectorType>())
8287 To = VecTy->getElementType();
8288 // It's a floating promotion if the source type is a lower rank.
8289 return ICE->getCastKind() == CK_FloatingCast &&
8290 S.Context.getFloatingTypeOrder(From, To) < 0;
8291}
8292
Richard Smith55ce3522012-06-25 20:30:08 +00008293bool
8294CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8295 const char *StartSpecifier,
8296 unsigned SpecifierLen,
8297 const Expr *E) {
8298 using namespace analyze_format_string;
8299 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008300
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008301 // Now type check the data expression that matches the
8302 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00008303 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00008304 if (!AT.isValid())
8305 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00008306
Jordan Rose598ec092012-12-05 18:44:40 +00008307 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00008308 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8309 ExprTy = TET->getUnderlyingExpr()->getType();
8310 }
8311
Erik Pilkington5741d192019-09-18 19:05:14 +00008312 // Diagnose attempts to print a boolean value as a character. Unlike other
8313 // -Wformat diagnostics, this is fine from a type perspective, but it still
8314 // doesn't make sense.
8315 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8316 E->isKnownToHaveBooleanValue()) {
8317 const CharSourceRange &CSR =
8318 getSpecifierRange(StartSpecifier, SpecifierLen);
8319 SmallString<4> FSString;
8320 llvm::raw_svector_ostream os(FSString);
8321 FS.toString(os);
8322 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8323 << FSString,
8324 E->getExprLoc(), false, CSR);
8325 return true;
8326 }
8327
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008328 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
JF Bastienec7d7f32018-06-22 21:54:40 +00008329 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00008330 return true;
Jordan Rose98709982012-06-04 22:48:57 +00008331
Jordan Rose22b74712012-09-05 22:56:19 +00008332 // Look through argument promotions for our error message's reported type.
8333 // This includes the integral and floating promotions, but excludes array
Aaron Ballman94d2d092018-12-18 15:54:38 +00008334 // and function pointer decay (seeing that an argument intended to be a
8335 // string has type 'char [6]' is probably more confusing than 'char *') and
8336 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
Jordan Rose22b74712012-09-05 22:56:19 +00008337 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Aaron Ballman94d2d092018-12-18 15:54:38 +00008338 if (isArithmeticArgumentPromotion(S, ICE)) {
Jordan Rose22b74712012-09-05 22:56:19 +00008339 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00008340 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00008341
8342 // Check if we didn't match because of an implicit cast from a 'char'
8343 // or 'short' to an 'int'. This is done because printf is a varargs
8344 // function.
8345 if (ICE->getType() == S.Context.IntTy ||
8346 ICE->getType() == S.Context.UnsignedIntTy) {
Nathan Huckleberrycc01d642019-08-23 18:01:57 +00008347 // All further checking is done on the subexpression
8348 const analyze_printf::ArgType::MatchKind ImplicitMatch =
8349 AT.matchesType(S.Context, ExprTy);
8350 if (ImplicitMatch == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00008351 return true;
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008352 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8353 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8354 Match = ImplicitMatch;
Ted Kremenek12a37de2010-10-21 04:00:58 +00008355 }
Jordan Rose98709982012-06-04 22:48:57 +00008356 }
Jordan Rose598ec092012-12-05 18:44:40 +00008357 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8358 // Special case for 'a', which has type 'int' in C.
8359 // Note, however, that we do /not/ want to treat multibyte constants like
8360 // 'MooV' as characters! This form is deprecated but still exists.
8361 if (ExprTy == S.Context.IntTy)
8362 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8363 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00008364 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008365
Jordan Rosebc53ed12014-05-31 04:12:14 +00008366 // Look through enums to their underlying type.
8367 bool IsEnum = false;
8368 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8369 ExprTy = EnumTy->getDecl()->getIntegerType();
8370 IsEnum = true;
8371 }
8372
Jordan Rose0e5badd2012-12-05 18:44:49 +00008373 // %C in an Objective-C context prints a unichar, not a wchar_t.
8374 // If the argument is an integer of some kind, believe the %C and suggest
8375 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00008376 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00008377 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00008378 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8379 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8380 !ExprTy->isCharType()) {
8381 // 'unichar' is defined as a typedef of unsigned short, but we should
8382 // prefer using the typedef if it is visible.
8383 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00008384
8385 // While we are here, check if the value is an IntegerLiteral that happens
8386 // to be within the valid range.
8387 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8388 const llvm::APInt &V = IL->getValue();
8389 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8390 return true;
8391 }
8392
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008393 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00008394 Sema::LookupOrdinaryName);
8395 if (S.LookupName(Result, S.getCurScope())) {
8396 NamedDecl *ND = Result.getFoundDecl();
8397 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8398 if (TD->getUnderlyingType() == IntendedTy)
8399 IntendedTy = S.Context.getTypedefType(TD);
8400 }
8401 }
8402 }
8403
8404 // Special-case some of Darwin's platform-independence types by suggesting
8405 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008406 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00008407 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008408 QualType CastTy;
8409 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8410 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008411 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00008412 // (long in ASTContext). Only complain to pedants.
8413 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008414 (AT.isSizeT() || AT.isPtrdiffT()) &&
8415 AT.matchesType(S.Context, CastTy))
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008416 Match = ArgType::NoMatchPedantic;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008417 IntendedTy = CastTy;
8418 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00008419 }
8420 }
8421
Jordan Rose22b74712012-09-05 22:56:19 +00008422 // We may be able to offer a FixItHint if it is a supported type.
8423 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008424 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00008425 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008426
JF Bastienec7d7f32018-06-22 21:54:40 +00008427 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00008428 // Get the fix string from the fixed format specifier
8429 SmallString<16> buf;
8430 llvm::raw_svector_ostream os(buf);
8431 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008432
Jordan Roseaee34382012-09-05 22:56:26 +00008433 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8434
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008435 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008436 unsigned Diag;
8437 switch (Match) {
8438 case ArgType::Match: llvm_unreachable("expected non-matching");
8439 case ArgType::NoMatchPedantic:
8440 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8441 break;
8442 case ArgType::NoMatchTypeConfusion:
8443 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8444 break;
8445 case ArgType::NoMatch:
8446 Diag = diag::warn_format_conversion_argument_type_mismatch;
8447 break;
8448 }
8449
Jordan Rose0e5badd2012-12-05 18:44:49 +00008450 // In this case, the specifier is wrong and should be changed to match
8451 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00008452 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00008453 << AT.getRepresentativeTypeName(S.Context)
8454 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008455 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00008456 /*IsStringLocation*/ false, SpecRange,
8457 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00008458 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00008459 // The canonical type for formatting this value is different from the
8460 // actual type of the expression. (This occurs, for example, with Darwin's
8461 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8462 // should be printed as 'long' for 64-bit compatibility.)
8463 // Rather than emitting a normal format/argument mismatch, we want to
8464 // add a cast to the recommended type (and correct the format string
8465 // if necessary).
8466 SmallString<16> CastBuf;
8467 llvm::raw_svector_ostream CastFix(CastBuf);
8468 CastFix << "(";
8469 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8470 CastFix << ")";
8471
8472 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00008473 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00008474 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8475
8476 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8477 // If there's already a cast present, just replace it.
8478 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8479 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8480
8481 } else if (!requiresParensToAddCast(E)) {
8482 // If the expression has high enough precedence,
8483 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008484 Hints.push_back(
8485 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008486 } else {
8487 // Otherwise, add parens around the expression as well as the cast.
8488 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008489 Hints.push_back(
8490 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008491
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008492 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00008493 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8494 }
8495
Jordan Rose0e5badd2012-12-05 18:44:49 +00008496 if (ShouldNotPrintDirectly) {
8497 // The expression has a type that should not be printed directly.
8498 // We extract the name from the typedef because we don't want to show
8499 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008500 StringRef Name;
8501 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8502 Name = TypedefTy->getDecl()->getName();
8503 else
8504 Name = CastTyName;
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008505 unsigned Diag = Match == ArgType::NoMatchPedantic
JF Bastienec7d7f32018-06-22 21:54:40 +00008506 ? diag::warn_format_argument_needs_cast_pedantic
8507 : diag::warn_format_argument_needs_cast;
8508 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8509 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008510 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00008511 SpecRange, Hints);
8512 } else {
8513 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00008514 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00008515 // and we should cast instead. Just use the normal warning message.
8516 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008517 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8518 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8519 << E->getSourceRange(),
8520 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00008521 }
Jordan Roseaee34382012-09-05 22:56:26 +00008522 }
Jordan Rose22b74712012-09-05 22:56:19 +00008523 } else {
8524 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8525 SpecifierLen);
8526 // Since the warning for passing non-POD types to variadic functions
8527 // was deferred until now, we emit a warning for non-POD
8528 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00008529 switch (S.isValidVarArgType(ExprTy)) {
8530 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00008531 case Sema::VAK_ValidInCXX11: {
Erik Pilkingtonf7766b1e2019-10-04 19:20:27 +00008532 unsigned Diag;
8533 switch (Match) {
8534 case ArgType::Match: llvm_unreachable("expected non-matching");
8535 case ArgType::NoMatchPedantic:
8536 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8537 break;
8538 case ArgType::NoMatchTypeConfusion:
8539 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8540 break;
8541 case ArgType::NoMatch:
8542 Diag = diag::warn_format_conversion_argument_type_mismatch;
8543 break;
8544 }
Richard Smithd7293d72013-08-05 18:49:43 +00008545
Seth Cantrellb4802962015-03-04 03:12:10 +00008546 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008547 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00008548 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008549 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00008550 break;
8551 }
Richard Smithd7293d72013-08-05 18:49:43 +00008552 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00008553 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008554 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8555 << S.getLangOpts().CPlusPlus11 << ExprTy
8556 << CallType
8557 << AT.getRepresentativeTypeName(S.Context) << CSR
8558 << E->getSourceRange(),
8559 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00008560 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00008561 break;
8562
8563 case Sema::VAK_Invalid:
8564 if (ExprTy->isObjCObjectType())
8565 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008566 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8567 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8568 << AT.getRepresentativeTypeName(S.Context) << CSR
8569 << E->getSourceRange(),
8570 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00008571 else
8572 // FIXME: If this is an initializer list, suggest removing the braces
8573 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008574 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8575 << isa<InitListExpr>(E) << ExprTy << CallType
8576 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00008577 break;
8578 }
8579
8580 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8581 "format string specifier index out of range");
8582 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008583 }
8584
Ted Kremenekab278de2010-01-28 23:39:18 +00008585 return true;
8586}
8587
Ted Kremenek02087932010-07-16 02:11:22 +00008588//===--- CHECK: Scanf format string checking ------------------------------===//
8589
Fangrui Song6907ce22018-07-30 19:24:48 +00008590namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008591
Ted Kremenek02087932010-07-16 02:11:22 +00008592class CheckScanfHandler : public CheckFormatHandler {
8593public:
Stephen Hines648c3692016-09-16 01:07:04 +00008594 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00008595 const Expr *origFormatExpr, Sema::FormatStringType type,
8596 unsigned firstDataArg, unsigned numDataArgs,
8597 const char *beg, bool hasVAListArg,
8598 ArrayRef<const Expr *> Args, unsigned formatIdx,
8599 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008600 llvm::SmallBitVector &CheckedVarArgs,
8601 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00008602 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8603 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8604 inFunctionCall, CallType, CheckedVarArgs,
8605 UncoveredArg) {}
8606
Ted Kremenek02087932010-07-16 02:11:22 +00008607 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8608 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008609 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00008610
Ted Kremenekce815422010-07-19 21:25:57 +00008611 bool HandleInvalidScanfConversionSpecifier(
8612 const analyze_scanf::ScanfSpecifier &FS,
8613 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008614 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008615
Craig Toppere14c0f82014-03-12 04:55:44 +00008616 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00008617};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008618
8619} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00008620
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008621void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8622 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008623 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8624 getLocationOfByte(end), /*IsStringLocation*/true,
8625 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008626}
8627
Ted Kremenekce815422010-07-19 21:25:57 +00008628bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8629 const analyze_scanf::ScanfSpecifier &FS,
8630 const char *startSpecifier,
8631 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008632 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00008633 FS.getConversionSpecifier();
8634
8635 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8636 getLocationOfByte(CS.getStart()),
8637 startSpecifier, specifierLen,
8638 CS.getStart(), CS.getLength());
8639}
8640
Ted Kremenek02087932010-07-16 02:11:22 +00008641bool CheckScanfHandler::HandleScanfSpecifier(
8642 const analyze_scanf::ScanfSpecifier &FS,
8643 const char *startSpecifier,
8644 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008645 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008646 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008647
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008648 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008649
Ted Kremenek6cd69422010-07-19 22:01:06 +00008650 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8651 // be used to decide if we are using positional arguments consistently.
8652 if (FS.consumesDataArgument()) {
8653 if (atFirstArg) {
8654 atFirstArg = false;
8655 usesPositionalArgs = FS.usesPositionalArg();
8656 }
8657 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008658 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8659 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008660 return false;
8661 }
Ted Kremenek02087932010-07-16 02:11:22 +00008662 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008663
Ted Kremenek02087932010-07-16 02:11:22 +00008664 // Check if the field with is non-zero.
8665 const OptionalAmount &Amt = FS.getFieldWidth();
8666 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8667 if (Amt.getConstantAmount() == 0) {
8668 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8669 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008670 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8671 getLocationOfByte(Amt.getStart()),
8672 /*IsStringLocation*/true, R,
8673 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008674 }
8675 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008676
Ted Kremenek02087932010-07-16 02:11:22 +00008677 if (!FS.consumesDataArgument()) {
8678 // FIXME: Technically specifying a precision or field width here
8679 // makes no sense. Worth issuing a warning at some point.
8680 return true;
8681 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008682
Ted Kremenek02087932010-07-16 02:11:22 +00008683 // Consume the argument.
8684 unsigned argIndex = FS.getArgIndex();
8685 if (argIndex < NumDataArgs) {
8686 // The check to see if the argIndex is valid will come later.
8687 // We set the bit here because we may exit early from this
8688 // function if we encounter some other error.
8689 CoveredArgs.set(argIndex);
8690 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008691
Ted Kremenek4407ea42010-07-20 20:04:47 +00008692 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00008693 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8694 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008695 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8696 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008697 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008698 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008699 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008700 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8701 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008702
Jordan Rose92303592012-09-08 04:00:03 +00008703 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8704 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8705
Ted Kremenek02087932010-07-16 02:11:22 +00008706 // The remaining checks depend on the data arguments.
8707 if (HasVAListArg)
8708 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008709
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008710 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008711 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008712
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008713 // Check that the argument type matches the format specifier.
8714 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008715 if (!Ex)
8716 return true;
8717
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008718 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008719
8720 if (!AT.isValid()) {
8721 return true;
8722 }
8723
JF Bastienec7d7f32018-06-22 21:54:40 +00008724 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008725 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008726 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8727 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008728 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008729
Seth Cantrell79340072015-03-04 05:58:08 +00008730 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008731 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008732 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008733
JF Bastienec7d7f32018-06-22 21:54:40 +00008734 unsigned Diag =
8735 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8736 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008737
JF Bastienec7d7f32018-06-22 21:54:40 +00008738 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008739 // Get the fix string from the fixed format specifier.
8740 SmallString<128> buf;
8741 llvm::raw_svector_ostream os(buf);
8742 fixedFS.toString(os);
8743
8744 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008745 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008746 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008747 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008748 /*IsStringLocation*/ false,
8749 getSpecifierRange(startSpecifier, specifierLen),
8750 FixItHint::CreateReplacement(
8751 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8752 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008753 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008754 << AT.getRepresentativeTypeName(S.Context)
8755 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008756 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008757 /*IsStringLocation*/ false,
8758 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008759 }
8760
Ted Kremenek02087932010-07-16 02:11:22 +00008761 return true;
8762}
8763
Stephen Hines648c3692016-09-16 01:07:04 +00008764static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008765 const Expr *OrigFormatExpr,
8766 ArrayRef<const Expr *> Args,
8767 bool HasVAListArg, unsigned format_idx,
8768 unsigned firstDataArg,
8769 Sema::FormatStringType Type,
8770 bool inFunctionCall,
8771 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008772 llvm::SmallBitVector &CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00008773 UncoveredArgHandler &UncoveredArg,
8774 bool IgnoreStringsWithoutSpecifiers) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008775 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008776 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008777 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008778 S, inFunctionCall, Args[format_idx],
8779 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8780 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008781 return;
8782 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008783
Ted Kremenekab278de2010-01-28 23:39:18 +00008784 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008785 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008786 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008787 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008788 const ConstantArrayType *T =
8789 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008790 assert(T && "String literal not of constant array type!");
8791 size_t TypeSize = T->getSize().getZExtValue();
8792 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008793 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008794
Erik Pilkingtonaa385562019-08-14 16:57:11 +00008795 if (IgnoreStringsWithoutSpecifiers &&
8796 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8797 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8798 return;
8799
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008800 // Emit a warning if the string literal is truncated and does not contain an
8801 // embedded null character.
8802 if (TypeSize <= StrRef.size() &&
8803 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8804 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008805 S, inFunctionCall, Args[format_idx],
8806 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008807 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008808 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8809 return;
8810 }
8811
Ted Kremenekab278de2010-01-28 23:39:18 +00008812 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008813 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008814 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008815 S, inFunctionCall, Args[format_idx],
8816 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8817 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008818 return;
8819 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008820
8821 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008822 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8823 Type == Sema::FST_OSTrace) {
8824 CheckPrintfHandler H(
8825 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8826 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8827 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8828 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008829
Hans Wennborg23926bd2011-12-15 10:25:47 +00008830 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008831 S.getLangOpts(),
8832 S.Context.getTargetInfo(),
8833 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008834 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008835 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008836 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8837 numDataArgs, Str, HasVAListArg, Args, format_idx,
8838 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008839
Hans Wennborg23926bd2011-12-15 10:25:47 +00008840 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008841 S.getLangOpts(),
8842 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008843 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008844 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008845}
8846
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008847bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8848 // Str - The format string. NOTE: this is NOT null-terminated!
8849 StringRef StrRef = FExpr->getString();
8850 const char *Str = StrRef.data();
8851 // Account for cases where the string literal is truncated in a declaration.
8852 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8853 assert(T && "String literal not of constant array type!");
8854 size_t TypeSize = T->getSize().getZExtValue();
8855 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8856 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8857 getLangOpts(),
8858 Context.getTargetInfo());
8859}
8860
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008861//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8862
8863// Returns the related absolute value function that is larger, of 0 if one
8864// does not exist.
8865static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8866 switch (AbsFunction) {
8867 default:
8868 return 0;
8869
8870 case Builtin::BI__builtin_abs:
8871 return Builtin::BI__builtin_labs;
8872 case Builtin::BI__builtin_labs:
8873 return Builtin::BI__builtin_llabs;
8874 case Builtin::BI__builtin_llabs:
8875 return 0;
8876
8877 case Builtin::BI__builtin_fabsf:
8878 return Builtin::BI__builtin_fabs;
8879 case Builtin::BI__builtin_fabs:
8880 return Builtin::BI__builtin_fabsl;
8881 case Builtin::BI__builtin_fabsl:
8882 return 0;
8883
8884 case Builtin::BI__builtin_cabsf:
8885 return Builtin::BI__builtin_cabs;
8886 case Builtin::BI__builtin_cabs:
8887 return Builtin::BI__builtin_cabsl;
8888 case Builtin::BI__builtin_cabsl:
8889 return 0;
8890
8891 case Builtin::BIabs:
8892 return Builtin::BIlabs;
8893 case Builtin::BIlabs:
8894 return Builtin::BIllabs;
8895 case Builtin::BIllabs:
8896 return 0;
8897
8898 case Builtin::BIfabsf:
8899 return Builtin::BIfabs;
8900 case Builtin::BIfabs:
8901 return Builtin::BIfabsl;
8902 case Builtin::BIfabsl:
8903 return 0;
8904
8905 case Builtin::BIcabsf:
8906 return Builtin::BIcabs;
8907 case Builtin::BIcabs:
8908 return Builtin::BIcabsl;
8909 case Builtin::BIcabsl:
8910 return 0;
8911 }
8912}
8913
8914// Returns the argument type of the absolute value function.
8915static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8916 unsigned AbsType) {
8917 if (AbsType == 0)
8918 return QualType();
8919
8920 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8921 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8922 if (Error != ASTContext::GE_None)
8923 return QualType();
8924
8925 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8926 if (!FT)
8927 return QualType();
8928
8929 if (FT->getNumParams() != 1)
8930 return QualType();
8931
8932 return FT->getParamType(0);
8933}
8934
8935// Returns the best absolute value function, or zero, based on type and
8936// current absolute value function.
8937static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8938 unsigned AbsFunctionKind) {
8939 unsigned BestKind = 0;
8940 uint64_t ArgSize = Context.getTypeSize(ArgType);
8941 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8942 Kind = getLargerAbsoluteValueFunction(Kind)) {
8943 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8944 if (Context.getTypeSize(ParamType) >= ArgSize) {
8945 if (BestKind == 0)
8946 BestKind = Kind;
8947 else if (Context.hasSameType(ParamType, ArgType)) {
8948 BestKind = Kind;
8949 break;
8950 }
8951 }
8952 }
8953 return BestKind;
8954}
8955
8956enum AbsoluteValueKind {
8957 AVK_Integer,
8958 AVK_Floating,
8959 AVK_Complex
8960};
8961
8962static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8963 if (T->isIntegralOrEnumerationType())
8964 return AVK_Integer;
8965 if (T->isRealFloatingType())
8966 return AVK_Floating;
8967 if (T->isAnyComplexType())
8968 return AVK_Complex;
8969
8970 llvm_unreachable("Type not integer, floating, or complex");
8971}
8972
8973// Changes the absolute value function to a different type. Preserves whether
8974// the function is a builtin.
8975static unsigned changeAbsFunction(unsigned AbsKind,
8976 AbsoluteValueKind ValueKind) {
8977 switch (ValueKind) {
8978 case AVK_Integer:
8979 switch (AbsKind) {
8980 default:
8981 return 0;
8982 case Builtin::BI__builtin_fabsf:
8983 case Builtin::BI__builtin_fabs:
8984 case Builtin::BI__builtin_fabsl:
8985 case Builtin::BI__builtin_cabsf:
8986 case Builtin::BI__builtin_cabs:
8987 case Builtin::BI__builtin_cabsl:
8988 return Builtin::BI__builtin_abs;
8989 case Builtin::BIfabsf:
8990 case Builtin::BIfabs:
8991 case Builtin::BIfabsl:
8992 case Builtin::BIcabsf:
8993 case Builtin::BIcabs:
8994 case Builtin::BIcabsl:
8995 return Builtin::BIabs;
8996 }
8997 case AVK_Floating:
8998 switch (AbsKind) {
8999 default:
9000 return 0;
9001 case Builtin::BI__builtin_abs:
9002 case Builtin::BI__builtin_labs:
9003 case Builtin::BI__builtin_llabs:
9004 case Builtin::BI__builtin_cabsf:
9005 case Builtin::BI__builtin_cabs:
9006 case Builtin::BI__builtin_cabsl:
9007 return Builtin::BI__builtin_fabsf;
9008 case Builtin::BIabs:
9009 case Builtin::BIlabs:
9010 case Builtin::BIllabs:
9011 case Builtin::BIcabsf:
9012 case Builtin::BIcabs:
9013 case Builtin::BIcabsl:
9014 return Builtin::BIfabsf;
9015 }
9016 case AVK_Complex:
9017 switch (AbsKind) {
9018 default:
9019 return 0;
9020 case Builtin::BI__builtin_abs:
9021 case Builtin::BI__builtin_labs:
9022 case Builtin::BI__builtin_llabs:
9023 case Builtin::BI__builtin_fabsf:
9024 case Builtin::BI__builtin_fabs:
9025 case Builtin::BI__builtin_fabsl:
9026 return Builtin::BI__builtin_cabsf;
9027 case Builtin::BIabs:
9028 case Builtin::BIlabs:
9029 case Builtin::BIllabs:
9030 case Builtin::BIfabsf:
9031 case Builtin::BIfabs:
9032 case Builtin::BIfabsl:
9033 return Builtin::BIcabsf;
9034 }
9035 }
9036 llvm_unreachable("Unable to convert function");
9037}
9038
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00009039static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009040 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9041 if (!FnInfo)
9042 return 0;
9043
9044 switch (FDecl->getBuiltinID()) {
9045 default:
9046 return 0;
9047 case Builtin::BI__builtin_abs:
9048 case Builtin::BI__builtin_fabs:
9049 case Builtin::BI__builtin_fabsf:
9050 case Builtin::BI__builtin_fabsl:
9051 case Builtin::BI__builtin_labs:
9052 case Builtin::BI__builtin_llabs:
9053 case Builtin::BI__builtin_cabs:
9054 case Builtin::BI__builtin_cabsf:
9055 case Builtin::BI__builtin_cabsl:
9056 case Builtin::BIabs:
9057 case Builtin::BIlabs:
9058 case Builtin::BIllabs:
9059 case Builtin::BIfabs:
9060 case Builtin::BIfabsf:
9061 case Builtin::BIfabsl:
9062 case Builtin::BIcabs:
9063 case Builtin::BIcabsf:
9064 case Builtin::BIcabsl:
9065 return FDecl->getBuiltinID();
9066 }
9067 llvm_unreachable("Unknown Builtin type");
9068}
9069
9070// If the replacement is valid, emit a note with replacement function.
9071// Additionally, suggest including the proper header if not already included.
9072static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00009073 unsigned AbsKind, QualType ArgType) {
9074 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00009075 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00009076 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00009077 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9078 FunctionName = "std::abs";
9079 if (ArgType->isIntegralOrEnumerationType()) {
9080 HeaderName = "cstdlib";
9081 } else if (ArgType->isRealFloatingType()) {
9082 HeaderName = "cmath";
9083 } else {
9084 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009085 }
Richard Trieubeffb832014-04-15 23:47:53 +00009086
9087 // Lookup all std::abs
9088 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00009089 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00009090 R.suppressDiagnostics();
9091 S.LookupQualifiedName(R, Std);
9092
9093 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009094 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00009095 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9096 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9097 } else {
9098 FDecl = dyn_cast<FunctionDecl>(I);
9099 }
9100 if (!FDecl)
9101 continue;
9102
9103 // Found std::abs(), check that they are the right ones.
9104 if (FDecl->getNumParams() != 1)
9105 continue;
9106
9107 // Check that the parameter type can handle the argument.
9108 QualType ParamType = FDecl->getParamDecl(0)->getType();
9109 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9110 S.Context.getTypeSize(ArgType) <=
9111 S.Context.getTypeSize(ParamType)) {
9112 // Found a function, don't need the header hint.
9113 EmitHeaderHint = false;
9114 break;
9115 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009116 }
Richard Trieubeffb832014-04-15 23:47:53 +00009117 }
9118 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00009119 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00009120 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9121
9122 if (HeaderName) {
9123 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9124 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9125 R.suppressDiagnostics();
9126 S.LookupName(R, S.getCurScope());
9127
9128 if (R.isSingleResult()) {
9129 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9130 if (FD && FD->getBuiltinID() == AbsKind) {
9131 EmitHeaderHint = false;
9132 } else {
9133 return;
9134 }
9135 } else if (!R.empty()) {
9136 return;
9137 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009138 }
9139 }
9140
9141 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00009142 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009143
Richard Trieubeffb832014-04-15 23:47:53 +00009144 if (!HeaderName)
9145 return;
9146
9147 if (!EmitHeaderHint)
9148 return;
9149
Alp Toker5d96e0a2014-07-11 20:53:51 +00009150 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9151 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00009152}
9153
Richard Trieua7f30b12016-12-06 01:42:28 +00009154template <std::size_t StrLen>
9155static bool IsStdFunction(const FunctionDecl *FDecl,
9156 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00009157 if (!FDecl)
9158 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00009159 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00009160 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00009161 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00009162 return false;
9163
9164 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009165}
9166
9167// Warn when using the wrong abs() function.
9168void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00009169 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009170 if (Call->getNumArgs() != 1)
9171 return;
9172
9173 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00009174 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00009175 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009176 return;
9177
9178 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9179 QualType ParamType = Call->getArg(0)->getType();
9180
Alp Toker5d96e0a2014-07-11 20:53:51 +00009181 // Unsigned types cannot be negative. Suggest removing the absolute value
9182 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009183 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00009184 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00009185 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009186 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9187 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00009188 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009189 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9190 return;
9191 }
9192
David Majnemer7f77eb92015-11-15 03:04:34 +00009193 // Taking the absolute value of a pointer is very suspicious, they probably
9194 // wanted to index into an array, dereference a pointer, call a function, etc.
9195 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9196 unsigned DiagType = 0;
9197 if (ArgType->isFunctionType())
9198 DiagType = 1;
9199 else if (ArgType->isArrayType())
9200 DiagType = 2;
9201
9202 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9203 return;
9204 }
9205
Richard Trieubeffb832014-04-15 23:47:53 +00009206 // std::abs has overloads which prevent most of the absolute value problems
9207 // from occurring.
9208 if (IsStdAbs)
9209 return;
9210
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009211 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9212 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9213
9214 // The argument and parameter are the same kind. Check if they are the right
9215 // size.
9216 if (ArgValueKind == ParamValueKind) {
9217 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9218 return;
9219
9220 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9221 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9222 << FDecl << ArgType << ParamType;
9223
9224 if (NewAbsKind == 0)
9225 return;
9226
9227 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00009228 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009229 return;
9230 }
9231
9232 // ArgValueKind != ParamValueKind
9233 // The wrong type of absolute value function was used. Attempt to find the
9234 // proper one.
9235 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9236 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9237 if (NewAbsKind == 0)
9238 return;
9239
9240 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9241 << FDecl << ParamValueKind << ArgValueKind;
9242
9243 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00009244 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009245}
9246
Richard Trieu67c00712016-12-05 23:41:46 +00009247//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00009248void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9249 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00009250 if (!Call || !FDecl) return;
9251
9252 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00009253 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00009254 if (Call->getExprLoc().isMacroID()) return;
9255
9256 // Only care about the one template argument, two function parameter std::max
9257 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00009258 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00009259 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9260 if (!ArgList) return;
9261 if (ArgList->size() != 1) return;
9262
9263 // Check that template type argument is unsigned integer.
9264 const auto& TA = ArgList->get(0);
9265 if (TA.getKind() != TemplateArgument::Type) return;
9266 QualType ArgType = TA.getAsType();
9267 if (!ArgType->isUnsignedIntegerType()) return;
9268
9269 // See if either argument is a literal zero.
9270 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9271 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9272 if (!MTE) return false;
Tykerb0561b32019-11-17 11:41:55 +01009273 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
Richard Trieu67c00712016-12-05 23:41:46 +00009274 if (!Num) return false;
9275 if (Num->getValue() != 0) return false;
9276 return true;
9277 };
9278
9279 const Expr *FirstArg = Call->getArg(0);
9280 const Expr *SecondArg = Call->getArg(1);
9281 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9282 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9283
9284 // Only warn when exactly one argument is zero.
9285 if (IsFirstArgZero == IsSecondArgZero) return;
9286
9287 SourceRange FirstRange = FirstArg->getSourceRange();
9288 SourceRange SecondRange = SecondArg->getSourceRange();
9289
9290 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9291
9292 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9293 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9294
9295 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9296 SourceRange RemovalRange;
9297 if (IsFirstArgZero) {
9298 RemovalRange = SourceRange(FirstRange.getBegin(),
9299 SecondRange.getBegin().getLocWithOffset(-1));
9300 } else {
9301 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9302 SecondRange.getEnd());
9303 }
9304
9305 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9306 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9307 << FixItHint::CreateRemoval(RemovalRange);
9308}
9309
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009310//===--- CHECK: Standard memory functions ---------------------------------===//
9311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009312/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00009313/// such as memcmp, strncat, etc and warns if it's a comparison.
9314///
9315/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9316static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9317 IdentifierInfo *FnName,
9318 SourceLocation FnLoc,
9319 SourceLocation RParenLoc) {
9320 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9321 if (!Size)
9322 return false;
9323
Richard Smithc70f1d62017-12-14 15:16:18 +00009324 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9325 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00009326 return false;
9327
Nico Weber0e6daef2013-12-26 23:38:39 +00009328 SourceRange SizeRange = Size->getSourceRange();
9329 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9330 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00009331 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009332 << FnName
9333 << FixItHint::CreateInsertion(
9334 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00009335 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00009336 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00009337 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00009338 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9339 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00009340
9341 return true;
9342}
9343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009344/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009345/// (e.g., whether it has a vtable).
9346static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9347 bool &IsContained) {
9348 // Look through array types while ignoring qualifiers.
9349 const Type *Ty = T->getBaseElementTypeUnsafe();
9350 IsContained = false;
9351
9352 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9353 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00009354 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009355 return nullptr;
9356
9357 if (RD->isDynamicClass())
9358 return RD;
9359
9360 // Check all the fields. If any bases were dynamic, the class is dynamic.
9361 // It's impossible for a class to transitively contain itself by value, so
9362 // infinite recursion is impossible.
9363 for (auto *FD : RD->fields()) {
9364 bool SubContained;
9365 if (const CXXRecordDecl *ContainedRD =
9366 getContainedDynamicClass(FD->getType(), SubContained)) {
9367 IsContained = true;
9368 return ContainedRD;
9369 }
9370 }
9371
9372 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00009373}
9374
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009375static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9376 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9377 if (Unary->getKind() == UETT_SizeOf)
9378 return Unary;
9379 return nullptr;
9380}
9381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009382/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009383/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00009384static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009385 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9386 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009387 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00009388 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009389}
9390
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009391/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00009392static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009393 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9394 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009395 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00009396}
9397
Akira Hatanaka2be04412018-04-17 19:13:41 +00009398namespace {
9399
9400struct SearchNonTrivialToInitializeField
9401 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9402 using Super =
9403 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9404
9405 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9406
9407 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9408 SourceLocation SL) {
9409 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9410 asDerived().visitArray(PDIK, AT, SL);
9411 return;
9412 }
9413
9414 Super::visitWithKind(PDIK, FT, SL);
9415 }
9416
9417 void visitARCStrong(QualType FT, SourceLocation SL) {
9418 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9419 }
9420 void visitARCWeak(QualType FT, SourceLocation SL) {
9421 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9422 }
9423 void visitStruct(QualType FT, SourceLocation SL) {
9424 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9425 visit(FD->getType(), FD->getLocation());
9426 }
9427 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9428 const ArrayType *AT, SourceLocation SL) {
9429 visit(getContext().getBaseElementType(AT), SL);
9430 }
9431 void visitTrivial(QualType FT, SourceLocation SL) {}
9432
9433 static void diag(QualType RT, const Expr *E, Sema &S) {
9434 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9435 }
9436
9437 ASTContext &getContext() { return S.getASTContext(); }
9438
9439 const Expr *E;
9440 Sema &S;
9441};
9442
9443struct SearchNonTrivialToCopyField
9444 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9445 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9446
9447 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9448
9449 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9450 SourceLocation SL) {
9451 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9452 asDerived().visitArray(PCK, AT, SL);
9453 return;
9454 }
9455
9456 Super::visitWithKind(PCK, FT, SL);
9457 }
9458
9459 void visitARCStrong(QualType FT, SourceLocation SL) {
9460 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9461 }
9462 void visitARCWeak(QualType FT, SourceLocation SL) {
9463 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9464 }
9465 void visitStruct(QualType FT, SourceLocation SL) {
9466 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9467 visit(FD->getType(), FD->getLocation());
9468 }
9469 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9470 SourceLocation SL) {
9471 visit(getContext().getBaseElementType(AT), SL);
9472 }
9473 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9474 SourceLocation SL) {}
9475 void visitTrivial(QualType FT, SourceLocation SL) {}
9476 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9477
9478 static void diag(QualType RT, const Expr *E, Sema &S) {
9479 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9480 }
9481
9482 ASTContext &getContext() { return S.getASTContext(); }
9483
9484 const Expr *E;
9485 Sema &S;
9486};
9487
9488}
9489
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009490/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9491static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9492 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9493
9494 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9495 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9496 return false;
9497
9498 return doesExprLikelyComputeSize(BO->getLHS()) ||
9499 doesExprLikelyComputeSize(BO->getRHS());
9500 }
9501
9502 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9503}
9504
9505/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9506///
9507/// \code
9508/// #define MACRO 0
9509/// foo(MACRO);
9510/// foo(0);
9511/// \endcode
9512///
9513/// This should return true for the first call to foo, but not for the second
9514/// (regardless of whether foo is a macro or function).
9515static bool isArgumentExpandedFromMacro(SourceManager &SM,
9516 SourceLocation CallLoc,
9517 SourceLocation ArgLoc) {
9518 if (!CallLoc.isMacroID())
9519 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9520
9521 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9522 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9523}
9524
9525/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9526/// last two arguments transposed.
9527static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9528 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9529 return;
9530
9531 const Expr *SizeArg =
9532 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9533
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009534 auto isLiteralZero = [](const Expr *E) {
9535 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9536 };
9537
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009538 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9539 SourceLocation CallLoc = Call->getRParenLoc();
9540 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009541 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009542 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9543
9544 SourceLocation DiagLoc = SizeArg->getExprLoc();
9545
9546 // Some platforms #define bzero to __builtin_memset. See if this is the
9547 // case, and if so, emit a better diagnostic.
9548 if (BId == Builtin::BIbzero ||
9549 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9550 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9551 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9552 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009553 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009554 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9555 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9556 }
9557 return;
9558 }
9559
9560 // If the second argument to a memset is a sizeof expression and the third
9561 // isn't, this is also likely an error. This should catch
9562 // 'memset(buf, sizeof(buf), 0xff)'.
9563 if (BId == Builtin::BImemset &&
9564 doesExprLikelyComputeSize(Call->getArg(1)) &&
9565 !doesExprLikelyComputeSize(Call->getArg(2))) {
9566 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9567 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9568 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9569 return;
9570 }
9571}
9572
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009573/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009574///
Chandler Carruthac687262011-06-03 06:23:57 +00009575/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009576/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9577/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009578///
9579/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009580void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00009581 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009582 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00009583 assert(BId != 0);
9584
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009585 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00009586 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009587 unsigned ExpectedNumArgs =
9588 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00009589 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009590 return;
9591
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009592 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00009593 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009594 unsigned LenArg =
9595 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00009596 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009597
Nico Weber0e6daef2013-12-26 23:38:39 +00009598 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009599 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009600 return;
9601
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009602 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9603 CheckMemaccessSize(*this, BId, Call);
9604
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009605 // We have special checking when the length is a sizeof expression.
9606 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9607 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9608 llvm::FoldingSetNodeID SizeOfArgID;
9609
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00009610 // Although widely used, 'bzero' is not a standard function. Be more strict
9611 // with the argument types before allowing diagnostics and only allow the
9612 // form bzero(ptr, sizeof(...)).
9613 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9614 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9615 return;
9616
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009617 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9618 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00009619 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009620
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009621 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00009622 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009623 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009624 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00009625
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009626 // Never warn about void type pointers. This can be used to suppress
9627 // false positives.
9628 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009629 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009630
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009631 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9632 // actually comparing the expressions for equality. Because computing the
9633 // expression IDs can be expensive, we only do this if the diagnostic is
9634 // enabled.
9635 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009636 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9637 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009638 // We only compute IDs for expressions if the warning is enabled, and
9639 // cache the sizeof arg's ID.
9640 if (SizeOfArgID == llvm::FoldingSetNodeID())
9641 SizeOfArg->Profile(SizeOfArgID, Context, true);
9642 llvm::FoldingSetNodeID DestID;
9643 Dest->Profile(DestID, Context, true);
9644 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009645 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9646 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009647 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009648 StringRef ReadableName = FnName->getName();
9649
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009650 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009651 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009652 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009653 if (!PointeeTy->isIncompleteType() &&
9654 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009655 ActionIdx = 2; // If the pointee's size is sizeof(char),
9656 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009657
9658 // If the function is defined as a builtin macro, do not show macro
9659 // expansion.
9660 SourceLocation SL = SizeOfArg->getExprLoc();
9661 SourceRange DSR = Dest->getSourceRange();
9662 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009663 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009664
9665 if (SM.isMacroArgExpansion(SL)) {
9666 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9667 SL = SM.getSpellingLoc(SL);
9668 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9669 SM.getSpellingLoc(DSR.getEnd()));
9670 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9671 SM.getSpellingLoc(SSR.getEnd()));
9672 }
9673
Anna Zaksd08d9152012-05-30 23:14:52 +00009674 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009675 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009676 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009677 << PointeeTy
9678 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009679 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009680 << SSR);
9681 DiagRuntimeBehavior(SL, SizeOfArg,
9682 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9683 << ActionIdx
9684 << SSR);
9685
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009686 break;
9687 }
9688 }
9689
9690 // Also check for cases where the sizeof argument is the exact same
9691 // type as the memory argument, and where it points to a user-defined
9692 // record type.
9693 if (SizeOfArgTy != QualType()) {
9694 if (PointeeTy->isRecordType() &&
9695 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9696 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9697 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9698 << FnName << SizeOfArgTy << ArgIdx
9699 << PointeeTy << Dest->getSourceRange()
9700 << LenExpr->getSourceRange());
9701 break;
9702 }
Nico Weberc5e73862011-06-14 16:14:58 +00009703 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009704 } else if (DestTy->isArrayType()) {
9705 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009706 }
Nico Weberc5e73862011-06-14 16:14:58 +00009707
Nico Weberc44b35e2015-03-21 17:37:46 +00009708 if (PointeeTy == QualType())
9709 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009710
Nico Weberc44b35e2015-03-21 17:37:46 +00009711 // Always complain about dynamic classes.
9712 bool IsContained;
9713 if (const CXXRecordDecl *ContainedRD =
9714 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009715
Nico Weberc44b35e2015-03-21 17:37:46 +00009716 unsigned OperationType = 0;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009717 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
Nico Weberc44b35e2015-03-21 17:37:46 +00009718 // "overwritten" if we're warning about the destination for any call
9719 // but memcmp; otherwise a verb appropriate to the call.
Clement Courbet8c3343d2019-02-14 12:00:34 +00009720 if (ArgIdx != 0 || IsCmp) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009721 if (BId == Builtin::BImemcpy)
9722 OperationType = 1;
9723 else if(BId == Builtin::BImemmove)
9724 OperationType = 2;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009725 else if (IsCmp)
Nico Weberc44b35e2015-03-21 17:37:46 +00009726 OperationType = 3;
9727 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009728
Clement Courbet8c3343d2019-02-14 12:00:34 +00009729 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9730 PDiag(diag::warn_dyn_class_memaccess)
9731 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9732 << IsContained << ContainedRD << OperationType
9733 << Call->getCallee()->getSourceRange());
Nico Weberc44b35e2015-03-21 17:37:46 +00009734 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9735 BId != Builtin::BImemset)
9736 DiagRuntimeBehavior(
9737 Dest->getExprLoc(), Dest,
9738 PDiag(diag::warn_arc_object_memaccess)
9739 << ArgIdx << FnName << PointeeTy
9740 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009741 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9742 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9743 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9744 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9745 PDiag(diag::warn_cstruct_memaccess)
9746 << ArgIdx << FnName << PointeeTy << 0);
9747 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9748 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9749 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9750 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9751 PDiag(diag::warn_cstruct_memaccess)
9752 << ArgIdx << FnName << PointeeTy << 1);
9753 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9754 } else {
9755 continue;
9756 }
9757 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009758 continue;
9759
9760 DiagRuntimeBehavior(
9761 Dest->getExprLoc(), Dest,
9762 PDiag(diag::note_bad_memaccess_silence)
9763 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9764 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009765 }
9766}
9767
Ted Kremenek6865f772011-08-18 20:55:45 +00009768// A little helper routine: ignore addition and subtraction of integer literals.
9769// This intentionally does not ignore all integer constant expressions because
9770// we don't want to remove sizeof().
9771static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9772 Ex = Ex->IgnoreParenCasts();
9773
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009774 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009775 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9776 if (!BO || !BO->isAdditiveOp())
9777 break;
9778
9779 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9780 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009781
Ted Kremenek6865f772011-08-18 20:55:45 +00009782 if (isa<IntegerLiteral>(RHS))
9783 Ex = LHS;
9784 else if (isa<IntegerLiteral>(LHS))
9785 Ex = RHS;
9786 else
9787 break;
9788 }
9789
9790 return Ex;
9791}
9792
Anna Zaks13b08572012-08-08 21:42:23 +00009793static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9794 ASTContext &Context) {
9795 // Only handle constant-sized or VLAs, but not flexible members.
9796 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9797 // Only issue the FIXIT for arrays of size > 1.
9798 if (CAT->getSize().getSExtValue() <= 1)
9799 return false;
9800 } else if (!Ty->isVariableArrayType()) {
9801 return false;
9802 }
9803 return true;
9804}
9805
Ted Kremenek6865f772011-08-18 20:55:45 +00009806// Warn if the user has made the 'size' argument to strlcpy or strlcat
9807// be the size of the source, instead of the destination.
9808void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9809 IdentifierInfo *FnName) {
9810
9811 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009812 unsigned NumArgs = Call->getNumArgs();
9813 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009814 return;
9815
9816 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9817 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009818 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009819
9820 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009821 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009822 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009823
Ted Kremenek6865f772011-08-18 20:55:45 +00009824 // Look for 'strlcpy(dst, x, sizeof(x))'
9825 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9826 CompareWithSrc = Ex;
9827 else {
9828 // Look for 'strlcpy(dst, x, strlen(x))'
9829 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009830 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9831 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009832 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9833 }
9834 }
9835
9836 if (!CompareWithSrc)
9837 return;
9838
9839 // Determine if the argument to sizeof/strlen is equal to the source
9840 // argument. In principle there's all kinds of things you could do
9841 // here, for instance creating an == expression and evaluating it with
9842 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9843 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9844 if (!SrcArgDRE)
9845 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009846
Ted Kremenek6865f772011-08-18 20:55:45 +00009847 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009848 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009849 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9850 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009851
Ted Kremenek6865f772011-08-18 20:55:45 +00009852 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009853 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9854 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009855
Ted Kremenek6865f772011-08-18 20:55:45 +00009856 // Output a FIXIT hint if the destination is an array (rather than a
9857 // pointer to an array). This could be enhanced to handle some
9858 // pointers if we know the actual size, like if DstArg is 'array+2'
9859 // we could say 'sizeof(array)-2'.
9860 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009861 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009862 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009863
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009864 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009865 llvm::raw_svector_ostream OS(sizeString);
9866 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009867 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009868 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009869
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009870 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9871 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9872 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009873}
9874
Anna Zaks314cd092012-02-01 19:08:57 +00009875/// Check if two expressions refer to the same declaration.
9876static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9877 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9878 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9879 return D1->getDecl() == D2->getDecl();
9880 return false;
9881}
9882
9883static const Expr *getStrlenExprArg(const Expr *E) {
9884 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9885 const FunctionDecl *FD = CE->getDirectCallee();
9886 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009887 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009888 return CE->getArg(0)->IgnoreParenCasts();
9889 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009890 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009891}
9892
9893// Warn on anti-patterns as the 'size' argument to strncat.
9894// The correct size argument should look like following:
9895// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9896void Sema::CheckStrncatArguments(const CallExpr *CE,
9897 IdentifierInfo *FnName) {
9898 // Don't crash if the user has the wrong number of arguments.
9899 if (CE->getNumArgs() < 3)
9900 return;
9901 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9902 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9903 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9904
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009905 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009906 CE->getRParenLoc()))
9907 return;
9908
Anna Zaks314cd092012-02-01 19:08:57 +00009909 // Identify common expressions, which are wrongly used as the size argument
9910 // to strncat and may lead to buffer overflows.
9911 unsigned PatternType = 0;
9912 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9913 // - sizeof(dst)
9914 if (referToTheSameDecl(SizeOfArg, DstArg))
9915 PatternType = 1;
9916 // - sizeof(src)
9917 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9918 PatternType = 2;
9919 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9920 if (BE->getOpcode() == BO_Sub) {
9921 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9922 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9923 // - sizeof(dst) - strlen(dst)
9924 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9925 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9926 PatternType = 1;
9927 // - sizeof(src) - (anything)
9928 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9929 PatternType = 2;
9930 }
9931 }
9932
9933 if (PatternType == 0)
9934 return;
9935
Anna Zaks5069aa32012-02-03 01:27:37 +00009936 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009937 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009938 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009939 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009940
9941 // If the function is defined as a builtin macro, do not show macro expansion.
9942 if (SM.isMacroArgExpansion(SL)) {
9943 SL = SM.getSpellingLoc(SL);
9944 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9945 SM.getSpellingLoc(SR.getEnd()));
9946 }
9947
Anna Zaks13b08572012-08-08 21:42:23 +00009948 // Check if the destination is an array (rather than a pointer to an array).
9949 QualType DstTy = DstArg->getType();
9950 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9951 Context);
9952 if (!isKnownSizeArray) {
9953 if (PatternType == 1)
9954 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9955 else
9956 Diag(SL, diag::warn_strncat_src_size) << SR;
9957 return;
9958 }
9959
Anna Zaks314cd092012-02-01 19:08:57 +00009960 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009961 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009962 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009963 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009964
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009965 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009966 llvm::raw_svector_ostream OS(sizeString);
9967 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009968 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009969 OS << ") - ";
9970 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009971 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009972 OS << ") - 1";
9973
Anna Zaks5069aa32012-02-03 01:27:37 +00009974 Diag(SL, diag::note_strncat_wrong_size)
9975 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009976}
9977
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009978void
9979Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9980 SourceLocation ReturnLoc,
9981 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009982 const AttrVec *Attrs,
9983 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009984 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009985 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9986 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009987 CheckNonNullExpr(*this, RetValExp))
9988 Diag(ReturnLoc, diag::warn_null_ret)
9989 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009990
9991 // C++11 [basic.stc.dynamic.allocation]p4:
9992 // If an allocation function declared with a non-throwing
9993 // exception-specification fails to allocate storage, it shall return
9994 // a null pointer. Any other allocation function that fails to allocate
9995 // storage shall indicate failure only by throwing an exception [...]
9996 if (FD) {
9997 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9998 if (Op == OO_New || Op == OO_Array_New) {
9999 const FunctionProtoType *Proto
10000 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +000010001 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +000010002 CheckNonNullExpr(*this, RetValExp))
10003 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10004 << FD << getLangOpts().CPlusPlus11;
10005 }
10006 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +000010007}
10008
Ted Kremenek43fb8b02007-11-25 00:58:00 +000010009//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10010
10011/// Check for comparisons of floating point operands using != and ==.
10012/// Issue a warning if these are no self-comparisons, as they are not likely
10013/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +000010014void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +000010015 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10016 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +000010017
10018 // Special case: check for x == x (which is OK).
10019 // Do not emit warnings for such cases.
10020 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10021 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10022 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +000010023 return;
Mike Stump11289f42009-09-09 15:08:12 +000010024
Ted Kremenekeda40e22007-11-29 00:59:04 +000010025 // Special case: check for comparisons against literals that can be exactly
10026 // represented by APFloat. In such cases, do not emit a warning. This
10027 // is a heuristic: often comparison against such literals are used to
10028 // detect if a value in a variable has not changed. This clearly can
10029 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +000010030 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10031 if (FLL->isExact())
10032 return;
10033 } else
10034 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10035 if (FLR->isExact())
10036 return;
Mike Stump11289f42009-09-09 15:08:12 +000010037
Ted Kremenek43fb8b02007-11-25 00:58:00 +000010038 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +000010039 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +000010040 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +000010041 return;
Mike Stump11289f42009-09-09 15:08:12 +000010042
David Blaikie1f4ff152012-07-16 20:47:22 +000010043 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +000010044 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +000010045 return;
Mike Stump11289f42009-09-09 15:08:12 +000010046
Ted Kremenek43fb8b02007-11-25 00:58:00 +000010047 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +000010048 Diag(Loc, diag::warn_floatingpoint_eq)
10049 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +000010050}
John McCallca01b222010-01-04 23:21:16 +000010051
John McCall70aa5392010-01-06 05:24:50 +000010052//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10053//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +000010054
John McCall70aa5392010-01-06 05:24:50 +000010055namespace {
John McCallca01b222010-01-04 23:21:16 +000010056
John McCall70aa5392010-01-06 05:24:50 +000010057/// Structure recording the 'active' range of an integer-valued
10058/// expression.
10059struct IntRange {
10060 /// The number of bits active in the int.
10061 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +000010062
John McCall70aa5392010-01-06 05:24:50 +000010063 /// True if the int is known not to have negative values.
10064 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +000010065
John McCall70aa5392010-01-06 05:24:50 +000010066 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010067 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +000010068
John McCall817d4af2010-11-10 23:38:19 +000010069 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +000010070 static IntRange forBoolType() {
10071 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +000010072 }
10073
John McCall817d4af2010-11-10 23:38:19 +000010074 /// Returns the range of an opaque value of the given integral type.
10075 static IntRange forValueOfType(ASTContext &C, QualType T) {
10076 return forValueOfCanonicalType(C,
10077 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +000010078 }
10079
John McCall817d4af2010-11-10 23:38:19 +000010080 /// Returns the range of an opaque value of a canonical integral type.
10081 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +000010082 assert(T->isCanonicalUnqualified());
10083
10084 if (const VectorType *VT = dyn_cast<VectorType>(T))
10085 T = VT->getElementType().getTypePtr();
10086 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10087 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +000010088 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10089 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +000010090
Roman Lebedevca1aaac2017-10-21 16:44:03 +000010091 if (!C.getLangOpts().CPlusPlus) {
10092 // For enum types in C code, use the underlying datatype.
10093 if (const EnumType *ET = dyn_cast<EnumType>(T))
10094 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10095 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10096 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +000010097 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +000010098 // In C++11, enums can have a fixed underlying type. Use this type to
10099 // compute the range.
10100 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +000010101 return IntRange(C.getIntWidth(QualType(T, 0)),
10102 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +000010103 }
John McCall18a2c2c2010-11-09 22:22:12 +000010104
David Majnemer6a426652013-06-07 22:07:20 +000010105 unsigned NumPositive = Enum->getNumPositiveBits();
10106 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +000010107
David Majnemer6a426652013-06-07 22:07:20 +000010108 if (NumNegative == 0)
10109 return IntRange(NumPositive, true/*NonNegative*/);
10110 else
10111 return IntRange(std::max(NumPositive + 1, NumNegative),
10112 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +000010113 }
John McCall70aa5392010-01-06 05:24:50 +000010114
10115 const BuiltinType *BT = cast<BuiltinType>(T);
10116 assert(BT->isInteger());
10117
10118 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10119 }
10120
John McCall817d4af2010-11-10 23:38:19 +000010121 /// Returns the "target" range of a canonical integral type, i.e.
10122 /// the range of values expressible in the type.
10123 ///
10124 /// This matches forValueOfCanonicalType except that enums have the
10125 /// full range of their type, not the range of their enumerators.
10126 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10127 assert(T->isCanonicalUnqualified());
10128
10129 if (const VectorType *VT = dyn_cast<VectorType>(T))
10130 T = VT->getElementType().getTypePtr();
10131 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10132 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +000010133 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10134 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +000010135 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +000010136 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +000010137
10138 const BuiltinType *BT = cast<BuiltinType>(T);
10139 assert(BT->isInteger());
10140
10141 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10142 }
10143
10144 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +000010145 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +000010146 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +000010147 L.NonNegative && R.NonNegative);
10148 }
10149
John McCall817d4af2010-11-10 23:38:19 +000010150 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +000010151 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +000010152 return IntRange(std::min(L.Width, R.Width),
10153 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +000010154 }
10155};
10156
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010157} // namespace
10158
10159static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10160 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +000010161 if (value.isSigned() && value.isNegative())
10162 return IntRange(value.getMinSignedBits(), false);
10163
10164 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +000010165 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +000010166
10167 // isNonNegative() just checks the sign bit without considering
10168 // signedness.
10169 return IntRange(value.getActiveBits(), true);
10170}
10171
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010172static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10173 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +000010174 if (result.isInt())
10175 return GetValueRange(C, result.getInt(), MaxWidth);
10176
10177 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +000010178 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10179 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10180 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10181 R = IntRange::join(R, El);
10182 }
John McCall70aa5392010-01-06 05:24:50 +000010183 return R;
10184 }
10185
10186 if (result.isComplexInt()) {
10187 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10188 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10189 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +000010190 }
10191
10192 // This can happen with lossless casts to intptr_t of "based" lvalues.
10193 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +000010194 // FIXME: The only reason we need to pass the type in here is to get
10195 // the sign right on this one case. It would be nice if APValue
10196 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000010197 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +000010198 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +000010199}
John McCall70aa5392010-01-06 05:24:50 +000010200
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010201static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +000010202 QualType Ty = E->getType();
10203 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10204 Ty = AtomicRHS->getValueType();
10205 return Ty;
10206}
10207
John McCall70aa5392010-01-06 05:24:50 +000010208/// Pseudo-evaluate the given integer expression, estimating the
10209/// range of values it might take.
10210///
10211/// \param MaxWidth - the width to which the value will be truncated
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010212static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10213 bool InConstantContext) {
John McCall70aa5392010-01-06 05:24:50 +000010214 E = E->IgnoreParens();
10215
10216 // Try a full evaluation first.
10217 Expr::EvalResult result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010218 if (E->EvaluateAsRValue(result, C, InConstantContext))
Eli Friedmane6d33952013-07-08 20:20:06 +000010219 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +000010220
10221 // I think we only want to look through implicit casts here; if the
10222 // user has an explicit widening cast, we should treat the value as
10223 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010224 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +000010225 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010226 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010227
Eli Friedmane6d33952013-07-08 20:20:06 +000010228 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +000010229
George Burgess IVdf1ed002016-01-13 01:52:39 +000010230 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10231 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +000010232
John McCall70aa5392010-01-06 05:24:50 +000010233 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +000010234 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +000010235 return OutputTypeRange;
10236
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010237 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10238 std::min(MaxWidth, OutputTypeRange.Width),
10239 InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010240
10241 // Bail out if the subexpr's range is as wide as the cast type.
10242 if (SubRange.Width >= OutputTypeRange.Width)
10243 return OutputTypeRange;
10244
10245 // Otherwise, we take the smaller width, and we're non-negative if
10246 // either the output type or the subexpr is.
10247 return IntRange(SubRange.Width,
10248 SubRange.NonNegative || OutputTypeRange.NonNegative);
10249 }
10250
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010251 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010252 // If we can fold the condition, just take that operand.
10253 bool CondResult;
10254 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010255 return GetExprRange(C,
10256 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10257 MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010258
10259 // Otherwise, conservatively merge.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010260 IntRange L =
10261 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10262 IntRange R =
10263 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010264 return IntRange::join(L, R);
10265 }
10266
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010267 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010268 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +000010269 case BO_Cmp:
10270 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +000010271
10272 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +000010273 case BO_LAnd:
10274 case BO_LOr:
10275 case BO_LT:
10276 case BO_GT:
10277 case BO_LE:
10278 case BO_GE:
10279 case BO_EQ:
10280 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +000010281 return IntRange::forBoolType();
10282
John McCallc3688382011-07-13 06:35:24 +000010283 // The type of the assignments is the type of the LHS, so the RHS
10284 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +000010285 case BO_MulAssign:
10286 case BO_DivAssign:
10287 case BO_RemAssign:
10288 case BO_AddAssign:
10289 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +000010290 case BO_XorAssign:
10291 case BO_OrAssign:
10292 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +000010293 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +000010294
John McCallc3688382011-07-13 06:35:24 +000010295 // Simple assignments just pass through the RHS, which will have
10296 // been coerced to the LHS type.
10297 case BO_Assign:
10298 // TODO: bitfields?
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010299 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCallc3688382011-07-13 06:35:24 +000010300
John McCall70aa5392010-01-06 05:24:50 +000010301 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +000010302 case BO_PtrMemD:
10303 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +000010304 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010305
John McCall2ce81ad2010-01-06 22:07:33 +000010306 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +000010307 case BO_And:
10308 case BO_AndAssign:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010309 return IntRange::meet(
10310 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10311 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
John McCall2ce81ad2010-01-06 22:07:33 +000010312
John McCall70aa5392010-01-06 05:24:50 +000010313 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +000010314 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +000010315 // ...except that we want to treat '1 << (blah)' as logically
10316 // positive. It's an important idiom.
10317 if (IntegerLiteral *I
10318 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10319 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +000010320 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +000010321 return IntRange(R.Width, /*NonNegative*/ true);
10322 }
10323 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010324 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +000010325
John McCalle3027922010-08-25 11:45:40 +000010326 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +000010327 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010328
John McCall2ce81ad2010-01-06 22:07:33 +000010329 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +000010330 case BO_Shr:
10331 case BO_ShrAssign: {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010332 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
John McCall2ce81ad2010-01-06 22:07:33 +000010333
10334 // If the shift amount is a positive constant, drop the width by
10335 // that much.
10336 llvm::APSInt shift;
10337 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10338 shift.isNonNegative()) {
10339 unsigned zext = shift.getZExtValue();
10340 if (zext >= L.Width)
10341 L.Width = (L.NonNegative ? 0 : 1);
10342 else
10343 L.Width -= zext;
10344 }
10345
10346 return L;
10347 }
10348
10349 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +000010350 case BO_Comma:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010351 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010352
John McCall2ce81ad2010-01-06 22:07:33 +000010353 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +000010354 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +000010355 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +000010356 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +000010357 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +000010358
John McCall51431812011-07-14 22:39:48 +000010359 // The width of a division result is mostly determined by the size
10360 // of the LHS.
10361 case BO_Div: {
10362 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010363 unsigned opWidth = C.getIntWidth(GetExprType(E));
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010364 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010365
10366 // If the divisor is constant, use that.
10367 llvm::APSInt divisor;
10368 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10369 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10370 if (log2 >= L.Width)
10371 L.Width = (L.NonNegative ? 0 : 1);
10372 else
10373 L.Width = std::min(L.Width - log2, MaxWidth);
10374 return L;
10375 }
10376
10377 // Otherwise, just use the LHS's width.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010378 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010379 return IntRange(L.Width, L.NonNegative && R.NonNegative);
10380 }
10381
10382 // The result of a remainder can't be larger than the result of
10383 // either side.
10384 case BO_Rem: {
10385 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010386 unsigned opWidth = C.getIntWidth(GetExprType(E));
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010387 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10388 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010389
10390 IntRange meet = IntRange::meet(L, R);
10391 meet.Width = std::min(meet.Width, MaxWidth);
10392 return meet;
10393 }
10394
10395 // The default behavior is okay for these.
10396 case BO_Mul:
10397 case BO_Add:
10398 case BO_Xor:
10399 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +000010400 break;
10401 }
10402
John McCall51431812011-07-14 22:39:48 +000010403 // The default case is to treat the operation as if it were closed
10404 // on the narrowest type that encompasses both operands.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010405 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10406 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010407 return IntRange::join(L, R);
10408 }
10409
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010410 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010411 switch (UO->getOpcode()) {
10412 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +000010413 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +000010414 return IntRange::forBoolType();
10415
10416 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +000010417 case UO_Deref:
10418 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +000010419 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010420
10421 default:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010422 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010423 }
10424 }
10425
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010426 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010427 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
Ted Kremeneka553fbf2013-10-14 18:55:27 +000010428
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010429 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +000010430 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +000010431 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +000010432
Eli Friedmane6d33952013-07-08 20:20:06 +000010433 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010434}
John McCall263a48b2010-01-04 23:31:57 +000010435
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010436static IntRange GetExprRange(ASTContext &C, const Expr *E,
10437 bool InConstantContext) {
10438 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010439}
10440
John McCall263a48b2010-01-04 23:31:57 +000010441/// Checks whether the given value, which currently has the given
10442/// source semantics, has the same value when coerced through the
10443/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010444static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10445 const llvm::fltSemantics &Src,
10446 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010447 llvm::APFloat truncated = value;
10448
10449 bool ignored;
10450 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10451 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10452
10453 return truncated.bitwiseIsEqual(value);
10454}
10455
10456/// Checks whether the given value, which currently has the given
10457/// source semantics, has the same value when coerced through the
10458/// target semantics.
10459///
10460/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010461static bool IsSameFloatAfterCast(const APValue &value,
10462 const llvm::fltSemantics &Src,
10463 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010464 if (value.isFloat())
10465 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10466
10467 if (value.isVector()) {
10468 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10469 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10470 return false;
10471 return true;
10472 }
10473
10474 assert(value.isComplexFloat());
10475 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10476 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10477}
10478
Ziang Wan87b668b2019-08-01 00:16:43 +000010479static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10480 bool IsListInit = false);
John McCallcc7e5bf2010-05-06 08:58:33 +000010481
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010482static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +000010483 // Suppress cases where we are comparing against an enum constant.
10484 if (const DeclRefExpr *DR =
10485 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10486 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +000010487 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +000010488
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010489 // Suppress cases where the value is expanded from a macro, unless that macro
10490 // is how a language represents a boolean literal. This is the case in both C
10491 // and Objective-C.
10492 SourceLocation BeginLoc = E->getBeginLoc();
10493 if (BeginLoc.isMacroID()) {
10494 StringRef MacroName = Lexer::getImmediateMacroName(
10495 BeginLoc, S.getSourceManager(), S.getLangOpts());
10496 return MacroName != "YES" && MacroName != "NO" &&
10497 MacroName != "true" && MacroName != "false";
10498 }
Ted Kremenek6274be42010-09-23 21:43:44 +000010499
Roman Lebedev6de129e2017-10-15 20:13:17 +000010500 return false;
10501}
10502
Richard Smith692f66ab2017-12-06 19:23:19 +000010503static bool isKnownToHaveUnsignedValue(Expr *E) {
10504 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +000010505 (!E->getType()->isSignedIntegerType() ||
10506 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10507}
10508
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010509namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +000010510/// The promoted range of values of a type. In general this has the
10511/// following structure:
10512///
10513/// |-----------| . . . |-----------|
10514/// ^ ^ ^ ^
10515/// Min HoleMin HoleMax Max
10516///
10517/// ... where there is only a hole if a signed type is promoted to unsigned
10518/// (in which case Min and Max are the smallest and largest representable
10519/// values).
10520struct PromotedRange {
10521 // Min, or HoleMax if there is a hole.
10522 llvm::APSInt PromotedMin;
10523 // Max, or HoleMin if there is a hole.
10524 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010525
Richard Smitha5370fb2017-12-08 22:57:11 +000010526 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10527 if (R.Width == 0)
10528 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10529 else if (R.Width >= BitWidth && !Unsigned) {
10530 // Promotion made the type *narrower*. This happens when promoting
10531 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10532 // Treat all values of 'signed int' as being in range for now.
10533 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10534 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10535 } else {
10536 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10537 .extOrTrunc(BitWidth);
10538 PromotedMin.setIsUnsigned(Unsigned);
10539
10540 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10541 .extOrTrunc(BitWidth);
10542 PromotedMax.setIsUnsigned(Unsigned);
10543 }
10544 }
10545
10546 // Determine whether this range is contiguous (has no hole).
10547 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10548
10549 // Where a constant value is within the range.
10550 enum ComparisonResult {
10551 LT = 0x1,
10552 LE = 0x2,
10553 GT = 0x4,
10554 GE = 0x8,
10555 EQ = 0x10,
10556 NE = 0x20,
10557 InRangeFlag = 0x40,
10558
10559 Less = LE | LT | NE,
10560 Min = LE | InRangeFlag,
10561 InRange = InRangeFlag,
10562 Max = GE | InRangeFlag,
10563 Greater = GE | GT | NE,
10564
10565 OnlyValue = LE | GE | EQ | InRangeFlag,
10566 InHole = NE
10567 };
10568
10569 ComparisonResult compare(const llvm::APSInt &Value) const {
10570 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10571 Value.isUnsigned() == PromotedMin.isUnsigned());
10572 if (!isContiguous()) {
10573 assert(Value.isUnsigned() && "discontiguous range for signed compare");
10574 if (Value.isMinValue()) return Min;
10575 if (Value.isMaxValue()) return Max;
10576 if (Value >= PromotedMin) return InRange;
10577 if (Value <= PromotedMax) return InRange;
10578 return InHole;
10579 }
10580
10581 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10582 case -1: return Less;
10583 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10584 case 1:
10585 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10586 case -1: return InRange;
10587 case 0: return Max;
10588 case 1: return Greater;
10589 }
10590 }
10591
10592 llvm_unreachable("impossible compare result");
10593 }
10594
Richard Smithc70f1d62017-12-14 15:16:18 +000010595 static llvm::Optional<StringRef>
10596 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10597 if (Op == BO_Cmp) {
10598 ComparisonResult LTFlag = LT, GTFlag = GT;
10599 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10600
10601 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10602 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10603 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10604 return llvm::None;
10605 }
10606
Richard Smitha5370fb2017-12-08 22:57:11 +000010607 ComparisonResult TrueFlag, FalseFlag;
10608 if (Op == BO_EQ) {
10609 TrueFlag = EQ;
10610 FalseFlag = NE;
10611 } else if (Op == BO_NE) {
10612 TrueFlag = NE;
10613 FalseFlag = EQ;
10614 } else {
10615 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10616 TrueFlag = LT;
10617 FalseFlag = GE;
10618 } else {
10619 TrueFlag = GT;
10620 FalseFlag = LE;
10621 }
10622 if (Op == BO_GE || Op == BO_LE)
10623 std::swap(TrueFlag, FalseFlag);
10624 }
10625 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010626 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +000010627 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010628 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +000010629 return llvm::None;
10630 }
Roman Lebedev6de129e2017-10-15 20:13:17 +000010631};
John McCallcc7e5bf2010-05-06 08:58:33 +000010632}
10633
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010634static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +000010635 // Strip off implicit integral promotions.
10636 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010637 if (ICE->getCastKind() != CK_IntegralCast &&
10638 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +000010639 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010640 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +000010641 }
10642
10643 return E->getType()->isEnumeralType();
10644}
10645
Richard Smith692f66ab2017-12-06 19:23:19 +000010646static int classifyConstantValue(Expr *Constant) {
10647 // The values of this enumeration are used in the diagnostics
10648 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10649 enum ConstantValueKind {
10650 Miscellaneous = 0,
10651 LiteralTrue,
10652 LiteralFalse
10653 };
10654 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10655 return BL->getValue() ? ConstantValueKind::LiteralTrue
10656 : ConstantValueKind::LiteralFalse;
10657 return ConstantValueKind::Miscellaneous;
10658}
10659
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010660static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10661 Expr *Constant, Expr *Other,
10662 const llvm::APSInt &Value,
10663 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010664 if (S.inTemplateInstantiation())
10665 return false;
10666
Richard Smitha5370fb2017-12-08 22:57:11 +000010667 Expr *OriginalOther = Other;
10668
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010669 Constant = Constant->IgnoreParenImpCasts();
10670 Other = Other->IgnoreParenImpCasts();
10671
Richard Smitha5370fb2017-12-08 22:57:11 +000010672 // Suppress warnings on tautological comparisons between values of the same
10673 // enumeration type. There are only two ways we could warn on this:
10674 // - If the constant is outside the range of representable values of
10675 // the enumeration. In such a case, we should warn about the cast
10676 // to enumeration type, not about the comparison.
10677 // - If the constant is the maximum / minimum in-range value. For an
10678 // enumeratin type, such comparisons can be meaningful and useful.
10679 if (Constant->getType()->isEnumeralType() &&
10680 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10681 return false;
10682
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010683 // TODO: Investigate using GetExprRange() to get tighter bounds
10684 // on the bit ranges.
10685 QualType OtherT = Other->getType();
10686 if (const auto *AT = OtherT->getAs<AtomicType>())
10687 OtherT = AT->getValueType();
10688 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10689
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010690 // Special case for ObjC BOOL on targets where its a typedef for a signed char
10691 // (Namely, macOS).
10692 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10693 S.NSAPIObj->isObjCBOOLType(OtherT) &&
10694 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10695
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010696 // Whether we're treating Other as being a bool because of the form of
10697 // expression despite it having another type (typically 'int' in C).
10698 bool OtherIsBooleanDespiteType =
10699 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010700 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010701 OtherRange = IntRange::forBoolType();
10702
Richard Smitha5370fb2017-12-08 22:57:11 +000010703 // Determine the promoted range of the other type and see if a comparison of
10704 // the constant against that range is tautological.
10705 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10706 Value.isUnsigned());
10707 auto Cmp = OtherPromotedRange.compare(Value);
10708 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10709 if (!Result)
10710 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010711
Richard Smitha5370fb2017-12-08 22:57:11 +000010712 // Suppress the diagnostic for an in-range comparison if the constant comes
10713 // from a macro or enumerator. We don't want to diagnose
10714 //
10715 // some_long_value <= INT_MAX
10716 //
10717 // when sizeof(int) == sizeof(long).
10718 bool InRange = Cmp & PromotedRange::InRangeFlag;
10719 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10720 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010721
10722 // If this is a comparison to an enum constant, include that
10723 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010724 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010725 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10726 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10727
Richard Smitha5370fb2017-12-08 22:57:11 +000010728 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010729 SmallString<64> PrettySourceValue;
10730 llvm::raw_svector_ostream OS(PrettySourceValue);
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010731 if (ED) {
Ted Kremeneke943ce12013-03-15 22:02:46 +000010732 OS << '\'' << *ED << "' (" << Value << ")";
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010733 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10734 Constant->IgnoreParenImpCasts())) {
10735 OS << (BL->getValue() ? "YES" : "NO");
10736 } else {
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010737 OS << Value;
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010738 }
10739
10740 if (IsObjCSignedCharBool) {
10741 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10742 S.PDiag(diag::warn_tautological_compare_objc_bool)
10743 << OS.str() << *Result);
10744 return true;
10745 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010746
Richard Smitha5370fb2017-12-08 22:57:11 +000010747 // FIXME: We use a somewhat different formatting for the in-range cases and
10748 // cases involving boolean values for historical reasons. We should pick a
10749 // consistent way of presenting these diagnostics.
10750 if (!InRange || Other->isKnownToHaveBooleanValue()) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010751
Richard Smitha5370fb2017-12-08 22:57:11 +000010752 S.DiagRuntimeBehavior(
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010753 E->getOperatorLoc(), E,
10754 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10755 : diag::warn_tautological_bool_compare)
10756 << OS.str() << classifyConstantValue(Constant) << OtherT
10757 << OtherIsBooleanDespiteType << *Result
10758 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Richard Smitha5370fb2017-12-08 22:57:11 +000010759 } else {
10760 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10761 ? (HasEnumType(OriginalOther)
10762 ? diag::warn_unsigned_enum_always_true_comparison
10763 : diag::warn_unsigned_always_true_comparison)
10764 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010765
Richard Smitha5370fb2017-12-08 22:57:11 +000010766 S.Diag(E->getOperatorLoc(), Diag)
10767 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10768 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10769 }
10770
10771 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010772}
10773
John McCallcc7e5bf2010-05-06 08:58:33 +000010774/// Analyze the operands of the given comparison. Implements the
10775/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010776static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010777 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10778 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010779}
John McCall263a48b2010-01-04 23:31:57 +000010780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010781/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010782///
Richard Trieu82402a02011-09-15 21:56:47 +000010783/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010784static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010785 // The type the comparison is being performed in.
10786 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010787
10788 // Only analyze comparison operators where both sides have been converted to
10789 // the same type.
10790 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10791 return AnalyzeImpConvsInComparison(S, E);
10792
10793 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010794 if (E->isValueDependent())
10795 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010796
Roman Lebedev6de129e2017-10-15 20:13:17 +000010797 Expr *LHS = E->getLHS();
10798 Expr *RHS = E->getRHS();
10799
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010800 if (T->isIntegralType(S.Context)) {
10801 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010802 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010803
Roman Lebedev6de129e2017-10-15 20:13:17 +000010804 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10805 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010806
Roman Lebedev6de129e2017-10-15 20:13:17 +000010807 // We don't care about expressions whose result is a constant.
10808 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10809 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010810
Roman Lebedev6de129e2017-10-15 20:13:17 +000010811 // We only care about expressions where just one side is literal
10812 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10813 // Is the constant on the RHS or LHS?
10814 const bool RhsConstant = IsRHSIntegralLiteral;
10815 Expr *Const = RhsConstant ? RHS : LHS;
10816 Expr *Other = RhsConstant ? LHS : RHS;
10817 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10818
10819 // Check whether an integer constant comparison results in a value
10820 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010821 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10822 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010823 }
10824 }
10825
10826 if (!T->hasUnsignedIntegerRepresentation()) {
10827 // We don't do anything special if this isn't an unsigned integral
10828 // comparison: we're only interested in integral comparisons, and
10829 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010830 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010831 }
10832
10833 LHS = LHS->IgnoreParenImpCasts();
10834 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010835
Alex Lorenzb57409f2018-02-07 20:45:39 +000010836 if (!S.getLangOpts().CPlusPlus) {
10837 // Avoid warning about comparison of integers with different signs when
10838 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10839 // the type of `E`.
10840 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10841 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10842 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10843 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10844 }
10845
John McCallcc7e5bf2010-05-06 08:58:33 +000010846 // Check to see if one of the (unmodified) operands is of different
10847 // signedness.
10848 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010849 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10850 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010851 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010852 signedOperand = LHS;
10853 unsignedOperand = RHS;
10854 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10855 signedOperand = RHS;
10856 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010857 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010858 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010859 }
10860
John McCallcc7e5bf2010-05-06 08:58:33 +000010861 // Otherwise, calculate the effective range of the signed operand.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010862 IntRange signedRange =
10863 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
John McCall70aa5392010-01-06 05:24:50 +000010864
John McCallcc7e5bf2010-05-06 08:58:33 +000010865 // Go ahead and analyze implicit conversions in the operands. Note
10866 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010867 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10868 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010869
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010870 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010871 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010872 return;
John McCallca01b222010-01-04 23:21:16 +000010873
10874 // For (in)equality comparisons, if the unsigned operand is a
10875 // constant which cannot collide with a overflowed signed operand,
10876 // then reinterpreting the signed operand as unsigned will not
10877 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010878 if (E->isEqualityOp()) {
10879 unsigned comparisonWidth = S.Context.getIntWidth(T);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010880 IntRange unsignedRange =
10881 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
John McCallca01b222010-01-04 23:21:16 +000010882
John McCallcc7e5bf2010-05-06 08:58:33 +000010883 // We should never be unable to prove that the unsigned operand is
10884 // non-negative.
10885 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10886
10887 if (unsignedRange.Width < comparisonWidth)
10888 return;
10889 }
10890
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010891 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010892 S.PDiag(diag::warn_mixed_sign_comparison)
10893 << LHS->getType() << RHS->getType()
10894 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010895}
10896
John McCall1f425642010-11-11 03:21:53 +000010897/// Analyzes an attempt to assign the given value to a bitfield.
10898///
10899/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010900static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10901 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010902 assert(Bitfield->isBitField());
10903 if (Bitfield->isInvalidDecl())
10904 return false;
10905
John McCalldeebbcf2010-11-11 05:33:51 +000010906 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010907 QualType BitfieldType = Bitfield->getType();
10908 if (BitfieldType->isBooleanType())
10909 return false;
10910
10911 if (BitfieldType->isEnumeralType()) {
Simon Pilgrimdc4d9082019-10-07 14:25:46 +000010912 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
Reid Klecknerad425622016-11-16 23:40:00 +000010913 // If the underlying enum type was not explicitly specified as an unsigned
10914 // type and the enum contain only positive values, MSVC++ will cause an
10915 // inconsistency by storing this as a signed type.
10916 if (S.getLangOpts().CPlusPlus11 &&
10917 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10918 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10919 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10920 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10921 << BitfieldEnumDecl->getNameAsString();
10922 }
10923 }
10924
John McCalldeebbcf2010-11-11 05:33:51 +000010925 if (Bitfield->getType()->isBooleanType())
10926 return false;
10927
Douglas Gregor789adec2011-02-04 13:09:01 +000010928 // Ignore value- or type-dependent expressions.
10929 if (Bitfield->getBitWidth()->isValueDependent() ||
10930 Bitfield->getBitWidth()->isTypeDependent() ||
10931 Init->isValueDependent() ||
10932 Init->isTypeDependent())
10933 return false;
10934
John McCall1f425642010-11-11 03:21:53 +000010935 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010936 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010937
Fangrui Song407659a2018-11-30 23:41:18 +000010938 Expr::EvalResult Result;
10939 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Reid Kleckner329f24d2017-03-14 18:01:02 +000010940 Expr::SE_AllowSideEffects)) {
10941 // The RHS is not constant. If the RHS has an enum type, make sure the
10942 // bitfield is wide enough to hold all the values of the enum without
10943 // truncation.
10944 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10945 EnumDecl *ED = EnumTy->getDecl();
10946 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10947
10948 // Enum types are implicitly signed on Windows, so check if there are any
10949 // negative enumerators to see if the enum was intended to be signed or
10950 // not.
10951 bool SignedEnum = ED->getNumNegativeBits() > 0;
10952
10953 // Check for surprising sign changes when assigning enum values to a
10954 // bitfield of different signedness. If the bitfield is signed and we
10955 // have exactly the right number of bits to store this unsigned enum,
10956 // suggest changing the enum to an unsigned type. This typically happens
10957 // on Windows where unfixed enums always use an underlying type of 'int'.
10958 unsigned DiagID = 0;
10959 if (SignedEnum && !SignedBitfield) {
10960 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10961 } else if (SignedBitfield && !SignedEnum &&
10962 ED->getNumPositiveBits() == FieldWidth) {
10963 DiagID = diag::warn_signed_bitfield_enum_conversion;
10964 }
10965
10966 if (DiagID) {
10967 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10968 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10969 SourceRange TypeRange =
10970 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10971 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10972 << SignedEnum << TypeRange;
10973 }
10974
10975 // Compute the required bitwidth. If the enum has negative values, we need
10976 // one more bit than the normal number of positive bits to represent the
10977 // sign bit.
10978 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10979 ED->getNumNegativeBits())
10980 : ED->getNumPositiveBits();
10981
10982 // Check the bitwidth.
10983 if (BitsNeeded > FieldWidth) {
10984 Expr *WidthExpr = Bitfield->getBitWidth();
10985 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10986 << Bitfield << ED;
10987 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10988 << BitsNeeded << ED << WidthExpr->getSourceRange();
10989 }
10990 }
10991
John McCall1f425642010-11-11 03:21:53 +000010992 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010993 }
John McCall1f425642010-11-11 03:21:53 +000010994
Fangrui Song407659a2018-11-30 23:41:18 +000010995 llvm::APSInt Value = Result.Val.getInt();
10996
John McCall1f425642010-11-11 03:21:53 +000010997 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010998
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010999 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000011000 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000011001 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11002 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000011003
John McCall1f425642010-11-11 03:21:53 +000011004 if (OriginalWidth <= FieldWidth)
11005 return false;
11006
Eli Friedmanc267a322012-01-26 23:11:39 +000011007 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000011008 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000011009 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000011010
Eli Friedmanc267a322012-01-26 23:11:39 +000011011 // Check whether the stored value is equal to the original value.
11012 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000011013 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000011014 return false;
11015
Eli Friedmanc267a322012-01-26 23:11:39 +000011016 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000011017 // therefore don't strictly fit into a signed bitfield of width 1.
11018 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000011019 return false;
11020
John McCall1f425642010-11-11 03:21:53 +000011021 std::string PrettyValue = Value.toString(10);
11022 std::string PrettyTrunc = TruncatedValue.toString(10);
11023
11024 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11025 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11026 << Init->getSourceRange();
11027
11028 return true;
11029}
11030
John McCalld2a53122010-11-09 23:24:47 +000011031/// Analyze the given simple or compound assignment for warning-worthy
11032/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011033static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000011034 // Just recurse on the LHS.
11035 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11036
11037 // We want to recurse on the RHS as normal unless we're assigning to
11038 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000011039 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011040 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000011041 E->getOperatorLoc())) {
11042 // Recurse, ignoring any implicit conversions on the RHS.
11043 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11044 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000011045 }
11046 }
11047
11048 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000011049
JF Bastiene77b48b2018-09-10 20:42:56 +000011050 // Diagnose implicitly sequentially-consistent atomic assignment.
11051 if (E->getLHS()->getType()->isAtomicType())
11052 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000011053}
11054
John McCall263a48b2010-01-04 23:31:57 +000011055/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000011056static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011057 SourceLocation CContext, unsigned diag,
11058 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000011059 if (pruneControlFlow) {
11060 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11061 S.PDiag(diag)
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011062 << SourceType << T << E->getSourceRange()
11063 << SourceRange(CContext));
Anna Zaks314cd092012-02-01 19:08:57 +000011064 return;
11065 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000011066 S.Diag(E->getExprLoc(), diag)
11067 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11068}
11069
Chandler Carruth7f3654f2011-04-05 06:47:57 +000011070/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011071static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11072 SourceLocation CContext,
11073 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000011074 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000011075}
11076
Erik Pilkington5c621522019-09-17 21:11:51 +000011077static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11078 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11079 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11080}
11081
11082static void adornObjCBoolConversionDiagWithTernaryFixit(
11083 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11084 Expr *Ignored = SourceExpr->IgnoreImplicit();
11085 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11086 Ignored = OVE->getSourceExpr();
11087 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11088 isa<BinaryOperator>(Ignored) ||
11089 isa<CXXOperatorCallExpr>(Ignored);
11090 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11091 if (NeedsParens)
11092 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11093 << FixItHint::CreateInsertion(EndLoc, ")");
11094 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11095}
11096
Richard Trieube234c32016-04-21 21:04:55 +000011097/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011098static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11099 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000011100 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000011101 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000011102
11103 Expr *InnerE = E->IgnoreParenImpCasts();
11104 // We also want to warn on, e.g., "int i = -1.234"
11105 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11106 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11107 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11108
11109 const bool IsLiteral =
11110 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11111
11112 llvm::APFloat Value(0.0);
11113 bool IsConstant =
11114 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11115 if (!IsConstant) {
Erik Pilkington5c621522019-09-17 21:11:51 +000011116 if (isObjCSignedCharBool(S, T)) {
11117 return adornObjCBoolConversionDiagWithTernaryFixit(
11118 S, E,
11119 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11120 << E->getType());
11121 }
11122
Richard Trieu891f0f12016-04-22 22:14:32 +000011123 return DiagnoseImpCast(S, E, T, CContext,
11124 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000011125 }
11126
Chandler Carruth016ef402011-04-10 08:36:24 +000011127 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000011128
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000011129 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11130 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000011131 llvm::APFloat::opStatus Result = Value.convertToInteger(
11132 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11133
Erik Pilkington5c621522019-09-17 21:11:51 +000011134 // FIXME: Force the precision of the source value down so we don't print
11135 // digits which are usually useless (we don't really care here if we
11136 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11137 // would automatically print the shortest representation, but it's a bit
11138 // tricky to implement.
11139 SmallString<16> PrettySourceValue;
11140 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11141 precision = (precision * 59 + 195) / 196;
11142 Value.toString(PrettySourceValue, precision);
11143
11144 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11145 return adornObjCBoolConversionDiagWithTernaryFixit(
11146 S, E,
11147 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11148 << PrettySourceValue);
11149 }
11150
Erich Keanea4c48c62018-05-08 21:26:21 +000011151 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000011152 if (IsLiteral) return;
11153 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11154 PruneWarnings);
11155 }
11156
Erich Keanea4c48c62018-05-08 21:26:21 +000011157 // Conversion of a floating-point value to a non-bool integer where the
11158 // integral part cannot be represented by the integer type is undefined.
11159 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11160 return DiagnoseImpCast(
11161 S, E, T, CContext,
11162 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000011163 : diag::warn_impcast_float_to_integer_out_of_range,
11164 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000011165
Richard Trieube234c32016-04-21 21:04:55 +000011166 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000011167 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000011168 // Warn on floating point literal to integer.
11169 DiagID = diag::warn_impcast_literal_float_to_integer;
11170 } else if (IntegerValue == 0) {
11171 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11172 return DiagnoseImpCast(S, E, T, CContext,
11173 diag::warn_impcast_float_integer, PruneWarnings);
11174 }
11175 // Warn on non-zero to zero conversion.
11176 DiagID = diag::warn_impcast_float_to_integer_zero;
11177 } else {
11178 if (IntegerValue.isUnsigned()) {
11179 if (!IntegerValue.isMaxValue()) {
11180 return DiagnoseImpCast(S, E, T, CContext,
11181 diag::warn_impcast_float_integer, PruneWarnings);
11182 }
11183 } else { // IntegerValue.isSigned()
11184 if (!IntegerValue.isMaxSignedValue() &&
11185 !IntegerValue.isMinSignedValue()) {
11186 return DiagnoseImpCast(S, E, T, CContext,
11187 diag::warn_impcast_float_integer, PruneWarnings);
11188 }
11189 }
11190 // Warn on evaluatable floating point expression to integer conversion.
11191 DiagID = diag::warn_impcast_float_to_integer;
11192 }
Chandler Carruth016ef402011-04-10 08:36:24 +000011193
David Blaikie9b88cc02012-05-15 17:18:27 +000011194 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000011195 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000011196 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000011197 else
David Blaikie9b88cc02012-05-15 17:18:27 +000011198 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000011199
Richard Trieube234c32016-04-21 21:04:55 +000011200 if (PruneWarnings) {
11201 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11202 S.PDiag(DiagID)
11203 << E->getType() << T.getUnqualifiedType()
11204 << PrettySourceValue << PrettyTargetValue
11205 << E->getSourceRange() << SourceRange(CContext));
11206 } else {
11207 S.Diag(E->getExprLoc(), DiagID)
11208 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11209 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11210 }
Chandler Carruth016ef402011-04-10 08:36:24 +000011211}
11212
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000011213/// Analyze the given compound assignment for the possible losing of
11214/// floating-point precision.
11215static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11216 assert(isa<CompoundAssignOperator>(E) &&
11217 "Must be compound assignment operation");
11218 // Recurse on the LHS and RHS in here
11219 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11220 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11221
JF Bastiene77b48b2018-09-10 20:42:56 +000011222 if (E->getLHS()->getType()->isAtomicType())
11223 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11224
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000011225 // Now check the outermost expression
11226 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11227 const auto *RBT = cast<CompoundAssignOperator>(E)
11228 ->getComputationResultType()
11229 ->getAs<BuiltinType>();
11230
11231 // The below checks assume source is floating point.
11232 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11233
Erik Pilkingtond5b017d2019-02-14 22:48:01 +000011234 // If source is floating point but target is an integer.
11235 if (ResultBT->isInteger())
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011236 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11237 E->getExprLoc(), diag::warn_impcast_float_integer);
11238
11239 if (!ResultBT->isFloatingPoint())
11240 return;
11241
11242 // If both source and target are floating points, warn about losing precision.
11243 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11244 QualType(ResultBT, 0), QualType(RBT, 0));
11245 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000011246 // warn about dropping FP rank.
11247 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11248 diag::warn_impcast_float_result_precision);
11249}
11250
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011251static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11252 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000011253 if (!Range.Width) return "0";
11254
11255 llvm::APSInt ValueInRange = Value;
11256 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000011257 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000011258 return ValueInRange.toString(10);
11259}
11260
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011261static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011262 if (!isa<ImplicitCastExpr>(Ex))
11263 return false;
11264
11265 Expr *InnerE = Ex->IgnoreParenImpCasts();
11266 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11267 const Type *Source =
11268 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11269 if (Target->isDependentType())
11270 return false;
11271
11272 const BuiltinType *FloatCandidateBT =
11273 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11274 const Type *BoolCandidateType = ToBool ? Target : Source;
11275
11276 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11277 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11278}
11279
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011280static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11281 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011282 unsigned NumArgs = TheCall->getNumArgs();
11283 for (unsigned i = 0; i < NumArgs; ++i) {
11284 Expr *CurrA = TheCall->getArg(i);
11285 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11286 continue;
11287
11288 bool IsSwapped = ((i > 0) &&
11289 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11290 IsSwapped |= ((i < (NumArgs - 1)) &&
11291 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11292 if (IsSwapped) {
11293 // Warn on this floating-point to bool conversion.
11294 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11295 CurrA->getType(), CC,
11296 diag::warn_impcast_floating_point_to_bool);
11297 }
11298 }
11299}
11300
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011301static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11302 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000011303 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11304 E->getExprLoc()))
11305 return;
11306
Richard Trieu09d6b802016-01-08 23:35:06 +000011307 // Don't warn on functions which have return type nullptr_t.
11308 if (isa<CallExpr>(E))
11309 return;
11310
Richard Trieu5b993502014-10-15 03:42:06 +000011311 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11312 const Expr::NullPointerConstantKind NullKind =
11313 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11314 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11315 return;
11316
11317 // Return if target type is a safe conversion.
11318 if (T->isAnyPointerType() || T->isBlockPointerType() ||
11319 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11320 return;
11321
11322 SourceLocation Loc = E->getSourceRange().getBegin();
11323
Richard Trieu0a5e1662016-02-13 00:58:53 +000011324 // Venture through the macro stacks to get to the source of macro arguments.
11325 // The new location is a better location than the complete location that was
11326 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000011327 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11328 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000011329
Richard Trieu5b993502014-10-15 03:42:06 +000011330 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000011331 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11332 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11333 Loc, S.SourceMgr, S.getLangOpts());
11334 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000011335 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000011336 }
11337
11338 // Only warn if the null and context location are in the same macro expansion.
11339 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11340 return;
11341
11342 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011343 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000011344 << FixItHint::CreateReplacement(Loc,
11345 S.getFixItZeroLiteralForType(T, Loc));
11346}
11347
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011348static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11349 ObjCArrayLiteral *ArrayLiteral);
11350
11351static void
11352checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11353 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000011354
11355/// Check a single element within a collection literal against the
11356/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011357static void checkObjCCollectionLiteralElement(Sema &S,
11358 QualType TargetElementType,
11359 Expr *Element,
11360 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011361 // Skip a bitcast to 'id' or qualified 'id'.
11362 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11363 if (ICE->getCastKind() == CK_BitCast &&
11364 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11365 Element = ICE->getSubExpr();
11366 }
11367
11368 QualType ElementType = Element->getType();
11369 ExprResult ElementResult(Element);
11370 if (ElementType->getAs<ObjCObjectPointerType>() &&
11371 S.CheckSingleAssignmentConstraints(TargetElementType,
11372 ElementResult,
11373 false, false)
11374 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011375 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11376 << ElementType << ElementKind << TargetElementType
11377 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000011378 }
11379
11380 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11381 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11382 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11383 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11384}
11385
11386/// Check an Objective-C array literal being converted to the given
11387/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011388static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11389 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011390 if (!S.NSArrayDecl)
11391 return;
11392
11393 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11394 if (!TargetObjCPtr)
11395 return;
11396
11397 if (TargetObjCPtr->isUnspecialized() ||
11398 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11399 != S.NSArrayDecl->getCanonicalDecl())
11400 return;
11401
11402 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11403 if (TypeArgs.size() != 1)
11404 return;
11405
11406 QualType TargetElementType = TypeArgs[0];
11407 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11408 checkObjCCollectionLiteralElement(S, TargetElementType,
11409 ArrayLiteral->getElement(I),
11410 0);
11411 }
11412}
11413
11414/// Check an Objective-C dictionary literal being converted to the given
11415/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011416static void
11417checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11418 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011419 if (!S.NSDictionaryDecl)
11420 return;
11421
11422 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11423 if (!TargetObjCPtr)
11424 return;
11425
11426 if (TargetObjCPtr->isUnspecialized() ||
11427 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11428 != S.NSDictionaryDecl->getCanonicalDecl())
11429 return;
11430
11431 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11432 if (TypeArgs.size() != 2)
11433 return;
11434
11435 QualType TargetKeyType = TypeArgs[0];
11436 QualType TargetObjectType = TypeArgs[1];
11437 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11438 auto Element = DictionaryLiteral->getKeyValueElement(I);
11439 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11440 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11441 }
11442}
11443
Richard Trieufc404c72016-02-05 23:02:38 +000011444// Helper function to filter out cases for constant width constant conversion.
11445// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011446static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11447 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000011448 // If initializing from a constant, and the constant starts with '0',
11449 // then it is a binary, octal, or hexadecimal. Allow these constants
11450 // to fill all the bits, even if there is a sign change.
11451 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11452 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011453 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000011454 if (FirstLiteralCharacter == '0')
11455 return false;
11456 }
11457
11458 // If the CC location points to a '{', and the type is char, then assume
11459 // assume it is an array initialization.
11460 if (CC.isValid() && T->isCharType()) {
11461 const char FirstContextCharacter =
11462 S.getSourceManager().getCharacterData(CC)[0];
11463 if (FirstContextCharacter == '{')
11464 return false;
11465 }
11466
11467 return true;
11468}
11469
David Bolvansky849fd282019-09-24 09:14:33 +000011470static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11471 const auto *IL = dyn_cast<IntegerLiteral>(E);
11472 if (!IL) {
11473 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11474 if (UO->getOpcode() == UO_Minus)
11475 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11476 }
11477 }
11478
11479 return IL;
11480}
11481
David Bolvansky471910d2019-09-30 19:55:50 +000011482static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11483 Expr *LHS, Expr *RHS) {
11484 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11485 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11486
11487 const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11488 if (!LHSEnumType)
11489 return;
11490 const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11491 if (!RHSEnumType)
11492 return;
11493
11494 // Ignore anonymous enums.
11495 if (!LHSEnumType->getDecl()->hasNameForLinkage())
11496 return;
11497 if (!RHSEnumType->getDecl()->hasNameForLinkage())
11498 return;
11499
11500 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11501 return;
11502
11503 S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11504 << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11505 << RHS->getSourceRange();
11506}
11507
David Bolvansky84ea41f2019-09-23 14:21:08 +000011508static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
David Bolvanskyfb218172019-09-22 22:00:48 +000011509 E = E->IgnoreParenImpCasts();
11510 SourceLocation ExprLoc = E->getExprLoc();
11511
David Bolvansky84ea41f2019-09-23 14:21:08 +000011512 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11513 BinaryOperator::Opcode Opc = BO->getOpcode();
David Bolvansky275e4df2019-09-24 13:14:18 +000011514 Expr::EvalResult Result;
David Bolvansky849fd282019-09-24 09:14:33 +000011515 // Do not diagnose unsigned shifts.
David Bolvansky275e4df2019-09-24 13:14:18 +000011516 if (Opc == BO_Shl) {
11517 const auto *LHS = getIntegerLiteral(BO->getLHS());
11518 const auto *RHS = getIntegerLiteral(BO->getRHS());
11519 if (LHS && LHS->getValue() == 0)
11520 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
David Bolvanskye52ed1e2019-09-24 20:10:57 +000011521 else if (!E->isValueDependent() && LHS && RHS &&
11522 RHS->getValue().isNonNegative() &&
David Bolvansky275e4df2019-09-24 13:14:18 +000011523 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11524 S.Diag(ExprLoc, diag::warn_left_shift_always)
11525 << (Result.Val.getInt() != 0);
11526 else if (E->getType()->isSignedIntegerType())
11527 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11528 }
David Bolvansky84ea41f2019-09-23 14:21:08 +000011529 }
11530
David Bolvanskyfb218172019-09-22 22:00:48 +000011531 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
David Bolvansky849fd282019-09-24 09:14:33 +000011532 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
David Bolvansky849fd282019-09-24 09:14:33 +000011533 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
David Bolvansky275e4df2019-09-24 13:14:18 +000011534 if (!LHS || !RHS)
David Bolvansky849fd282019-09-24 09:14:33 +000011535 return;
David Bolvanskyfb218172019-09-22 22:00:48 +000011536 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11537 (RHS->getValue() == 0 || RHS->getValue() == 1))
David Bolvansky849fd282019-09-24 09:14:33 +000011538 // Do not diagnose common idioms.
David Bolvanskyfb218172019-09-22 22:00:48 +000011539 return;
Yuanfang Chen442ddff2019-10-04 21:37:20 +000011540 if (LHS->getValue() != 0 && RHS->getValue() != 0)
David Bolvanskyfb218172019-09-22 22:00:48 +000011541 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11542 }
11543}
11544
Ziang Wan87b668b2019-08-01 00:16:43 +000011545static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11546 SourceLocation CC,
11547 bool *ICContext = nullptr,
11548 bool IsListInit = false) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011549 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000011550
John McCallcc7e5bf2010-05-06 08:58:33 +000011551 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11552 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11553 if (Source == Target) return;
11554 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000011555
Chandler Carruthc22845a2011-07-26 05:40:03 +000011556 // If the conversion context location is invalid don't complain. We also
11557 // don't want to emit a warning if the issue occurs from the expansion of
11558 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11559 // delay this check as long as possible. Once we detect we are in that
11560 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011561 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000011562 return;
11563
JF Bastiene77b48b2018-09-10 20:42:56 +000011564 if (Source->isAtomicType())
11565 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11566
Richard Trieu021baa32011-09-23 20:10:00 +000011567 // Diagnose implicit casts to bool.
11568 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11569 if (isa<StringLiteral>(E))
11570 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000011571 // and expressions, for instance, assert(0 && "error here"), are
11572 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000011573 return DiagnoseImpCast(S, E, T, CC,
11574 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000011575 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11576 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11577 // This covers the literal expressions that evaluate to Objective-C
11578 // objects.
11579 return DiagnoseImpCast(S, E, T, CC,
11580 diag::warn_impcast_objective_c_literal_to_bool);
11581 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011582 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11583 // Warn on pointer to bool conversion that is always true.
11584 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11585 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000011586 }
Richard Trieu021baa32011-09-23 20:10:00 +000011587 }
John McCall263a48b2010-01-04 23:31:57 +000011588
Erik Pilkingtonabffae3a52019-07-09 17:29:40 +000011589 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11590 // is a typedef for signed char (macOS), then that constant value has to be 1
11591 // or 0.
11592 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11593 Expr::EvalResult Result;
11594 if (E->EvaluateAsInt(Result, S.getASTContext(),
Erik Pilkington5c621522019-09-17 21:11:51 +000011595 Expr::SE_AllowSideEffects)) {
11596 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11597 adornObjCBoolConversionDiagWithTernaryFixit(
11598 S, E,
11599 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11600 << Result.Val.getInt().toString(10));
11601 }
Erik Pilkingtonabffae3a52019-07-09 17:29:40 +000011602 return;
11603 }
11604 }
11605
Douglas Gregor5054cb02015-07-07 03:58:22 +000011606 // Check implicit casts from Objective-C collection literals to specialized
11607 // collection types, e.g., NSArray<NSString *> *.
11608 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11609 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11610 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11611 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11612
John McCall263a48b2010-01-04 23:31:57 +000011613 // Strip vector types.
11614 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011615 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011616 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011617 return;
John McCallacf0ee52010-10-08 02:01:28 +000011618 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011619 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011620
Chris Lattneree7286f2011-06-14 04:51:15 +000011621 // If the vector cast is cast between two vectors of the same size, it is
11622 // a bitcast, not a conversion.
11623 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11624 return;
John McCall263a48b2010-01-04 23:31:57 +000011625
11626 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11627 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11628 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000011629 if (auto VecTy = dyn_cast<VectorType>(Target))
11630 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000011631
11632 // Strip complex types.
11633 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011634 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000011635 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011636 return;
11637
Tim Northover02416372017-08-08 23:18:05 +000011638 return DiagnoseImpCast(S, E, T, CC,
11639 S.getLangOpts().CPlusPlus
11640 ? diag::err_impcast_complex_scalar
11641 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011642 }
John McCall263a48b2010-01-04 23:31:57 +000011643
11644 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11645 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11646 }
11647
11648 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11649 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11650
11651 // If the source is floating point...
11652 if (SourceBT && SourceBT->isFloatingPoint()) {
11653 // ...and the target is floating point...
11654 if (TargetBT && TargetBT->isFloatingPoint()) {
11655 // ...then warn if we're dropping FP rank.
11656
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011657 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11658 QualType(SourceBT, 0), QualType(TargetBT, 0));
11659 if (Order > 0) {
John McCall263a48b2010-01-04 23:31:57 +000011660 // Don't warn about float constants that are precisely
11661 // representable in the target type.
11662 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000011663 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000011664 // Value might be a float, a float vector, or a float complex.
11665 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000011666 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11667 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000011668 return;
11669 }
11670
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011671 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011672 return;
11673
John McCallacf0ee52010-10-08 02:01:28 +000011674 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000011675 }
11676 // ... or possibly if we're increasing rank, too
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011677 else if (Order < 0) {
George Burgess IV148e0d32015-10-29 00:28:52 +000011678 if (S.SourceMgr.isInSystemMacro(CC))
11679 return;
11680
11681 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000011682 }
11683 return;
11684 }
11685
Richard Trieube234c32016-04-21 21:04:55 +000011686 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000011687 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011688 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011689 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000011690
Richard Trieube234c32016-04-21 21:04:55 +000011691 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000011692 }
John McCall263a48b2010-01-04 23:31:57 +000011693
Richard Smith54894fd2015-12-30 01:06:52 +000011694 // Detect the case where a call result is converted from floating-point to
11695 // to bool, and the final argument to the call is converted from bool, to
11696 // discover this typo:
11697 //
11698 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11699 //
11700 // FIXME: This is an incredibly special case; is there some more general
11701 // way to detect this class of misplaced-parentheses bug?
11702 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011703 // Check last argument of function call to see if it is an
11704 // implicit cast from a type matching the type the result
11705 // is being cast to.
11706 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000011707 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011708 Expr *LastA = CEx->getArg(NumArgs - 1);
11709 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000011710 if (isa<ImplicitCastExpr>(LastA) &&
11711 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011712 // Warn on this floating-point to bool conversion
11713 DiagnoseImpCast(S, E, T, CC,
11714 diag::warn_impcast_floating_point_to_bool);
11715 }
11716 }
11717 }
John McCall263a48b2010-01-04 23:31:57 +000011718 return;
11719 }
11720
Leonard Chan8f7caae2019-03-06 00:28:43 +000011721 // Valid casts involving fixed point types should be accounted for here.
Leonard Chand3f3e162019-01-18 21:04:25 +000011722 if (Source->isFixedPointType()) {
Leonard Chan8f7caae2019-03-06 00:28:43 +000011723 if (Target->isUnsaturatedFixedPointType()) {
Leonard Chand3f3e162019-01-18 21:04:25 +000011724 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011725 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11726 S.isConstantEvaluated())) {
Leonard Chand3f3e162019-01-18 21:04:25 +000011727 APFixedPoint Value = Result.Val.getFixedPoint();
11728 APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11729 APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11730 if (Value > MaxVal || Value < MinVal) {
11731 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11732 S.PDiag(diag::warn_impcast_fixed_point_range)
11733 << Value.toString() << T
11734 << E->getSourceRange()
11735 << clang::SourceRange(CC));
11736 return;
11737 }
11738 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011739 } else if (Target->isIntegerType()) {
11740 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011741 if (!S.isConstantEvaluated() &&
11742 E->EvaluateAsFixedPoint(Result, S.Context,
Leonard Chan8f7caae2019-03-06 00:28:43 +000011743 Expr::SE_AllowSideEffects)) {
11744 APFixedPoint FXResult = Result.Val.getFixedPoint();
11745
11746 bool Overflowed;
11747 llvm::APSInt IntResult = FXResult.convertToInt(
11748 S.Context.getIntWidth(T),
11749 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11750
11751 if (Overflowed) {
11752 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11753 S.PDiag(diag::warn_impcast_fixed_point_range)
11754 << FXResult.toString() << T
11755 << E->getSourceRange()
11756 << clang::SourceRange(CC));
11757 return;
11758 }
11759 }
11760 }
11761 } else if (Target->isUnsaturatedFixedPointType()) {
11762 if (Source->isIntegerType()) {
11763 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011764 if (!S.isConstantEvaluated() &&
11765 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
Leonard Chan8f7caae2019-03-06 00:28:43 +000011766 llvm::APSInt Value = Result.Val.getInt();
11767
11768 bool Overflowed;
11769 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11770 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11771
11772 if (Overflowed) {
11773 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11774 S.PDiag(diag::warn_impcast_fixed_point_range)
Rui Ueyama49a3ad22019-07-16 04:46:31 +000011775 << Value.toString(/*Radix=*/10) << T
Leonard Chan8f7caae2019-03-06 00:28:43 +000011776 << E->getSourceRange()
11777 << clang::SourceRange(CC));
11778 return;
11779 }
11780 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011781 }
11782 }
11783
Ziang Wan87b668b2019-08-01 00:16:43 +000011784 // If we are casting an integer type to a floating point type without
11785 // initialization-list syntax, we might lose accuracy if the floating
11786 // point type has a narrower significand than the integer type.
11787 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11788 TargetBT->isFloatingType() && !IsListInit) {
11789 // Determine the number of precision bits in the source integer type.
11790 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11791 unsigned int SourcePrecision = SourceRange.Width;
11792
11793 // Determine the number of precision bits in the
11794 // target floating point type.
11795 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11796 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11797
11798 if (SourcePrecision > 0 && TargetPrecision > 0 &&
11799 SourcePrecision > TargetPrecision) {
11800
11801 llvm::APSInt SourceInt;
11802 if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11803 // If the source integer is a constant, convert it to the target
11804 // floating point type. Issue a warning if the value changes
11805 // during the whole conversion.
11806 llvm::APFloat TargetFloatValue(
11807 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11808 llvm::APFloat::opStatus ConversionStatus =
11809 TargetFloatValue.convertFromAPInt(
11810 SourceInt, SourceBT->isSignedInteger(),
11811 llvm::APFloat::rmNearestTiesToEven);
11812
11813 if (ConversionStatus != llvm::APFloat::opOK) {
11814 std::string PrettySourceValue = SourceInt.toString(10);
11815 SmallString<32> PrettyTargetValue;
11816 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11817
11818 S.DiagRuntimeBehavior(
11819 E->getExprLoc(), E,
11820 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11821 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11822 << E->getSourceRange() << clang::SourceRange(CC));
11823 }
11824 } else {
11825 // Otherwise, the implicit conversion may lose precision.
11826 DiagnoseImpCast(S, E, T, CC,
11827 diag::warn_impcast_integer_float_precision);
11828 }
11829 }
11830 }
11831
Richard Trieu5b993502014-10-15 03:42:06 +000011832 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000011833
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011834 S.DiscardMisalignedMemberAddress(Target, E);
11835
David Bolvansky84ea41f2019-09-23 14:21:08 +000011836 if (Target->isBooleanType())
11837 DiagnoseIntInBoolContext(S, E);
11838
David Blaikie9366d2b2012-06-19 21:19:06 +000011839 if (!Source->isIntegerType() || !Target->isIntegerType())
11840 return;
11841
David Blaikie7555b6a2012-05-15 16:56:36 +000011842 // TODO: remove this early return once the false positives for constant->bool
11843 // in templates, macros, etc, are reduced or removed.
11844 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11845 return;
11846
Erik Pilkington5c621522019-09-17 21:11:51 +000011847 if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
Erik Pilkingtond9957c72019-11-20 15:39:22 -080011848 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
Erik Pilkington5c621522019-09-17 21:11:51 +000011849 return adornObjCBoolConversionDiagWithTernaryFixit(
11850 S, E,
11851 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11852 << E->getType());
11853 }
11854
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011855 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
John McCall817d4af2010-11-10 23:38:19 +000011856 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000011857
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011858 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000011859 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011860 // TODO: this should happen for bitfield stores, too.
Fangrui Song407659a2018-11-30 23:41:18 +000011861 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011862 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11863 S.isConstantEvaluated())) {
Fangrui Song407659a2018-11-30 23:41:18 +000011864 llvm::APSInt Value(32);
11865 Value = Result.Val.getInt();
11866
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011867 if (S.SourceMgr.isInSystemMacro(CC))
11868 return;
11869
John McCall18a2c2c2010-11-09 22:22:12 +000011870 std::string PrettySourceValue = Value.toString(10);
11871 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011872
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011873 S.DiagRuntimeBehavior(
11874 E->getExprLoc(), E,
11875 S.PDiag(diag::warn_impcast_integer_precision_constant)
11876 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11877 << E->getSourceRange() << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000011878 return;
11879 }
11880
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011881 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11882 if (S.SourceMgr.isInSystemMacro(CC))
11883 return;
11884
David Blaikie9455da02012-04-12 22:40:54 +000011885 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000011886 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11887 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000011888 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000011889 }
11890
David Bolvanskycf7d2252018-10-02 06:02:30 +000011891 if (TargetRange.Width > SourceRange.Width) {
11892 if (auto *UO = dyn_cast<UnaryOperator>(E))
11893 if (UO->getOpcode() == UO_Minus)
11894 if (Source->isUnsignedIntegerType()) {
11895 if (Target->isUnsignedIntegerType())
11896 return DiagnoseImpCast(S, E, T, CC,
11897 diag::warn_impcast_high_order_zero_bits);
11898 if (Target->isSignedIntegerType())
11899 return DiagnoseImpCast(S, E, T, CC,
11900 diag::warn_impcast_nonnegative_result);
11901 }
11902 }
11903
Richard Trieudcb55572016-01-29 23:51:16 +000011904 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11905 SourceRange.NonNegative && Source->isSignedIntegerType()) {
11906 // Warn when doing a signed to signed conversion, warn if the positive
11907 // source value is exactly the width of the target type, which will
11908 // cause a negative value to be stored.
11909
Fangrui Song407659a2018-11-30 23:41:18 +000011910 Expr::EvalResult Result;
11911 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
Richard Trieufc404c72016-02-05 23:02:38 +000011912 !S.SourceMgr.isInSystemMacro(CC)) {
Fangrui Song407659a2018-11-30 23:41:18 +000011913 llvm::APSInt Value = Result.Val.getInt();
Richard Trieufc404c72016-02-05 23:02:38 +000011914 if (isSameWidthConstantConversion(S, E, T, CC)) {
11915 std::string PrettySourceValue = Value.toString(10);
11916 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000011917
Richard Trieufc404c72016-02-05 23:02:38 +000011918 S.DiagRuntimeBehavior(
11919 E->getExprLoc(), E,
11920 S.PDiag(diag::warn_impcast_integer_precision_constant)
11921 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11922 << E->getSourceRange() << clang::SourceRange(CC));
11923 return;
Richard Trieudcb55572016-01-29 23:51:16 +000011924 }
11925 }
Richard Trieufc404c72016-02-05 23:02:38 +000011926
Richard Trieudcb55572016-01-29 23:51:16 +000011927 // Fall through for non-constants to give a sign conversion warning.
11928 }
11929
John McCallcc7e5bf2010-05-06 08:58:33 +000011930 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11931 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11932 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011933 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011934 return;
11935
John McCallcc7e5bf2010-05-06 08:58:33 +000011936 unsigned DiagID = diag::warn_impcast_integer_sign;
11937
11938 // Traditionally, gcc has warned about this under -Wsign-compare.
11939 // We also want to warn about it in -Wconversion.
11940 // So if -Wconversion is off, use a completely identical diagnostic
11941 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011942 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011943 if (ICContext) {
11944 DiagID = diag::warn_impcast_integer_sign_conditional;
11945 *ICContext = true;
11946 }
11947
John McCallacf0ee52010-10-08 02:01:28 +000011948 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011949 }
11950
Douglas Gregora78f1932011-02-22 02:45:07 +000011951 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011952 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11953 // type, to give us better diagnostics.
11954 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011955 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011956 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11957 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11958 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11959 SourceType = S.Context.getTypeDeclType(Enum);
11960 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11961 }
11962 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011963
Douglas Gregora78f1932011-02-22 02:45:07 +000011964 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11965 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011966 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11967 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011968 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011969 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011970 return;
11971
Fangrui Song6907ce22018-07-30 19:24:48 +000011972 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011973 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011974 }
John McCall263a48b2010-01-04 23:31:57 +000011975}
11976
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011977static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11978 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011979
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011980static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11981 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011982 E = E->IgnoreParenImpCasts();
11983
11984 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011985 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011986
John McCallacf0ee52010-10-08 02:01:28 +000011987 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011988 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011989 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011990}
11991
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011992static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11993 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011994 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011995
11996 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011997 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11998 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
David Bolvansky471910d2019-09-30 19:55:50 +000011999 CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
12000 E->getFalseExpr());
John McCallcc7e5bf2010-05-06 08:58:33 +000012001
David Bolvanskyfb218172019-09-22 22:00:48 +000012002 if (T->isBooleanType())
12003 DiagnoseIntInBoolContext(S, E);
12004
John McCallcc7e5bf2010-05-06 08:58:33 +000012005 // If -Wconversion would have warned about either of the candidates
12006 // for a signedness conversion to the context type...
12007 if (!Suspicious) return;
12008
12009 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012010 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000012011 return;
12012
John McCallcc7e5bf2010-05-06 08:58:33 +000012013 // ...then check whether it would have warned about either of the
12014 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000012015 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012016
Richard Trieubb43dec2011-07-21 02:46:28 +000012017 Suspicious = false;
12018 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
12019 E->getType(), CC, &Suspicious);
12020 if (!Suspicious)
12021 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000012022 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000012023}
12024
JF Bastiene77b48b2018-09-10 20:42:56 +000012025/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000012026/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012027static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000012028 if (S.getLangOpts().Bool)
12029 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000012030 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12031 return;
Richard Trieu65724892014-11-15 06:37:39 +000012032 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12033}
12034
John McCallcc7e5bf2010-05-06 08:58:33 +000012035/// AnalyzeImplicitConversions - Find and report any interesting
12036/// implicit conversions in the given expression. There are a couple
12037/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Ziang Wan87b668b2019-08-01 00:16:43 +000012038static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12039 bool IsListInit/*= false*/) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000012040 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000012041 Expr *E = OrigE->IgnoreParenImpCasts();
12042
Ziang Wan87b668b2019-08-01 00:16:43 +000012043 // Propagate whether we are in a C++ list initialization expression.
12044 // If so, we do not issue warnings for implicit int-float conversion
12045 // precision loss, because C++11 narrowing already handles it.
12046 IsListInit =
12047 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12048
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000012049 if (E->isTypeDependent() || E->isValueDependent())
12050 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000012051
David Bolvanskyaaea76b2019-10-07 21:57:03 +000012052 if (const auto *UO = dyn_cast<UnaryOperator>(E))
12053 if (UO->getOpcode() == UO_Not &&
12054 UO->getSubExpr()->isKnownToHaveBooleanValue())
12055 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12056 << OrigE->getSourceRange() << T->isBooleanType()
12057 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12058
John McCallcc7e5bf2010-05-06 08:58:33 +000012059 // For conditional operators, we analyze the arguments as if they
12060 // were being fed directly into the output.
12061 if (isa<ConditionalOperator>(E)) {
12062 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000012063 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000012064 return;
12065 }
12066
Hans Wennborgf4ad2322012-08-28 15:44:30 +000012067 // Check implicit argument conversions for function calls.
12068 if (CallExpr *Call = dyn_cast<CallExpr>(E))
12069 CheckImplicitArgumentConversions(S, Call, CC);
12070
John McCallcc7e5bf2010-05-06 08:58:33 +000012071 // Go ahead and check any implicit conversions we might have skipped.
12072 // The non-canonical typecheck is just an optimization;
12073 // CheckImplicitConversion will filter out dead implicit conversions.
12074 if (E->getType() != T)
Ziang Wan87b668b2019-08-01 00:16:43 +000012075 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
John McCallcc7e5bf2010-05-06 08:58:33 +000012076
12077 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000012078
12079 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12080 // The bound subexpressions in a PseudoObjectExpr are not reachable
12081 // as transitive children.
12082 // FIXME: Use a more uniform representation for this.
12083 for (auto *SE : POE->semantics())
12084 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
Ziang Wan87b668b2019-08-01 00:16:43 +000012085 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000012086 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000012087
John McCallcc7e5bf2010-05-06 08:58:33 +000012088 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000012089 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12090 E = CE->getSubExpr()->IgnoreParenImpCasts();
12091 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12092 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
Ziang Wan87b668b2019-08-01 00:16:43 +000012093 return AnalyzeImplicitConversions(S, E, CC, IsListInit);
John McCallcc7e5bf2010-05-06 08:58:33 +000012094 }
12095
John McCalld2a53122010-11-09 23:24:47 +000012096 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12097 // Do a somewhat different check with comparison operators.
12098 if (BO->isComparisonOp())
12099 return AnalyzeComparison(S, BO);
12100
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000012101 // And with simple assignments.
12102 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000012103 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000012104 // And with compound assignments.
12105 if (BO->isAssignmentOp())
12106 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000012107 }
John McCallcc7e5bf2010-05-06 08:58:33 +000012108
12109 // These break the otherwise-useful invariant below. Fortunately,
12110 // we don't really need to recurse into them, because any internal
12111 // expressions should have been analyzed already when they were
12112 // built into statements.
12113 if (isa<StmtExpr>(E)) return;
12114
12115 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000012116 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000012117
12118 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000012119 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000012120 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000012121 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000012122 for (Stmt *SubStmt : E->children()) {
12123 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000012124 if (!ChildExpr)
12125 continue;
12126
Richard Trieu955231d2014-01-25 01:10:35 +000012127 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000012128 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000012129 // Ignore checking string literals that are in logical and operators.
12130 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000012131 continue;
Ziang Wan87b668b2019-08-01 00:16:43 +000012132 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
Richard Trieu021baa32011-09-23 20:10:00 +000012133 }
Richard Trieu791b86e2014-11-19 06:08:18 +000012134
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000012135 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000012136 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12137 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000012138 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000012139
12140 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12141 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000012142 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000012143 }
Richard Trieu791b86e2014-11-19 06:08:18 +000012144
JF Bastiene77b48b2018-09-10 20:42:56 +000012145 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12146 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000012147 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000012148 } else if (U->getOpcode() != UO_AddrOf) {
12149 if (U->getSubExpr()->getType()->isAtomicType())
12150 S.Diag(U->getSubExpr()->getBeginLoc(),
12151 diag::warn_atomic_implicit_seq_cst);
12152 }
12153 }
John McCallcc7e5bf2010-05-06 08:58:33 +000012154}
12155
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012156/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000012157static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12158 // Taking into account implicit conversions,
12159 // allow any integer.
12160 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012161 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000012162 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12163 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012164 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000012165 // Potentially emit standard warnings for implicit conversions if enabled
12166 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012167 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000012168 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012169}
12170
Richard Trieuc1888e02014-06-28 23:25:37 +000012171// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12172// Returns true when emitting a warning about taking the address of a reference.
12173static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000012174 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000012175 E = E->IgnoreParenImpCasts();
12176
12177 const FunctionDecl *FD = nullptr;
12178
12179 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12180 if (!DRE->getDecl()->getType()->isReferenceType())
12181 return false;
12182 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12183 if (!M->getMemberDecl()->getType()->isReferenceType())
12184 return false;
12185 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000012186 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000012187 return false;
12188 FD = Call->getDirectCallee();
12189 } else {
12190 return false;
12191 }
12192
12193 SemaRef.Diag(E->getExprLoc(), PD);
12194
12195 // If possible, point to location of function.
12196 if (FD) {
12197 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12198 }
12199
12200 return true;
12201}
12202
Richard Trieu4cbff5c2014-08-08 22:41:43 +000012203// Returns true if the SourceLocation is expanded from any macro body.
12204// Returns false if the SourceLocation is invalid, is from not in a macro
12205// expansion, or is from expanded from a top-level macro argument.
12206static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12207 if (Loc.isInvalid())
12208 return false;
12209
12210 while (Loc.isMacroID()) {
12211 if (SM.isMacroBodyExpansion(Loc))
12212 return true;
12213 Loc = SM.getImmediateMacroCallerLoc(Loc);
12214 }
12215
12216 return false;
12217}
12218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012219/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000012220/// \param E the expression containing the pointer
12221/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12222/// compared to a null pointer
12223/// \param IsEqual True when the comparison is equal to a null pointer
12224/// \param Range Extra SourceRange to highlight in the diagnostic
12225void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12226 Expr::NullPointerConstantKind NullKind,
12227 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000012228 if (!E)
12229 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000012230
12231 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000012232 if (E->getExprLoc().isMacroID()) {
12233 const SourceManager &SM = getSourceManager();
12234 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12235 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000012236 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000012237 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000012238 E = E->IgnoreImpCasts();
12239
12240 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12241
Richard Trieuf7432752014-06-06 21:39:26 +000012242 if (isa<CXXThisExpr>(E)) {
12243 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12244 : diag::warn_this_bool_conversion;
12245 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12246 return;
12247 }
12248
Richard Trieu3bb8b562014-02-26 02:36:06 +000012249 bool IsAddressOf = false;
12250
12251 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12252 if (UO->getOpcode() != UO_AddrOf)
12253 return;
12254 IsAddressOf = true;
12255 E = UO->getSubExpr();
12256 }
12257
Richard Trieuc1888e02014-06-28 23:25:37 +000012258 if (IsAddressOf) {
12259 unsigned DiagID = IsCompare
12260 ? diag::warn_address_of_reference_null_compare
12261 : diag::warn_address_of_reference_bool_conversion;
12262 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12263 << IsEqual;
12264 if (CheckForReference(*this, E, PD)) {
12265 return;
12266 }
12267 }
12268
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012269 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12270 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000012271 std::string Str;
12272 llvm::raw_string_ostream S(Str);
12273 E->printPretty(S, nullptr, getPrintingPolicy());
12274 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12275 : diag::warn_cast_nonnull_to_bool;
12276 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12277 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012278 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000012279 };
12280
12281 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12282 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12283 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012284 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12285 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000012286 return;
12287 }
12288 }
12289 }
12290
Richard Trieu3bb8b562014-02-26 02:36:06 +000012291 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000012292 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000012293 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12294 D = R->getDecl();
12295 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12296 D = M->getMemberDecl();
12297 }
12298
12299 // Weak Decls can be null.
12300 if (!D || D->isWeak())
12301 return;
George Burgess IV850269a2015-12-08 22:02:00 +000012302
Fariborz Jahanianef202d92014-11-18 21:57:54 +000012303 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000012304 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12305 if (getCurFunction() &&
12306 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012307 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12308 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000012309 return;
12310 }
12311
12312 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
Michael Liaoce389922019-03-29 03:55:52 +000012313 // Skip function template not specialized yet.
12314 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12315 return;
David Majnemera3debed2016-06-24 05:33:44 +000012316 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000012317 assert(ParamIter != FD->param_end());
12318 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12319
Fariborz Jahanianef202d92014-11-18 21:57:54 +000012320 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12321 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012322 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000012323 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000012324 }
George Burgess IV850269a2015-12-08 22:02:00 +000012325
Joel E. Denny81508102018-03-13 14:51:22 +000012326 for (const ParamIdx &ArgNo : NonNull->args()) {
12327 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000012328 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000012329 return;
12330 }
George Burgess IV850269a2015-12-08 22:02:00 +000012331 }
12332 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000012333 }
12334 }
George Burgess IV850269a2015-12-08 22:02:00 +000012335 }
12336
Richard Trieu3bb8b562014-02-26 02:36:06 +000012337 QualType T = D->getType();
12338 const bool IsArray = T->isArrayType();
12339 const bool IsFunction = T->isFunctionType();
12340
Richard Trieuc1888e02014-06-28 23:25:37 +000012341 // Address of function is used to silence the function warning.
12342 if (IsAddressOf && IsFunction) {
12343 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000012344 }
12345
12346 // Found nothing.
12347 if (!IsAddressOf && !IsFunction && !IsArray)
12348 return;
12349
12350 // Pretty print the expression for the diagnostic.
12351 std::string Str;
12352 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000012353 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000012354
12355 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12356 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000012357 enum {
12358 AddressOf,
12359 FunctionPointer,
12360 ArrayPointer
12361 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000012362 if (IsAddressOf)
12363 DiagType = AddressOf;
12364 else if (IsFunction)
12365 DiagType = FunctionPointer;
12366 else if (IsArray)
12367 DiagType = ArrayPointer;
12368 else
12369 llvm_unreachable("Could not determine diagnostic.");
12370 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12371 << Range << IsEqual;
12372
12373 if (!IsFunction)
12374 return;
12375
12376 // Suggest '&' to silence the function warning.
12377 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012378 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000012379
12380 // Check to see if '()' fixit should be emitted.
12381 QualType ReturnType;
12382 UnresolvedSet<4> NonTemplateOverloads;
12383 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12384 if (ReturnType.isNull())
12385 return;
12386
12387 if (IsCompare) {
12388 // There are two cases here. If there is null constant, the only suggest
12389 // for a pointer return type. If the null is 0, then suggest if the return
12390 // type is a pointer or an integer type.
12391 if (!ReturnType->isPointerType()) {
12392 if (NullKind == Expr::NPCK_ZeroExpression ||
12393 NullKind == Expr::NPCK_ZeroLiteral) {
12394 if (!ReturnType->isIntegerType())
12395 return;
12396 } else {
12397 return;
12398 }
12399 }
12400 } else { // !IsCompare
12401 // For function to bool, only suggest if the function pointer has bool
12402 // return type.
12403 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12404 return;
12405 }
12406 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000012407 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000012408}
12409
John McCallcc7e5bf2010-05-06 08:58:33 +000012410/// Diagnoses "dangerous" implicit conversions within the given
12411/// expression (which is a full expression). Implements -Wconversion
12412/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000012413///
12414/// \param CC the "context" location of the implicit conversion, i.e.
12415/// the most location of the syntactic entity requiring the implicit
12416/// conversion
12417void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000012418 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000012419 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000012420 return;
12421
12422 // Don't diagnose for value- or type-dependent expressions.
12423 if (E->isTypeDependent() || E->isValueDependent())
12424 return;
12425
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012426 // Check for array bounds violations in cases where the check isn't triggered
12427 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12428 // ArraySubscriptExpr is on the RHS of a variable initialization.
12429 CheckArrayAccess(E);
12430
John McCallacf0ee52010-10-08 02:01:28 +000012431 // This is not the right CC for (e.g.) a variable initialization.
12432 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000012433}
12434
Richard Trieu65724892014-11-15 06:37:39 +000012435/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12436/// Input argument E is a logical expression.
12437void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12438 ::CheckBoolLikeConversion(*this, E, CC);
12439}
12440
Richard Smith9f7df0c2017-06-26 23:19:32 +000012441/// Diagnose when expression is an integer constant expression and its evaluation
12442/// results in integer overflow
12443void Sema::CheckForIntOverflow (Expr *E) {
12444 // Use a work list to deal with nested struct initializers.
12445 SmallVector<Expr *, 2> Exprs(1, E);
12446
12447 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012448 Expr *OriginalE = Exprs.pop_back_val();
12449 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000012450
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012451 if (isa<BinaryOperator>(E)) {
12452 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000012453 continue;
12454 }
12455
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012456 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000012457 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012458 else if (isa<ObjCBoxedExpr>(OriginalE))
12459 E->EvaluateForOverflow(Context);
12460 else if (auto Call = dyn_cast<CallExpr>(E))
12461 Exprs.append(Call->arg_begin(), Call->arg_end());
12462 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12463 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000012464 } while (!Exprs.empty());
12465}
12466
Richard Smithc406cb72013-01-17 01:17:56 +000012467namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012468
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012469/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000012470/// same object.
12471class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012472 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000012473
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012474 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000012475 /// unsequenced if one is an ancestor or a descendent of the other. When we
12476 /// finish processing an expression with sequencing, such as a comma
12477 /// expression, we fold its tree nodes into its parent, since they are
12478 /// unsequenced with respect to nodes we will visit later.
12479 class SequenceTree {
12480 struct Value {
12481 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12482 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000012483 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000012484 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012485 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000012486
12487 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012488 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000012489 /// to some other region.
12490 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000012491 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012492
Serge Gueltonbe885392019-01-20 21:19:56 +000012493 unsigned Index;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012494
12495 explicit Seq(unsigned N) : Index(N) {}
12496
Richard Smithc406cb72013-01-17 01:17:56 +000012497 public:
Serge Gueltonbe885392019-01-20 21:19:56 +000012498 Seq() : Index(0) {}
Richard Smithc406cb72013-01-17 01:17:56 +000012499 };
12500
12501 SequenceTree() { Values.push_back(Value(0)); }
12502 Seq root() const { return Seq(0); }
12503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012504 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000012505 /// subset of \p Parent. This sequence of operations is sequenced with
12506 /// respect to other children of \p Parent.
12507 Seq allocate(Seq Parent) {
12508 Values.push_back(Value(Parent.Index));
12509 return Seq(Values.size() - 1);
12510 }
12511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012512 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000012513 void merge(Seq S) {
12514 Values[S.Index].Merged = true;
12515 }
12516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012517 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000012518 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12519 /// should have been merged into its parent as appropriate.
12520 bool isUnsequenced(Seq Cur, Seq Old) {
12521 unsigned C = representative(Cur.Index);
12522 unsigned Target = representative(Old.Index);
12523 while (C >= Target) {
12524 if (C == Target)
12525 return true;
12526 C = Values[C].Parent;
12527 }
12528 return false;
12529 }
12530
12531 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012532 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000012533 unsigned representative(unsigned K) {
12534 if (Values[K].Merged)
12535 // Perform path compression as we go.
12536 return Values[K].Parent = representative(Values[K].Parent);
12537 return K;
12538 }
12539 };
12540
12541 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012542 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000012543
12544 /// Different flavors of object usage which we track. We only track the
12545 /// least-sequenced usage of each kind.
12546 enum UsageKind {
12547 /// A read of an object. Multiple unsequenced reads are OK.
12548 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012549
Richard Smithc406cb72013-01-17 01:17:56 +000012550 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000012551 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000012552 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012553
Richard Smithc406cb72013-01-17 01:17:56 +000012554 /// A modification of an object which is not sequenced before the value
12555 /// computation of the expression, such as n++.
12556 UK_ModAsSideEffect,
12557
12558 UK_Count = UK_ModAsSideEffect + 1
12559 };
12560
12561 struct Usage {
Serge Gueltonc1904042019-01-20 23:43:37 +000012562 Expr *Use;
Richard Smithc406cb72013-01-17 01:17:56 +000012563 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012564
Serge Gueltonc1904042019-01-20 23:43:37 +000012565 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000012566 };
12567
12568 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000012569 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012570
Richard Smithc406cb72013-01-17 01:17:56 +000012571 /// Have we issued a diagnostic for this variable already?
Serge Gueltonc1904042019-01-20 23:43:37 +000012572 bool Diagnosed;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012573
Serge Gueltonc1904042019-01-20 23:43:37 +000012574 UsageInfo() : Uses(), Diagnosed(false) {}
Richard Smithc406cb72013-01-17 01:17:56 +000012575 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012576 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000012577
12578 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012579
Richard Smithc406cb72013-01-17 01:17:56 +000012580 /// Sequenced regions within the expression.
12581 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012582
Richard Smithc406cb72013-01-17 01:17:56 +000012583 /// Declaration modifications and references which we have seen.
12584 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012585
Richard Smithc406cb72013-01-17 01:17:56 +000012586 /// The region we are currently within.
12587 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012588
Richard Smithc406cb72013-01-17 01:17:56 +000012589 /// Filled in with declarations which were modified as a side-effect
12590 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012591 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12592
Richard Smithd33f5202013-01-17 23:18:09 +000012593 /// Expressions to check later. We defer checking these to reduce
12594 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012595 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000012596
12597 /// RAII object wrapping the visitation of a sequenced subexpression of an
12598 /// expression. At the end of this process, the side-effects of the evaluation
12599 /// become sequenced with respect to the value computation of the result, so
12600 /// we downgrade any UK_ModAsSideEffect within the evaluation to
12601 /// UK_ModAsValue.
12602 struct SequencedSubexpression {
12603 SequencedSubexpression(SequenceChecker &Self)
12604 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12605 Self.ModAsSideEffect = &ModAsSideEffect;
12606 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012607
Richard Smithc406cb72013-01-17 01:17:56 +000012608 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000012609 for (auto &M : llvm::reverse(ModAsSideEffect)) {
12610 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000012611 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000012612 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12613 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000012614 }
12615 Self.ModAsSideEffect = OldModAsSideEffect;
12616 }
12617
12618 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012619 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012620 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000012621 };
12622
Richard Smith40238f02013-06-20 22:21:56 +000012623 /// RAII object wrapping the visitation of a subexpression which we might
12624 /// choose to evaluate as a constant. If any subexpression is evaluated and
12625 /// found to be non-constant, this allows us to suppress the evaluation of
12626 /// the outer expression.
12627 class EvaluationTracker {
12628 public:
12629 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012630 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000012631 Self.EvalTracker = this;
12632 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012633
Richard Smith40238f02013-06-20 22:21:56 +000012634 ~EvaluationTracker() {
12635 Self.EvalTracker = Prev;
12636 if (Prev)
12637 Prev->EvalOK &= EvalOK;
12638 }
12639
12640 bool evaluate(const Expr *E, bool &Result) {
12641 if (!EvalOK || E->isValueDependent())
12642 return false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012643 EvalOK = E->EvaluateAsBooleanCondition(
12644 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
Richard Smith40238f02013-06-20 22:21:56 +000012645 return EvalOK;
12646 }
12647
12648 private:
12649 SequenceChecker &Self;
12650 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012651 bool EvalOK = true;
12652 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000012653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012654 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000012655 /// if any.
12656 Object getObject(Expr *E, bool Mod) const {
12657 E = E->IgnoreParenCasts();
12658 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12659 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12660 return getObject(UO->getSubExpr(), Mod);
12661 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12662 if (BO->getOpcode() == BO_Comma)
12663 return getObject(BO->getRHS(), Mod);
12664 if (Mod && BO->isAssignmentOp())
12665 return getObject(BO->getLHS(), Mod);
12666 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12667 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12668 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12669 return ME->getMemberDecl();
12670 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12671 // FIXME: If this is a reference, map through to its value.
12672 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000012673 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000012674 }
12675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012676 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000012677 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12678 Usage &U = UI.Uses[UK];
12679 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12680 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12681 ModAsSideEffect->push_back(std::make_pair(O, U));
12682 U.Use = Ref;
12683 U.Seq = Region;
12684 }
12685 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012687 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000012688 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12689 bool IsModMod) {
12690 if (UI.Diagnosed)
12691 return;
12692
12693 const Usage &U = UI.Uses[OtherKind];
12694 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12695 return;
12696
12697 Expr *Mod = U.Use;
12698 Expr *ModOrUse = Ref;
12699 if (OtherKind == UK_Use)
12700 std::swap(Mod, ModOrUse);
12701
Richard Smith7d02ca42019-05-06 04:14:01 +000012702 SemaRef.DiagRuntimeBehavior(
12703 Mod->getExprLoc(), {Mod, ModOrUse},
12704 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12705 : diag::warn_unsequenced_mod_use)
12706 << O << SourceRange(ModOrUse->getExprLoc()));
Richard Smithc406cb72013-01-17 01:17:56 +000012707 UI.Diagnosed = true;
12708 }
12709
12710 void notePreUse(Object O, Expr *Use) {
12711 UsageInfo &U = UsageMap[O];
12712 // Uses conflict with other modifications.
12713 checkUsage(O, U, Use, UK_ModAsValue, false);
12714 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012715
Richard Smithc406cb72013-01-17 01:17:56 +000012716 void notePostUse(Object O, Expr *Use) {
12717 UsageInfo &U = UsageMap[O];
12718 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12719 addUsage(U, O, Use, UK_Use);
12720 }
12721
12722 void notePreMod(Object O, Expr *Mod) {
12723 UsageInfo &U = UsageMap[O];
12724 // Modifications conflict with other modifications and with uses.
12725 checkUsage(O, U, Mod, UK_ModAsValue, true);
12726 checkUsage(O, U, Mod, UK_Use, false);
12727 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012728
Richard Smithc406cb72013-01-17 01:17:56 +000012729 void notePostMod(Object O, Expr *Use, UsageKind UK) {
12730 UsageInfo &U = UsageMap[O];
12731 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12732 addUsage(U, O, Use, UK);
12733 }
12734
12735public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012736 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012737 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000012738 Visit(E);
12739 }
12740
12741 void VisitStmt(Stmt *S) {
12742 // Skip all statements which aren't expressions for now.
12743 }
12744
12745 void VisitExpr(Expr *E) {
12746 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000012747 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000012748 }
12749
12750 void VisitCastExpr(CastExpr *E) {
12751 Object O = Object();
12752 if (E->getCastKind() == CK_LValueToRValue)
12753 O = getObject(E->getSubExpr(), false);
12754
12755 if (O)
12756 notePreUse(O, E);
12757 VisitExpr(E);
12758 if (O)
12759 notePostUse(O, E);
12760 }
12761
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012762 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12763 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12764 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12765 SequenceTree::Seq OldRegion = Region;
12766
12767 {
12768 SequencedSubexpression SeqBefore(*this);
12769 Region = BeforeRegion;
12770 Visit(SequencedBefore);
12771 }
12772
12773 Region = AfterRegion;
12774 Visit(SequencedAfter);
12775
12776 Region = OldRegion;
12777
12778 Tree.merge(BeforeRegion);
12779 Tree.merge(AfterRegion);
12780 }
12781
12782 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12783 // C++17 [expr.sub]p1:
12784 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12785 // expression E1 is sequenced before the expression E2.
12786 if (SemaRef.getLangOpts().CPlusPlus17)
12787 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12788 else
12789 Base::VisitStmt(ASE);
12790 }
12791
Richard Smithc406cb72013-01-17 01:17:56 +000012792 void VisitBinComma(BinaryOperator *BO) {
12793 // C++11 [expr.comma]p1:
12794 // Every value computation and side effect associated with the left
12795 // expression is sequenced before every value computation and side
12796 // effect associated with the right expression.
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012797 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
Richard Smithc406cb72013-01-17 01:17:56 +000012798 }
12799
12800 void VisitBinAssign(BinaryOperator *BO) {
12801 // The modification is sequenced after the value computation of the LHS
12802 // and RHS, so check it before inspecting the operands and update the
12803 // map afterwards.
12804 Object O = getObject(BO->getLHS(), true);
12805 if (!O)
12806 return VisitExpr(BO);
12807
12808 notePreMod(O, BO);
12809
12810 // C++11 [expr.ass]p7:
12811 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12812 // only once.
12813 //
12814 // Therefore, for a compound assignment operator, O is considered used
12815 // everywhere except within the evaluation of E1 itself.
12816 if (isa<CompoundAssignOperator>(BO))
12817 notePreUse(O, BO);
12818
12819 Visit(BO->getLHS());
12820
12821 if (isa<CompoundAssignOperator>(BO))
12822 notePostUse(O, BO);
12823
12824 Visit(BO->getRHS());
12825
Richard Smith83e37bee2013-06-26 23:16:51 +000012826 // C++11 [expr.ass]p1:
12827 // the assignment is sequenced [...] before the value computation of the
12828 // assignment expression.
12829 // C11 6.5.16/3 has no such rule.
12830 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12831 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012832 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012833
Richard Smithc406cb72013-01-17 01:17:56 +000012834 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12835 VisitBinAssign(CAO);
12836 }
12837
12838 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12839 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12840 void VisitUnaryPreIncDec(UnaryOperator *UO) {
12841 Object O = getObject(UO->getSubExpr(), true);
12842 if (!O)
12843 return VisitExpr(UO);
12844
12845 notePreMod(O, UO);
12846 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000012847 // C++11 [expr.pre.incr]p1:
12848 // the expression ++x is equivalent to x+=1
12849 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12850 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012851 }
12852
12853 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12854 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12855 void VisitUnaryPostIncDec(UnaryOperator *UO) {
12856 Object O = getObject(UO->getSubExpr(), true);
12857 if (!O)
12858 return VisitExpr(UO);
12859
12860 notePreMod(O, UO);
12861 Visit(UO->getSubExpr());
12862 notePostMod(O, UO, UK_ModAsSideEffect);
12863 }
12864
12865 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12866 void VisitBinLOr(BinaryOperator *BO) {
12867 // The side-effects of the LHS of an '&&' are sequenced before the
12868 // value computation of the RHS, and hence before the value computation
12869 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12870 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000012871 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012872 {
12873 SequencedSubexpression Sequenced(*this);
12874 Visit(BO->getLHS());
12875 }
12876
12877 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012878 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012879 if (!Result)
12880 Visit(BO->getRHS());
12881 } else {
12882 // Check for unsequenced operations in the RHS, treating it as an
12883 // entirely separate evaluation.
12884 //
12885 // FIXME: If there are operations in the RHS which are unsequenced
12886 // with respect to operations outside the RHS, and those operations
12887 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000012888 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012889 }
Richard Smithc406cb72013-01-17 01:17:56 +000012890 }
12891 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000012892 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012893 {
12894 SequencedSubexpression Sequenced(*this);
12895 Visit(BO->getLHS());
12896 }
12897
12898 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012899 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012900 if (Result)
12901 Visit(BO->getRHS());
12902 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000012903 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012904 }
Richard Smithc406cb72013-01-17 01:17:56 +000012905 }
12906
12907 // Only visit the condition, unless we can be sure which subexpression will
12908 // be chosen.
12909 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000012910 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000012911 {
12912 SequencedSubexpression Sequenced(*this);
12913 Visit(CO->getCond());
12914 }
Richard Smithc406cb72013-01-17 01:17:56 +000012915
12916 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012917 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000012918 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012919 else {
Richard Smithd33f5202013-01-17 23:18:09 +000012920 WorkList.push_back(CO->getTrueExpr());
12921 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012922 }
Richard Smithc406cb72013-01-17 01:17:56 +000012923 }
12924
Richard Smithe3dbfe02013-06-30 10:40:20 +000012925 void VisitCallExpr(CallExpr *CE) {
12926 // C++11 [intro.execution]p15:
12927 // When calling a function [...], every value computation and side effect
12928 // associated with any argument expression, or with the postfix expression
12929 // designating the called function, is sequenced before execution of every
12930 // expression or statement in the body of the function [and thus before
12931 // the value computation of its result].
12932 SequencedSubexpression Sequenced(*this);
12933 Base::VisitCallExpr(CE);
12934
12935 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12936 }
12937
Richard Smithc406cb72013-01-17 01:17:56 +000012938 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000012939 // This is a call, so all subexpressions are sequenced before the result.
12940 SequencedSubexpression Sequenced(*this);
12941
Richard Smithc406cb72013-01-17 01:17:56 +000012942 if (!CCE->isListInitialization())
12943 return VisitExpr(CCE);
12944
12945 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012946 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012947 SequenceTree::Seq Parent = Region;
12948 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12949 E = CCE->arg_end();
12950 I != E; ++I) {
12951 Region = Tree.allocate(Parent);
12952 Elts.push_back(Region);
12953 Visit(*I);
12954 }
12955
12956 // Forget that the initializers are sequenced.
12957 Region = Parent;
12958 for (unsigned I = 0; I < Elts.size(); ++I)
12959 Tree.merge(Elts[I]);
12960 }
12961
12962 void VisitInitListExpr(InitListExpr *ILE) {
12963 if (!SemaRef.getLangOpts().CPlusPlus11)
12964 return VisitExpr(ILE);
12965
12966 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012967 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012968 SequenceTree::Seq Parent = Region;
12969 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12970 Expr *E = ILE->getInit(I);
12971 if (!E) continue;
12972 Region = Tree.allocate(Parent);
12973 Elts.push_back(Region);
12974 Visit(E);
12975 }
12976
12977 // Forget that the initializers are sequenced.
12978 Region = Parent;
12979 for (unsigned I = 0; I < Elts.size(); ++I)
12980 Tree.merge(Elts[I]);
12981 }
12982};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012983
12984} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012985
12986void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012987 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012988 WorkList.push_back(E);
12989 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012990 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012991 SequenceChecker(*this, Item, WorkList);
12992 }
Richard Smithc406cb72013-01-17 01:17:56 +000012993}
12994
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012995void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12996 bool IsConstexpr) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012997 llvm::SaveAndRestore<bool> ConstantContext(
12998 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
Richard Smithc406cb72013-01-17 01:17:56 +000012999 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000013000 if (!E->isInstantiationDependent())
13001 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013002 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000013003 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013004 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000013005}
13006
John McCall1f425642010-11-11 03:21:53 +000013007void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13008 FieldDecl *BitField,
13009 Expr *Init) {
13010 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13011}
13012
David Majnemer61a5bbf2015-04-07 22:08:51 +000013013static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13014 SourceLocation Loc) {
13015 if (!PType->isVariablyModifiedType())
13016 return;
13017 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13018 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13019 return;
13020 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000013021 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13022 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13023 return;
13024 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000013025 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13026 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13027 return;
13028 }
13029
13030 const ArrayType *AT = S.Context.getAsArrayType(PType);
13031 if (!AT)
13032 return;
13033
13034 if (AT->getSizeModifier() != ArrayType::Star) {
13035 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13036 return;
13037 }
13038
13039 S.Diag(Loc, diag::err_array_star_in_function_definition);
13040}
13041
Mike Stump0c2ec772010-01-21 03:59:47 +000013042/// CheckParmsForFunctionDef - Check that the parameters of the given
13043/// function are appropriate for the definition of a function. This
13044/// takes care of any checks that cannot be performed on the
13045/// declaration itself, e.g., that the types of each of the function
13046/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000013047bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000013048 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000013049 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000013050 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000013051 // C99 6.7.5.3p4: the parameters in a parameter type list in a
13052 // function declarator that is part of a function definition of
13053 // that function shall not have incomplete type.
13054 //
13055 // This is also C++ [dcl.fct]p6.
13056 if (!Param->isInvalidDecl() &&
13057 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013058 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000013059 Param->setInvalidDecl();
13060 HasInvalidParm = true;
13061 }
13062
13063 // C99 6.9.1p5: If the declarator includes a parameter type list, the
13064 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000013065 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000013066 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000013067 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000013068 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000013069 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000013070
13071 // C99 6.7.5.3p12:
13072 // If the function declarator is not part of a definition of that
13073 // function, parameters may have incomplete type and may use the [*]
13074 // notation in their sequences of declarator specifiers to specify
13075 // variable length array types.
13076 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000013077 // FIXME: This diagnostic should point the '[*]' if source-location
13078 // information is added for it.
13079 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000013080
Akira Hatanaka02914dc2018-02-05 20:23:22 +000013081 // If the parameter is a c++ class type and it has to be destructed in the
13082 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000013083 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000013084 if (!Param->isInvalidDecl()) {
13085 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13086 if (!ClassDecl->isInvalidDecl() &&
13087 !ClassDecl->hasIrrelevantDestructor() &&
13088 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000013089 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000013090 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13091 MarkFunctionReferenced(Param->getLocation(), Destructor);
13092 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000013093 }
13094 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000013095 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013096
13097 // Parameters with the pass_object_size attribute only need to be marked
13098 // constant at function definitions. Because we lack information about
13099 // whether we're on a declaration or definition when we're instantiating the
13100 // attribute, we need to check for constness here.
13101 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13102 if (!Param->getType().isConstQualified())
13103 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13104 << Attr->getSpelling() << 1;
Aaron Ballmanc3463f62018-12-05 18:56:57 +000013105
13106 // Check for parameter names shadowing fields from the class.
13107 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13108 // The owning context for the parameter should be the function, but we
13109 // want to see if this function's declaration context is a record.
13110 DeclContext *DC = Param->getDeclContext();
13111 if (DC && DC->isFunctionOrMethod()) {
13112 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13113 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13114 RD, /*DeclIsField*/ false);
13115 }
13116 }
Mike Stump0c2ec772010-01-21 03:59:47 +000013117 }
13118
13119 return HasInvalidParm;
13120}
John McCall2b5c1b22010-08-12 21:44:57 +000013121
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000013122/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13123/// or MemberExpr.
13124static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13125 ASTContext &Context) {
13126 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13127 return Context.getDeclAlign(DRE->getDecl());
13128
13129 if (const auto *ME = dyn_cast<MemberExpr>(E))
13130 return Context.getDeclAlign(ME->getMemberDecl());
13131
13132 return TypeAlign;
13133}
13134
John McCall2b5c1b22010-08-12 21:44:57 +000013135/// CheckCastAlign - Implements -Wcast-align, which warns when a
13136/// pointer cast increases the alignment requirements.
13137void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13138 // This is actually a lot of work to potentially be doing on every
13139 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013140 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000013141 return;
13142
13143 // Ignore dependent types.
13144 if (T->isDependentType() || Op->getType()->isDependentType())
13145 return;
13146
13147 // Require that the destination be a pointer type.
13148 const PointerType *DestPtr = T->getAs<PointerType>();
13149 if (!DestPtr) return;
13150
13151 // If the destination has alignment 1, we're done.
13152 QualType DestPointee = DestPtr->getPointeeType();
13153 if (DestPointee->isIncompleteType()) return;
13154 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13155 if (DestAlign.isOne()) return;
13156
13157 // Require that the source be a pointer type.
13158 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13159 if (!SrcPtr) return;
13160 QualType SrcPointee = SrcPtr->getPointeeType();
13161
13162 // Whitelist casts from cv void*. We already implicitly
13163 // whitelisted casts to cv void*, since they have alignment 1.
13164 // Also whitelist casts involving incomplete types, which implicitly
13165 // includes 'void'.
13166 if (SrcPointee->isIncompleteType()) return;
13167
13168 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000013169
13170 if (auto *CE = dyn_cast<CastExpr>(Op)) {
13171 if (CE->getCastKind() == CK_ArrayToPointerDecay)
13172 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13173 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13174 if (UO->getOpcode() == UO_AddrOf)
13175 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13176 }
13177
John McCall2b5c1b22010-08-12 21:44:57 +000013178 if (SrcAlign >= DestAlign) return;
13179
13180 Diag(TRange.getBegin(), diag::warn_cast_align)
13181 << Op->getType() << T
13182 << static_cast<unsigned>(SrcAlign.getQuantity())
13183 << static_cast<unsigned>(DestAlign.getQuantity())
13184 << TRange << Op->getSourceRange();
13185}
13186
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013187/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000013188/// array member of a struct.
13189///
13190/// We avoid emitting out-of-bounds access warnings for such arrays as they are
13191/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000013192static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000013193 const NamedDecl *ND) {
13194 if (Size != 1 || !ND) return false;
13195
13196 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13197 if (!FD) return false;
13198
13199 // Don't consider sizes resulting from macro expansions or template argument
13200 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000013201
13202 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000013203 while (TInfo) {
13204 TypeLoc TL = TInfo->getTypeLoc();
13205 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000013206 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13207 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000013208 TInfo = TDL->getTypeSourceInfo();
13209 continue;
13210 }
David Blaikie6adc78e2013-02-18 22:06:02 +000013211 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13212 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000013213 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13214 return false;
13215 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000013216 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000013217 }
Chandler Carruth28389f02011-08-05 09:10:50 +000013218
13219 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000013220 if (!RD) return false;
13221 if (RD->isUnion()) return false;
13222 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13223 if (!CRD->isStandardLayout()) return false;
13224 }
Chandler Carruth28389f02011-08-05 09:10:50 +000013225
Benjamin Kramer8c543672011-08-06 03:04:42 +000013226 // See if this is the last field decl in the record.
13227 const Decl *D = FD;
13228 while ((D = D->getNextDeclInContext()))
13229 if (isa<FieldDecl>(D))
13230 return false;
13231 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000013232}
13233
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013234void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013235 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000013236 bool AllowOnePastEnd, bool IndexNegated) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013237 // Already diagnosed by the constant evaluator.
13238 if (isConstantEvaluated())
13239 return;
13240
Eli Friedman84e6e5c2012-02-27 21:21:40 +000013241 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013242 if (IndexExpr->isValueDependent())
13243 return;
13244
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000013245 const Type *EffectiveType =
13246 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013247 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000013248 const ConstantArrayType *ArrayTy =
Bruno Riccied414842018-12-20 20:05:11 +000013249 Context.getAsConstantArrayType(BaseExpr->getType());
13250
Chandler Carruth2a666fc2011-02-17 20:55:08 +000013251 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000013252 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000013253
Bruno Riccied414842018-12-20 20:05:11 +000013254 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
Bruno Ricci95550e42019-03-25 21:37:10 +000013255 if (EffectiveType->isDependentType() || BaseType->isDependentType())
13256 return;
Bruno Riccied414842018-12-20 20:05:11 +000013257
Fangrui Song407659a2018-11-30 23:41:18 +000013258 Expr::EvalResult Result;
13259 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000013260 return;
Fangrui Song407659a2018-11-30 23:41:18 +000013261
13262 llvm::APSInt index = Result.Val.getInt();
Richard Smith13f67182011-12-16 19:31:14 +000013263 if (IndexNegated)
13264 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000013265
Craig Topperc3ec1492014-05-26 06:22:03 +000013266 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000013267 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013268 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000013269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013270 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000013271
Ted Kremeneke4b316c2011-02-23 23:06:04 +000013272 if (index.isUnsigned() || !index.isNegative()) {
Bruno Riccif605e822019-01-08 13:52:54 +000013273 // It is possible that the type of the base expression after
13274 // IgnoreParenCasts is incomplete, even though the type of the base
13275 // expression before IgnoreParenCasts is complete (see PR39746 for an
13276 // example). In this case we have no information about whether the array
13277 // access exceeds the array bounds. However we can still diagnose an array
13278 // access which precedes the array bounds.
13279 if (BaseType->isIncompleteType())
13280 return;
13281
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000013282 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000013283 if (!size.isStrictlyPositive())
13284 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013285
Nico Weber7c299802011-09-17 22:59:41 +000013286 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013287 // Make sure we're comparing apples to apples when comparing index to size
13288 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13289 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000013290 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000013291 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013292 if (ptrarith_typesize != array_typesize) {
13293 // There's a cast to a different size type involved
13294 uint64_t ratio = array_typesize / ptrarith_typesize;
13295 // TODO: Be smarter about handling cases where array_typesize is not a
13296 // multiple of ptrarith_typesize
13297 if (ptrarith_typesize * ratio == array_typesize)
13298 size *= llvm::APInt(size.getBitWidth(), ratio);
13299 }
13300 }
13301
Chandler Carruth2a666fc2011-02-17 20:55:08 +000013302 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000013303 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000013304 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000013305 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000013306
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013307 // For array subscripting the index must be less than size, but for pointer
13308 // arithmetic also allow the index (offset) to be equal to size since
13309 // computing the next address after the end of the array is legal and
13310 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000013311 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000013312 return;
13313
13314 // Also don't warn for arrays of size 1 which are members of some
13315 // structure. These are often used to approximate flexible arrays in C89
13316 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013317 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000013318 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000013319
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013320 // Suppress the warning if the subscript expression (as identified by the
13321 // ']' location) and the index expression are both from macro expansions
13322 // within a system header.
13323 if (ASE) {
13324 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13325 ASE->getRBracketLoc());
13326 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013327 SourceLocation IndexLoc =
13328 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000013329 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013330 return;
13331 }
13332 }
13333
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013334 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013335 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013336 DiagID = diag::warn_array_index_exceeds_bounds;
13337
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013338 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013339 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013340 << size.toString(10, true)
13341 << (unsigned)size.getLimitedValue(~0U)
13342 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000013343 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013344 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013345 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013346 DiagID = diag::warn_ptr_arith_precedes_bounds;
13347 if (index.isNegative()) index = -index;
13348 }
13349
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013350 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013351 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013352 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000013353 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000013354
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013355 if (!ND) {
13356 // Try harder to find a NamedDecl to point at in the note.
13357 while (const ArraySubscriptExpr *ASE =
13358 dyn_cast<ArraySubscriptExpr>(BaseExpr))
13359 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13360 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013361 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013362 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013363 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013364 }
13365
Chandler Carruth1af88f12011-02-17 21:10:52 +000013366 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013367 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
David Bolvanskyfd075682019-09-06 16:12:48 +000013368 PDiag(diag::note_array_declared_here)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013369 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000013370}
13371
Ted Kremenekdf26df72011-03-01 18:41:00 +000013372void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013373 int AllowOnePastEnd = 0;
13374 while (expr) {
13375 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000013376 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013377 case Stmt::ArraySubscriptExprClass: {
13378 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013379 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013380 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000013381 expr = ASE->getBase();
13382 break;
13383 }
13384 case Stmt::MemberExprClass: {
13385 expr = cast<MemberExpr>(expr)->getBase();
13386 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013387 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013388 case Stmt::OMPArraySectionExprClass: {
13389 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13390 if (ASE->getLowerBound())
13391 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13392 /*ASE=*/nullptr, AllowOnePastEnd > 0);
13393 return;
13394 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013395 case Stmt::UnaryOperatorClass: {
13396 // Only unwrap the * and & unary operators
13397 const UnaryOperator *UO = cast<UnaryOperator>(expr);
13398 expr = UO->getSubExpr();
13399 switch (UO->getOpcode()) {
13400 case UO_AddrOf:
13401 AllowOnePastEnd++;
13402 break;
13403 case UO_Deref:
13404 AllowOnePastEnd--;
13405 break;
13406 default:
13407 return;
13408 }
13409 break;
13410 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013411 case Stmt::ConditionalOperatorClass: {
13412 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13413 if (const Expr *lhs = cond->getLHS())
13414 CheckArrayAccess(lhs);
13415 if (const Expr *rhs = cond->getRHS())
13416 CheckArrayAccess(rhs);
13417 return;
13418 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000013419 case Stmt::CXXOperatorCallExprClass: {
13420 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13421 for (const auto *Arg : OCE->arguments())
13422 CheckArrayAccess(Arg);
13423 return;
13424 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013425 default:
13426 return;
13427 }
Peter Collingbourne91147592011-04-15 00:35:48 +000013428 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013429}
John McCall31168b02011-06-15 23:02:42 +000013430
13431//===--- CHECK: Objective-C retain cycles ----------------------------------//
13432
13433namespace {
John McCall31168b02011-06-15 23:02:42 +000013434
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013435struct RetainCycleOwner {
13436 VarDecl *Variable = nullptr;
13437 SourceRange Range;
13438 SourceLocation Loc;
13439 bool Indirect = false;
13440
13441 RetainCycleOwner() = default;
13442
13443 void setLocsFrom(Expr *e) {
13444 Loc = e->getExprLoc();
13445 Range = e->getSourceRange();
13446 }
13447};
13448
13449} // namespace
John McCall31168b02011-06-15 23:02:42 +000013450
13451/// Consider whether capturing the given variable can possibly lead to
13452/// a retain cycle.
13453static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000013454 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000013455 // lifetime. In MRR, it's captured strongly if the variable is
13456 // __block and has an appropriate type.
13457 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13458 return false;
13459
13460 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013461 if (ref)
13462 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000013463 return true;
13464}
13465
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013466static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000013467 while (true) {
13468 e = e->IgnoreParens();
13469 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13470 switch (cast->getCastKind()) {
13471 case CK_BitCast:
13472 case CK_LValueBitCast:
13473 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000013474 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000013475 e = cast->getSubExpr();
13476 continue;
13477
John McCall31168b02011-06-15 23:02:42 +000013478 default:
13479 return false;
13480 }
13481 }
13482
13483 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13484 ObjCIvarDecl *ivar = ref->getDecl();
13485 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13486 return false;
13487
13488 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013489 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000013490 return false;
13491
13492 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13493 owner.Indirect = true;
13494 return true;
13495 }
13496
13497 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13498 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13499 if (!var) return false;
13500 return considerVariable(var, ref, owner);
13501 }
13502
John McCall31168b02011-06-15 23:02:42 +000013503 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13504 if (member->isArrow()) return false;
13505
13506 // Don't count this as an indirect ownership.
13507 e = member->getBase();
13508 continue;
13509 }
13510
John McCallfe96e0b2011-11-06 09:01:30 +000013511 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13512 // Only pay attention to pseudo-objects on property references.
13513 ObjCPropertyRefExpr *pre
13514 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13515 ->IgnoreParens());
13516 if (!pre) return false;
13517 if (pre->isImplicitProperty()) return false;
13518 ObjCPropertyDecl *property = pre->getExplicitProperty();
13519 if (!property->isRetaining() &&
13520 !(property->getPropertyIvarDecl() &&
13521 property->getPropertyIvarDecl()->getType()
13522 .getObjCLifetime() == Qualifiers::OCL_Strong))
13523 return false;
13524
13525 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013526 if (pre->isSuperReceiver()) {
13527 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13528 if (!owner.Variable)
13529 return false;
13530 owner.Loc = pre->getLocation();
13531 owner.Range = pre->getSourceRange();
13532 return true;
13533 }
John McCallfe96e0b2011-11-06 09:01:30 +000013534 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13535 ->getSourceExpr());
13536 continue;
13537 }
13538
John McCall31168b02011-06-15 23:02:42 +000013539 // Array ivars?
13540
13541 return false;
13542 }
13543}
13544
13545namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013546
John McCall31168b02011-06-15 23:02:42 +000013547 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013548 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000013549 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013550 Expr *Capturer = nullptr;
13551 bool VarWillBeReased = false;
13552
13553 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13554 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13555 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000013556
13557 void VisitDeclRefExpr(DeclRefExpr *ref) {
13558 if (ref->getDecl() == Variable && !Capturer)
13559 Capturer = ref;
13560 }
13561
John McCall31168b02011-06-15 23:02:42 +000013562 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13563 if (Capturer) return;
13564 Visit(ref->getBase());
13565 if (Capturer && ref->isFreeIvar())
13566 Capturer = ref;
13567 }
13568
13569 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000013570 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000013571 if (block->getBlockDecl()->capturesVariable(Variable))
13572 Visit(block->getBlockDecl()->getBody());
13573 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013574
Fariborz Jahanian0e337542012-08-31 20:04:47 +000013575 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13576 if (Capturer) return;
13577 if (OVE->getSourceExpr())
13578 Visit(OVE->getSourceExpr());
13579 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013580
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013581 void VisitBinaryOperator(BinaryOperator *BinOp) {
13582 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13583 return;
13584 Expr *LHS = BinOp->getLHS();
13585 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13586 if (DRE->getDecl() != Variable)
13587 return;
13588 if (Expr *RHS = BinOp->getRHS()) {
13589 RHS = RHS->IgnoreParenCasts();
13590 llvm::APSInt Value;
13591 VarWillBeReased =
13592 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13593 }
13594 }
13595 }
John McCall31168b02011-06-15 23:02:42 +000013596 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013597
13598} // namespace
John McCall31168b02011-06-15 23:02:42 +000013599
13600/// Check whether the given argument is a block which captures a
13601/// variable.
13602static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13603 assert(owner.Variable && owner.Loc.isValid());
13604
13605 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000013606
13607 // Look through [^{...} copy] and Block_copy(^{...}).
13608 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13609 Selector Cmd = ME->getSelector();
13610 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13611 e = ME->getInstanceReceiver();
13612 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000013613 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000013614 e = e->IgnoreParenCasts();
13615 }
13616 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13617 if (CE->getNumArgs() == 1) {
13618 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000013619 if (Fn) {
13620 const IdentifierInfo *FnI = Fn->getIdentifier();
13621 if (FnI && FnI->isStr("_Block_copy")) {
13622 e = CE->getArg(0)->IgnoreParenCasts();
13623 }
13624 }
Jordan Rose67e887c2012-09-17 17:54:30 +000013625 }
13626 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013627
John McCall31168b02011-06-15 23:02:42 +000013628 BlockExpr *block = dyn_cast<BlockExpr>(e);
13629 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000013630 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000013631
13632 FindCaptureVisitor visitor(S.Context, owner.Variable);
13633 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013634 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000013635}
13636
13637static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13638 RetainCycleOwner &owner) {
13639 assert(capturer);
13640 assert(owner.Variable && owner.Loc.isValid());
13641
13642 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13643 << owner.Variable << capturer->getSourceRange();
13644 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13645 << owner.Indirect << owner.Range;
13646}
13647
13648/// Check for a keyword selector that starts with the word 'add' or
13649/// 'set'.
13650static bool isSetterLikeSelector(Selector sel) {
13651 if (sel.isUnarySelector()) return false;
13652
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013653 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000013654 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013655 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000013656 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013657 else if (str.startswith("add")) {
13658 // Specially whitelist 'addOperationWithBlock:'.
13659 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13660 return false;
13661 str = str.substr(3);
13662 }
John McCall31168b02011-06-15 23:02:42 +000013663 else
13664 return false;
13665
13666 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000013667 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000013668}
13669
Benjamin Kramer3a743452015-03-09 15:03:32 +000013670static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13671 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013672 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13673 Message->getReceiverInterface(),
13674 NSAPI::ClassId_NSMutableArray);
13675 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013676 return None;
13677 }
13678
13679 Selector Sel = Message->getSelector();
13680
13681 Optional<NSAPI::NSArrayMethodKind> MKOpt =
13682 S.NSAPIObj->getNSArrayMethodKind(Sel);
13683 if (!MKOpt) {
13684 return None;
13685 }
13686
13687 NSAPI::NSArrayMethodKind MK = *MKOpt;
13688
13689 switch (MK) {
13690 case NSAPI::NSMutableArr_addObject:
13691 case NSAPI::NSMutableArr_insertObjectAtIndex:
13692 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13693 return 0;
13694 case NSAPI::NSMutableArr_replaceObjectAtIndex:
13695 return 1;
13696
13697 default:
13698 return None;
13699 }
13700
13701 return None;
13702}
13703
13704static
13705Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13706 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013707 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13708 Message->getReceiverInterface(),
13709 NSAPI::ClassId_NSMutableDictionary);
13710 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013711 return None;
13712 }
13713
13714 Selector Sel = Message->getSelector();
13715
13716 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13717 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13718 if (!MKOpt) {
13719 return None;
13720 }
13721
13722 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13723
13724 switch (MK) {
13725 case NSAPI::NSMutableDict_setObjectForKey:
13726 case NSAPI::NSMutableDict_setValueForKey:
13727 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13728 return 0;
13729
13730 default:
13731 return None;
13732 }
13733
13734 return None;
13735}
13736
13737static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013738 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13739 Message->getReceiverInterface(),
13740 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000013741
Alex Denisov5dfac812015-08-06 04:51:14 +000013742 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13743 Message->getReceiverInterface(),
13744 NSAPI::ClassId_NSMutableOrderedSet);
13745 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013746 return None;
13747 }
13748
13749 Selector Sel = Message->getSelector();
13750
13751 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13752 if (!MKOpt) {
13753 return None;
13754 }
13755
13756 NSAPI::NSSetMethodKind MK = *MKOpt;
13757
13758 switch (MK) {
13759 case NSAPI::NSMutableSet_addObject:
13760 case NSAPI::NSOrderedSet_setObjectAtIndex:
13761 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13762 case NSAPI::NSOrderedSet_insertObjectAtIndex:
13763 return 0;
13764 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13765 return 1;
13766 }
13767
13768 return None;
13769}
13770
13771void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13772 if (!Message->isInstanceMessage()) {
13773 return;
13774 }
13775
13776 Optional<int> ArgOpt;
13777
13778 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13779 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13780 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13781 return;
13782 }
13783
13784 int ArgIndex = *ArgOpt;
13785
Alex Denisove1d882c2015-03-04 17:55:52 +000013786 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13787 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13788 Arg = OE->getSourceExpr()->IgnoreImpCasts();
13789 }
13790
Alex Denisov5dfac812015-08-06 04:51:14 +000013791 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013792 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013793 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013794 Diag(Message->getSourceRange().getBegin(),
13795 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013796 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000013797 }
13798 }
Alex Denisov5dfac812015-08-06 04:51:14 +000013799 } else {
13800 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13801
13802 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13803 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13804 }
13805
13806 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13807 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13808 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13809 ValueDecl *Decl = ReceiverRE->getDecl();
13810 Diag(Message->getSourceRange().getBegin(),
13811 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013812 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013813 if (!ArgRE->isObjCSelfExpr()) {
13814 Diag(Decl->getLocation(),
13815 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013816 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013817 }
13818 }
13819 }
13820 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13821 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13822 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13823 ObjCIvarDecl *Decl = IvarRE->getDecl();
13824 Diag(Message->getSourceRange().getBegin(),
13825 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013826 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013827 Diag(Decl->getLocation(),
13828 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013829 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013830 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013831 }
13832 }
13833 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013834}
13835
John McCall31168b02011-06-15 23:02:42 +000013836/// Check a message send to see if it's likely to cause a retain cycle.
13837void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13838 // Only check instance methods whose selector looks like a setter.
13839 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13840 return;
13841
13842 // Try to find a variable that the receiver is strongly owned by.
13843 RetainCycleOwner owner;
13844 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013845 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000013846 return;
13847 } else {
13848 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13849 owner.Variable = getCurMethodDecl()->getSelfDecl();
13850 owner.Loc = msg->getSuperLoc();
13851 owner.Range = msg->getSuperLoc();
13852 }
13853
13854 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000013855 const ObjCMethodDecl *MD = msg->getMethodDecl();
13856 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13857 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13858 // noescape blocks should not be retained by the method.
13859 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13860 continue;
John McCall31168b02011-06-15 23:02:42 +000013861 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000013862 }
13863 }
John McCall31168b02011-06-15 23:02:42 +000013864}
13865
13866/// Check a property assign to see if it's likely to cause a retain cycle.
13867void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13868 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013869 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000013870 return;
13871
13872 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13873 diagnoseRetainCycle(*this, capturer, owner);
13874}
13875
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013876void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13877 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000013878 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013879 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013880
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013881 // Because we don't have an expression for the variable, we have to set the
13882 // location explicitly here.
13883 Owner.Loc = Var->getLocation();
13884 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000013885
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013886 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13887 diagnoseRetainCycle(*this, Capturer, Owner);
13888}
13889
Ted Kremenek9304da92012-12-21 08:04:28 +000013890static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13891 Expr *RHS, bool isProperty) {
13892 // Check if RHS is an Objective-C object literal, which also can get
13893 // immediately zapped in a weak reference. Note that we explicitly
13894 // allow ObjCStringLiterals, since those are designed to never really die.
13895 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013896
Ted Kremenek64873352012-12-21 22:46:35 +000013897 // This enum needs to match with the 'select' in
13898 // warn_objc_arc_literal_assign (off-by-1).
13899 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13900 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13901 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013902
13903 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000013904 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000013905 << (isProperty ? 0 : 1)
13906 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013907
13908 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000013909}
13910
Ted Kremenekc1f014a2012-12-21 19:45:30 +000013911static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13912 Qualifiers::ObjCLifetime LT,
13913 Expr *RHS, bool isProperty) {
13914 // Strip off any implicit cast added to get to the one ARC-specific.
13915 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13916 if (cast->getCastKind() == CK_ARCConsumeObject) {
13917 S.Diag(Loc, diag::warn_arc_retained_assign)
13918 << (LT == Qualifiers::OCL_ExplicitNone)
13919 << (isProperty ? 0 : 1)
13920 << RHS->getSourceRange();
13921 return true;
13922 }
13923 RHS = cast->getSubExpr();
13924 }
13925
13926 if (LT == Qualifiers::OCL_Weak &&
13927 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13928 return true;
13929
13930 return false;
13931}
13932
Ted Kremenekb36234d2012-12-21 08:04:20 +000013933bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13934 QualType LHS, Expr *RHS) {
13935 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13936
13937 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13938 return false;
13939
13940 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13941 return true;
13942
13943 return false;
13944}
13945
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013946void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13947 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013948 QualType LHSType;
13949 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000013950 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013951 ObjCPropertyRefExpr *PRE
13952 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13953 if (PRE && !PRE->isImplicitProperty()) {
13954 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13955 if (PD)
13956 LHSType = PD->getType();
13957 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013958
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013959 if (LHSType.isNull())
13960 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000013961
13962 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13963
13964 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013965 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000013966 getCurFunction()->markSafeWeakUse(LHS);
13967 }
13968
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013969 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13970 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000013971
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013972 // FIXME. Check for other life times.
13973 if (LT != Qualifiers::OCL_None)
13974 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013975
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013976 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013977 if (PRE->isImplicitProperty())
13978 return;
13979 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13980 if (!PD)
13981 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013982
Bill Wendling44426052012-12-20 19:22:21 +000013983 unsigned Attributes = PD->getPropertyAttributes();
13984 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013985 // when 'assign' attribute was not explicitly specified
13986 // by user, ignore it and rely on property type itself
13987 // for lifetime info.
13988 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13989 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13990 LHSType->isObjCRetainableType())
13991 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013992
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013993 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000013994 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013995 Diag(Loc, diag::warn_arc_retained_property_assign)
13996 << RHS->getSourceRange();
13997 return;
13998 }
13999 RHS = cast->getSubExpr();
14000 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000014001 }
Bill Wendling44426052012-12-20 19:22:21 +000014002 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000014003 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14004 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000014005 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000014006 }
14007}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014008
14009//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14010
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014011static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14012 SourceLocation StmtLoc,
14013 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014014 // Do not warn if the body is a macro that expands to nothing, e.g:
14015 //
14016 // #define CALL(x)
14017 // if (condition)
14018 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014019 if (Body->hasLeadingEmptyMacro())
14020 return false;
14021
14022 // Get line numbers of statement and body.
14023 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000014024 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014025 &StmtLineInvalid);
14026 if (StmtLineInvalid)
14027 return false;
14028
14029 bool BodyLineInvalid;
14030 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14031 &BodyLineInvalid);
14032 if (BodyLineInvalid)
14033 return false;
14034
14035 // Warn if null statement and body are on the same line.
14036 if (StmtLine != BodyLine)
14037 return false;
14038
14039 return true;
14040}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014041
14042void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14043 const Stmt *Body,
14044 unsigned DiagID) {
14045 // Since this is a syntactic check, don't emit diagnostic for template
14046 // instantiations, this just adds noise.
14047 if (CurrentInstantiationScope)
14048 return;
14049
14050 // The body should be a null statement.
14051 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14052 if (!NBody)
14053 return;
14054
14055 // Do the usual checks.
14056 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14057 return;
14058
14059 Diag(NBody->getSemiLoc(), DiagID);
14060 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14061}
14062
14063void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14064 const Stmt *PossibleBody) {
14065 assert(!CurrentInstantiationScope); // Ensured by caller
14066
14067 SourceLocation StmtLoc;
14068 const Stmt *Body;
14069 unsigned DiagID;
14070 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14071 StmtLoc = FS->getRParenLoc();
14072 Body = FS->getBody();
14073 DiagID = diag::warn_empty_for_body;
14074 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14075 StmtLoc = WS->getCond()->getSourceRange().getEnd();
14076 Body = WS->getBody();
14077 DiagID = diag::warn_empty_while_body;
14078 } else
14079 return; // Neither `for' nor `while'.
14080
14081 // The body should be a null statement.
14082 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14083 if (!NBody)
14084 return;
14085
14086 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000014087 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014088 return;
14089
14090 // Do the usual checks.
14091 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14092 return;
14093
14094 // `for(...);' and `while(...);' are popular idioms, so in order to keep
14095 // noise level low, emit diagnostics only if for/while is followed by a
14096 // CompoundStmt, e.g.:
14097 // for (int i = 0; i < n; i++);
14098 // {
14099 // a(i);
14100 // }
14101 // or if for/while is followed by a statement with more indentation
14102 // than for/while itself:
14103 // for (int i = 0; i < n; i++);
14104 // a(i);
14105 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14106 if (!ProbableTypo) {
14107 bool BodyColInvalid;
14108 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014109 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014110 if (BodyColInvalid)
14111 return;
14112
14113 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014114 unsigned StmtCol =
14115 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000014116 if (StmtColInvalid)
14117 return;
14118
14119 if (BodyCol > StmtCol)
14120 ProbableTypo = true;
14121 }
14122
14123 if (ProbableTypo) {
14124 Diag(NBody->getSemiLoc(), DiagID);
14125 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14126 }
14127}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014128
Richard Trieu36d0b2b2015-01-13 02:32:02 +000014129//===--- CHECK: Warn on self move with std::move. -------------------------===//
14130
14131/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14132void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14133 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000014134 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14135 return;
14136
Richard Smith51ec0cf2017-02-21 01:17:38 +000014137 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000014138 return;
14139
14140 // Strip parens and casts away.
14141 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14142 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14143
14144 // Check for a call expression
14145 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14146 if (!CE || CE->getNumArgs() != 1)
14147 return;
14148
14149 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000014150 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000014151 return;
14152
14153 // Get argument from std::move
14154 RHSExpr = CE->getArg(0);
14155
14156 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14157 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14158
14159 // Two DeclRefExpr's, check that the decls are the same.
14160 if (LHSDeclRef && RHSDeclRef) {
14161 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14162 return;
14163 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14164 RHSDeclRef->getDecl()->getCanonicalDecl())
14165 return;
14166
14167 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14168 << LHSExpr->getSourceRange()
14169 << RHSExpr->getSourceRange();
14170 return;
14171 }
14172
14173 // Member variables require a different approach to check for self moves.
14174 // MemberExpr's are the same if every nested MemberExpr refers to the same
14175 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14176 // the base Expr's are CXXThisExpr's.
14177 const Expr *LHSBase = LHSExpr;
14178 const Expr *RHSBase = RHSExpr;
14179 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14180 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14181 if (!LHSME || !RHSME)
14182 return;
14183
14184 while (LHSME && RHSME) {
14185 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14186 RHSME->getMemberDecl()->getCanonicalDecl())
14187 return;
14188
14189 LHSBase = LHSME->getBase();
14190 RHSBase = RHSME->getBase();
14191 LHSME = dyn_cast<MemberExpr>(LHSBase);
14192 RHSME = dyn_cast<MemberExpr>(RHSBase);
14193 }
14194
14195 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14196 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14197 if (LHSDeclRef && RHSDeclRef) {
14198 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14199 return;
14200 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14201 RHSDeclRef->getDecl()->getCanonicalDecl())
14202 return;
14203
14204 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14205 << LHSExpr->getSourceRange()
14206 << RHSExpr->getSourceRange();
14207 return;
14208 }
14209
14210 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14211 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14212 << LHSExpr->getSourceRange()
14213 << RHSExpr->getSourceRange();
14214}
14215
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014216//===--- Layout compatibility ----------------------------------------------//
14217
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014218static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014219
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014220/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014221static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014222 // C++11 [dcl.enum] p8:
14223 // Two enumeration types are layout-compatible if they have the same
14224 // underlying type.
14225 return ED1->isComplete() && ED2->isComplete() &&
14226 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14227}
14228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014229/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014230static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14231 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014232 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14233 return false;
14234
14235 if (Field1->isBitField() != Field2->isBitField())
14236 return false;
14237
14238 if (Field1->isBitField()) {
14239 // Make sure that the bit-fields are the same length.
14240 unsigned Bits1 = Field1->getBitWidthValue(C);
14241 unsigned Bits2 = Field2->getBitWidthValue(C);
14242
14243 if (Bits1 != Bits2)
14244 return false;
14245 }
14246
14247 return true;
14248}
14249
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014250/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014251/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014252static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14253 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014254 // If both records are C++ classes, check that base classes match.
14255 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14256 // If one of records is a CXXRecordDecl we are in C++ mode,
14257 // thus the other one is a CXXRecordDecl, too.
14258 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14259 // Check number of base classes.
14260 if (D1CXX->getNumBases() != D2CXX->getNumBases())
14261 return false;
14262
14263 // Check the base classes.
14264 for (CXXRecordDecl::base_class_const_iterator
14265 Base1 = D1CXX->bases_begin(),
14266 BaseEnd1 = D1CXX->bases_end(),
14267 Base2 = D2CXX->bases_begin();
14268 Base1 != BaseEnd1;
14269 ++Base1, ++Base2) {
14270 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14271 return false;
14272 }
14273 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14274 // If only RD2 is a C++ class, it should have zero base classes.
14275 if (D2CXX->getNumBases() > 0)
14276 return false;
14277 }
14278
14279 // Check the fields.
14280 RecordDecl::field_iterator Field2 = RD2->field_begin(),
14281 Field2End = RD2->field_end(),
14282 Field1 = RD1->field_begin(),
14283 Field1End = RD1->field_end();
14284 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14285 if (!isLayoutCompatible(C, *Field1, *Field2))
14286 return false;
14287 }
14288 if (Field1 != Field1End || Field2 != Field2End)
14289 return false;
14290
14291 return true;
14292}
14293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014294/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014295/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014296static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14297 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014298 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000014299 for (auto *Field2 : RD2->fields())
14300 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014301
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000014302 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014303 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14304 I = UnmatchedFields.begin(),
14305 E = UnmatchedFields.end();
14306
14307 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000014308 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014309 bool Result = UnmatchedFields.erase(*I);
14310 (void) Result;
14311 assert(Result);
14312 break;
14313 }
14314 }
14315 if (I == E)
14316 return false;
14317 }
14318
14319 return UnmatchedFields.empty();
14320}
14321
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014322static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14323 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014324 if (RD1->isUnion() != RD2->isUnion())
14325 return false;
14326
14327 if (RD1->isUnion())
14328 return isLayoutCompatibleUnion(C, RD1, RD2);
14329 else
14330 return isLayoutCompatibleStruct(C, RD1, RD2);
14331}
14332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014333/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014334static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014335 if (T1.isNull() || T2.isNull())
14336 return false;
14337
14338 // C++11 [basic.types] p11:
14339 // If two types T1 and T2 are the same type, then T1 and T2 are
14340 // layout-compatible types.
14341 if (C.hasSameType(T1, T2))
14342 return true;
14343
14344 T1 = T1.getCanonicalType().getUnqualifiedType();
14345 T2 = T2.getCanonicalType().getUnqualifiedType();
14346
14347 const Type::TypeClass TC1 = T1->getTypeClass();
14348 const Type::TypeClass TC2 = T2->getTypeClass();
14349
14350 if (TC1 != TC2)
14351 return false;
14352
14353 if (TC1 == Type::Enum) {
14354 return isLayoutCompatible(C,
14355 cast<EnumType>(T1)->getDecl(),
14356 cast<EnumType>(T2)->getDecl());
14357 } else if (TC1 == Type::Record) {
14358 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14359 return false;
14360
14361 return isLayoutCompatible(C,
14362 cast<RecordType>(T1)->getDecl(),
14363 cast<RecordType>(T2)->getDecl());
14364 }
14365
14366 return false;
14367}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014368
14369//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14370
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014371/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014372///
14373/// \param TypeExpr Type tag expression, as it appears in user's code.
14374///
14375/// \param VD Declaration of an identifier that appears in a type tag.
14376///
14377/// \param MagicValue Type tag magic value.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014378///
14379/// \param isConstantEvaluated wether the evalaution should be performed in
14380
14381/// constant context.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014382static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014383 const ValueDecl **VD, uint64_t *MagicValue,
14384 bool isConstantEvaluated) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014385 while(true) {
14386 if (!TypeExpr)
14387 return false;
14388
14389 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14390
14391 switch (TypeExpr->getStmtClass()) {
14392 case Stmt::UnaryOperatorClass: {
14393 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14394 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14395 TypeExpr = UO->getSubExpr();
14396 continue;
14397 }
14398 return false;
14399 }
14400
14401 case Stmt::DeclRefExprClass: {
14402 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14403 *VD = DRE->getDecl();
14404 return true;
14405 }
14406
14407 case Stmt::IntegerLiteralClass: {
14408 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14409 llvm::APInt MagicValueAPInt = IL->getValue();
14410 if (MagicValueAPInt.getActiveBits() <= 64) {
14411 *MagicValue = MagicValueAPInt.getZExtValue();
14412 return true;
14413 } else
14414 return false;
14415 }
14416
14417 case Stmt::BinaryConditionalOperatorClass:
14418 case Stmt::ConditionalOperatorClass: {
14419 const AbstractConditionalOperator *ACO =
14420 cast<AbstractConditionalOperator>(TypeExpr);
14421 bool Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014422 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14423 isConstantEvaluated)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014424 if (Result)
14425 TypeExpr = ACO->getTrueExpr();
14426 else
14427 TypeExpr = ACO->getFalseExpr();
14428 continue;
14429 }
14430 return false;
14431 }
14432
14433 case Stmt::BinaryOperatorClass: {
14434 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14435 if (BO->getOpcode() == BO_Comma) {
14436 TypeExpr = BO->getRHS();
14437 continue;
14438 }
14439 return false;
14440 }
14441
14442 default:
14443 return false;
14444 }
14445 }
14446}
14447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014448/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014449///
14450/// \param TypeExpr Expression that specifies a type tag.
14451///
14452/// \param MagicValues Registered magic values.
14453///
14454/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14455/// kind.
14456///
14457/// \param TypeInfo Information about the corresponding C type.
14458///
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014459/// \param isConstantEvaluated wether the evalaution should be performed in
14460/// constant context.
14461///
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014462/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014463static bool GetMatchingCType(
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014464 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14465 const ASTContext &Ctx,
14466 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14467 *MagicValues,
14468 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14469 bool isConstantEvaluated) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014470 FoundWrongKind = false;
14471
14472 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000014473 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014474
14475 uint64_t MagicValue;
14476
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014477 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014478 return false;
14479
14480 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000014481 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014482 if (I->getArgumentKind() != ArgumentKind) {
14483 FoundWrongKind = true;
14484 return false;
14485 }
14486 TypeInfo.Type = I->getMatchingCType();
14487 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14488 TypeInfo.MustBeNull = I->getMustBeNull();
14489 return true;
14490 }
14491 return false;
14492 }
14493
14494 if (!MagicValues)
14495 return false;
14496
14497 llvm::DenseMap<Sema::TypeTagMagicValue,
14498 Sema::TypeTagData>::const_iterator I =
14499 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14500 if (I == MagicValues->end())
14501 return false;
14502
14503 TypeInfo = I->second;
14504 return true;
14505}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014506
14507void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14508 uint64_t MagicValue, QualType Type,
14509 bool LayoutCompatible,
14510 bool MustBeNull) {
14511 if (!TypeTagForDatatypeMagicValues)
14512 TypeTagForDatatypeMagicValues.reset(
14513 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14514
14515 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14516 (*TypeTagForDatatypeMagicValues)[Magic] =
14517 TypeTagData(Type, LayoutCompatible, MustBeNull);
14518}
14519
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014520static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014521 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14522 if (!BT1)
14523 return false;
14524
14525 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14526 if (!BT2)
14527 return false;
14528
14529 BuiltinType::Kind T1Kind = BT1->getKind();
14530 BuiltinType::Kind T2Kind = BT2->getKind();
14531
14532 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14533 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14534 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14535 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14536}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014537
14538void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014539 const ArrayRef<const Expr *> ExprArgs,
14540 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014541 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14542 bool IsPointerAttr = Attr->getIsPointer();
14543
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014544 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000014545 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14546 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014547 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000014548 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014549 return;
14550 }
Joel E. Denny81508102018-03-13 14:51:22 +000014551 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014552 bool FoundWrongKind;
14553 TypeTagData TypeInfo;
14554 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014555 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14556 TypeInfo, isConstantEvaluated())) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014557 if (FoundWrongKind)
14558 Diag(TypeTagExpr->getExprLoc(),
14559 diag::warn_type_tag_for_datatype_wrong_kind)
14560 << TypeTagExpr->getSourceRange();
14561 return;
14562 }
14563
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014564 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000014565 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14566 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014567 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000014568 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014569 return;
14570 }
Joel E. Denny81508102018-03-13 14:51:22 +000014571 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014572 if (IsPointerAttr) {
14573 // Skip implicit cast of pointer to `void *' (as a function argument).
14574 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000014575 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000014576 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014577 ArgumentExpr = ICE->getSubExpr();
14578 }
14579 QualType ArgumentType = ArgumentExpr->getType();
14580
14581 // Passing a `void*' pointer shouldn't trigger a warning.
14582 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14583 return;
14584
14585 if (TypeInfo.MustBeNull) {
14586 // Type tag with matching void type requires a null pointer.
14587 if (!ArgumentExpr->isNullPointerConstant(Context,
14588 Expr::NPC_ValueDependentIsNotNull)) {
14589 Diag(ArgumentExpr->getExprLoc(),
14590 diag::warn_type_safety_null_pointer_required)
14591 << ArgumentKind->getName()
14592 << ArgumentExpr->getSourceRange()
14593 << TypeTagExpr->getSourceRange();
14594 }
14595 return;
14596 }
14597
14598 QualType RequiredType = TypeInfo.Type;
14599 if (IsPointerAttr)
14600 RequiredType = Context.getPointerType(RequiredType);
14601
14602 bool mismatch = false;
14603 if (!TypeInfo.LayoutCompatible) {
14604 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14605
14606 // C++11 [basic.fundamental] p1:
14607 // Plain char, signed char, and unsigned char are three distinct types.
14608 //
14609 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14610 // char' depending on the current char signedness mode.
14611 if (mismatch)
14612 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14613 RequiredType->getPointeeType())) ||
14614 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14615 mismatch = false;
14616 } else
14617 if (IsPointerAttr)
14618 mismatch = !isLayoutCompatible(Context,
14619 ArgumentType->getPointeeType(),
14620 RequiredType->getPointeeType());
14621 else
14622 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14623
14624 if (mismatch)
14625 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000014626 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014627 << TypeInfo.LayoutCompatible << RequiredType
14628 << ArgumentExpr->getSourceRange()
14629 << TypeTagExpr->getSourceRange();
14630}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014631
14632void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14633 CharUnits Alignment) {
14634 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14635}
14636
14637void Sema::DiagnoseMisalignedMembers() {
14638 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000014639 const NamedDecl *ND = m.RD;
14640 if (ND->getName().empty()) {
14641 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14642 ND = TD;
14643 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014644 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000014645 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014646 }
14647 MisalignedMembers.clear();
14648}
14649
14650void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014651 E = E->IgnoreParens();
14652 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014653 return;
14654 if (isa<UnaryOperator>(E) &&
14655 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14656 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14657 if (isa<MemberExpr>(Op)) {
Fangrui Song75e74e02019-03-31 08:48:19 +000014658 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014659 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014660 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000014661 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14662 Context.getTypeAlignInChars(
14663 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014664 MisalignedMembers.erase(MA);
14665 }
14666 }
14667}
14668
14669void Sema::RefersToMemberWithReducedAlignment(
14670 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000014671 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14672 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014673 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014674 if (!ME)
14675 return;
14676
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000014677 // No need to check expressions with an __unaligned-qualified type.
14678 if (E->getType().getQualifiers().hasUnaligned())
14679 return;
14680
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014681 // For a chain of MemberExpr like "a.b.c.d" this list
14682 // will keep FieldDecl's like [d, c, b].
14683 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14684 const MemberExpr *TopME = nullptr;
14685 bool AnyIsPacked = false;
14686 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014687 QualType BaseType = ME->getBase()->getType();
14688 if (ME->isArrow())
14689 BaseType = BaseType->getPointeeType();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +000014690 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000014691 if (RD->isInvalidDecl())
14692 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014693
14694 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014695 auto *FD = dyn_cast<FieldDecl>(MD);
14696 // We do not care about non-data members.
14697 if (!FD || FD->isInvalidDecl())
14698 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014699
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014700 AnyIsPacked =
14701 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14702 ReverseMemberChain.push_back(FD);
14703
14704 TopME = ME;
14705 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14706 } while (ME);
14707 assert(TopME && "We did not compute a topmost MemberExpr!");
14708
14709 // Not the scope of this diagnostic.
14710 if (!AnyIsPacked)
14711 return;
14712
14713 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14714 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14715 // TODO: The innermost base of the member expression may be too complicated.
14716 // For now, just disregard these cases. This is left for future
14717 // improvement.
14718 if (!DRE && !isa<CXXThisExpr>(TopBase))
14719 return;
14720
14721 // Alignment expected by the whole expression.
14722 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14723
14724 // No need to do anything else with this case.
14725 if (ExpectedAlignment.isOne())
14726 return;
14727
14728 // Synthesize offset of the whole access.
14729 CharUnits Offset;
14730 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14731 I++) {
14732 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14733 }
14734
14735 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14736 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14737 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14738
14739 // The base expression of the innermost MemberExpr may give
14740 // stronger guarantees than the class containing the member.
14741 if (DRE && !TopME->isArrow()) {
14742 const ValueDecl *VD = DRE->getDecl();
14743 if (!VD->getType()->isReferenceType())
14744 CompleteObjectAlignment =
14745 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14746 }
14747
14748 // Check if the synthesized offset fulfills the alignment.
14749 if (Offset % ExpectedAlignment != 0 ||
14750 // It may fulfill the offset it but the effective alignment may still be
14751 // lower than the expected expression alignment.
14752 CompleteObjectAlignment < ExpectedAlignment) {
14753 // If this happens, we want to determine a sensible culprit of this.
14754 // Intuitively, watching the chain of member expressions from right to
14755 // left, we start with the required alignment (as required by the field
14756 // type) but some packed attribute in that chain has reduced the alignment.
14757 // It may happen that another packed structure increases it again. But if
14758 // we are here such increase has not been enough. So pointing the first
14759 // FieldDecl that either is packed or else its RecordDecl is,
14760 // seems reasonable.
14761 FieldDecl *FD = nullptr;
14762 CharUnits Alignment;
14763 for (FieldDecl *FDI : ReverseMemberChain) {
14764 if (FDI->hasAttr<PackedAttr>() ||
14765 FDI->getParent()->hasAttr<PackedAttr>()) {
14766 FD = FDI;
14767 Alignment = std::min(
14768 Context.getTypeAlignInChars(FD->getType()),
14769 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14770 break;
14771 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014772 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014773 assert(FD && "We did not find a packed FieldDecl!");
14774 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014775 }
14776}
14777
14778void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14779 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014780
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014781 RefersToMemberWithReducedAlignment(
14782 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14783 _2, _3, _4));
14784}