blob: de061e62aad5496b9a8d36311fd553254b43b84b [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000087#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000088#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <functional>
93#include <limits>
94#include <string>
95#include <tuple>
96#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Chris Lattnerb87b1b32007-08-10 20:18:51 +000098using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000099using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000100
Chris Lattnera26fb342009-02-18 17:49:48 +0000101SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000105}
106
John McCallbebede42011-02-26 05:39:39 +0000107/// Checks that a call expression's argument count is the desired number.
108/// This is useful when doing custom type-checking. Returns true on error.
109static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
112
113 if (argCount < desiredArgCount)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000114 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
John McCallbebede42011-02-26 05:39:39 +0000117
118 // Highlight all the excess arguments.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000119 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000120 call->getArg(argCount - 1)->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +0000121
John McCallbebede42011-02-26 05:39:39 +0000122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
125}
126
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000127/// Check that the first argument to __builtin_annotation is an integer
128/// and the second argument is a non-wide string literal.
129static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
131 return true;
132
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000137 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000139 return true;
140 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000141
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000146 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000148 return true;
149 }
150
151 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000152 return false;
153}
154
Reid Kleckner30701ed2017-09-05 20:27:35 +0000155static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000158 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
161 return true;
162 }
163
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000168 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000169 << Arg->getSourceRange();
170 return true;
171 }
172 }
173
174 return false;
175}
176
Richard Smith6cbd65d2013-07-11 02:27:57 +0000177/// Check that the argument to __builtin_addressof is a glvalue, and set the
178/// result type to the corresponding pointer type.
179static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
181 return true;
182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000183 ExprResult Arg(TheCall->getArg(0));
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000185 if (ResultType.isNull())
186 return true;
187
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000188 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000189 TheCall->setType(ResultType);
190 return false;
191}
192
John McCall03107a42015-10-29 20:48:01 +0000193static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
195 return true;
196
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000199 ExprResult Arg = TheCall->getArg(I);
200 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000201 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000202 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
Erich Keane1d73d1a2018-06-13 13:25:11 +0000203 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000204 return true;
205 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000206 InitializedEntity Entity = InitializedEntity::InitializeParameter(
207 S.getASTContext(), Ty, /*consume*/ false);
208 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
209 if (Arg.isInvalid())
210 return true;
211 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000212 }
213
214 // Third argument should be a pointer to a non-const integer.
215 // IRGen correctly handles volatile, restrict, and address spaces, and
216 // the other qualifiers aren't possible.
217 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000218 ExprResult Arg = TheCall->getArg(2);
219 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000220 const auto *PtrTy = Ty->getAs<PointerType>();
221 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
222 !PtrTy->getPointeeType().isConstQualified())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000223 S.Diag(Arg.get()->getBeginLoc(),
Erich Keane1d73d1a2018-06-13 13:25:11 +0000224 diag::err_overflow_builtin_must_be_ptr_int)
225 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000226 return true;
227 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000228 InitializedEntity Entity = InitializedEntity::InitializeParameter(
229 S.getASTContext(), Ty, /*consume*/ false);
230 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
231 if (Arg.isInvalid())
232 return true;
233 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000234 }
John McCall03107a42015-10-29 20:48:01 +0000235 return false;
236}
237
Peter Collingbournef7706832014-12-12 23:41:25 +0000238static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
239 if (checkArgCount(S, BuiltinCall, 2))
240 return true;
241
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000242 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000243 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
244 Expr *Call = BuiltinCall->getArg(0);
245 Expr *Chain = BuiltinCall->getArg(1);
246
247 if (Call->getStmtClass() != Stmt::CallExprClass) {
248 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
249 << Call->getSourceRange();
250 return true;
251 }
252
253 auto CE = cast<CallExpr>(Call);
254 if (CE->getCallee()->getType()->isBlockPointerType()) {
255 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
256 << Call->getSourceRange();
257 return true;
258 }
259
260 const Decl *TargetDecl = CE->getCalleeDecl();
261 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
262 if (FD->getBuiltinID()) {
263 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
264 << Call->getSourceRange();
265 return true;
266 }
267
268 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
269 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
270 << Call->getSourceRange();
271 return true;
272 }
273
274 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
275 if (ChainResult.isInvalid())
276 return true;
277 if (!ChainResult.get()->getType()->isPointerType()) {
278 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
279 << Chain->getSourceRange();
280 return true;
281 }
282
David Majnemerced8bdf2015-02-25 17:36:15 +0000283 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000284 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
285 QualType BuiltinTy = S.Context.getFunctionType(
286 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
287 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
288
289 Builtin =
290 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
291
292 BuiltinCall->setType(CE->getType());
293 BuiltinCall->setValueKind(CE->getValueKind());
294 BuiltinCall->setObjectKind(CE->getObjectKind());
295 BuiltinCall->setCallee(Builtin);
296 BuiltinCall->setArg(1, ChainResult.get());
297
298 return false;
299}
300
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000301/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
302/// __builtin_*_chk function, then use the object size argument specified in the
303/// source. Otherwise, infer the object size using __builtin_object_size.
304void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
305 CallExpr *TheCall) {
306 // FIXME: There are some more useful checks we could be doing here:
307 // - Analyze the format string of sprintf to see how much of buffer is used.
308 // - Evaluate strlen of strcpy arguments, use as object size.
309
Erik Pilkington233ff942019-03-29 19:53:41 +0000310 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
311 return;
312
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000313 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
314 if (!BuiltinID)
315 return;
316
317 unsigned DiagID = 0;
318 bool IsChkVariant = false;
319 unsigned SizeIndex, ObjectIndex;
320 switch (BuiltinID) {
321 default:
322 return;
323 case Builtin::BI__builtin___memcpy_chk:
324 case Builtin::BI__builtin___memmove_chk:
325 case Builtin::BI__builtin___memset_chk:
326 case Builtin::BI__builtin___strlcat_chk:
327 case Builtin::BI__builtin___strlcpy_chk:
328 case Builtin::BI__builtin___strncat_chk:
329 case Builtin::BI__builtin___strncpy_chk:
330 case Builtin::BI__builtin___stpncpy_chk:
331 case Builtin::BI__builtin___memccpy_chk: {
332 DiagID = diag::warn_builtin_chk_overflow;
333 IsChkVariant = true;
334 SizeIndex = TheCall->getNumArgs() - 2;
335 ObjectIndex = TheCall->getNumArgs() - 1;
336 break;
337 }
338
339 case Builtin::BI__builtin___snprintf_chk:
340 case Builtin::BI__builtin___vsnprintf_chk: {
341 DiagID = diag::warn_builtin_chk_overflow;
342 IsChkVariant = true;
343 SizeIndex = 1;
344 ObjectIndex = 3;
345 break;
346 }
347
348 case Builtin::BIstrncat:
349 case Builtin::BI__builtin_strncat:
350 case Builtin::BIstrncpy:
351 case Builtin::BI__builtin_strncpy:
352 case Builtin::BIstpncpy:
353 case Builtin::BI__builtin_stpncpy: {
354 // Whether these functions overflow depends on the runtime strlen of the
355 // string, not just the buffer size, so emitting the "always overflow"
356 // diagnostic isn't quite right. We should still diagnose passing a buffer
357 // size larger than the destination buffer though; this is a runtime abort
358 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
359 DiagID = diag::warn_fortify_source_size_mismatch;
360 SizeIndex = TheCall->getNumArgs() - 1;
361 ObjectIndex = 0;
362 break;
363 }
364
365 case Builtin::BImemcpy:
366 case Builtin::BI__builtin_memcpy:
367 case Builtin::BImemmove:
368 case Builtin::BI__builtin_memmove:
369 case Builtin::BImemset:
370 case Builtin::BI__builtin_memset: {
371 DiagID = diag::warn_fortify_source_overflow;
372 SizeIndex = TheCall->getNumArgs() - 1;
373 ObjectIndex = 0;
374 break;
375 }
376 case Builtin::BIsnprintf:
377 case Builtin::BI__builtin_snprintf:
378 case Builtin::BIvsnprintf:
379 case Builtin::BI__builtin_vsnprintf: {
380 DiagID = diag::warn_fortify_source_size_mismatch;
381 SizeIndex = 1;
382 ObjectIndex = 0;
383 break;
384 }
385 }
386
387 llvm::APSInt ObjectSize;
388 // For __builtin___*_chk, the object size is explicitly provided by the caller
389 // (usually using __builtin_object_size). Use that value to check this call.
390 if (IsChkVariant) {
391 Expr::EvalResult Result;
392 Expr *SizeArg = TheCall->getArg(ObjectIndex);
393 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
394 return;
395 ObjectSize = Result.Val.getInt();
396
397 // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
398 } else {
399 // If the parameter has a pass_object_size attribute, then we should use its
400 // (potentially) more strict checking mode. Otherwise, conservatively assume
401 // type 0.
402 int BOSType = 0;
403 if (const auto *POS =
404 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
405 BOSType = POS->getType();
406
407 Expr *ObjArg = TheCall->getArg(ObjectIndex);
408 uint64_t Result;
409 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
410 return;
411 // Get the object size in the target's size_t width.
412 const TargetInfo &TI = getASTContext().getTargetInfo();
413 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
414 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
415 }
416
417 // Evaluate the number of bytes of the object that this call will use.
418 Expr::EvalResult Result;
419 Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
420 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
421 return;
422 llvm::APSInt UsedSize = Result.Val.getInt();
423
424 if (UsedSize.ule(ObjectSize))
425 return;
426
427 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
428 // Skim off the details of whichever builtin was called to produce a better
429 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
430 if (IsChkVariant) {
431 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
432 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
433 } else if (FunctionName.startswith("__builtin_")) {
434 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
435 }
436
Erik Pilkington81869802019-03-26 23:21:22 +0000437 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
438 PDiag(DiagID)
439 << FunctionName << ObjectSize.toString(/*Radix=*/10)
440 << UsedSize.toString(/*Radix=*/10));
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000441}
442
Reid Kleckner1d59f992015-01-22 01:36:17 +0000443static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
444 Scope::ScopeFlags NeededScopeFlags,
445 unsigned DiagID) {
446 // Scopes aren't available during instantiation. Fortunately, builtin
447 // functions cannot be template args so they cannot be formed through template
448 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000449 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000450 return false;
451
452 Scope *S = SemaRef.getCurScope();
453 while (S && !S->isSEHExceptScope())
454 S = S->getParent();
455 if (!S || !(S->getFlags() & NeededScopeFlags)) {
456 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
457 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
458 << DRE->getDecl()->getIdentifier();
459 return true;
460 }
461
462 return false;
463}
464
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000465static inline bool isBlockPointer(Expr *Arg) {
466 return Arg->getType()->isBlockPointerType();
467}
468
469/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
470/// void*, which is a requirement of device side enqueue.
471static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
472 const BlockPointerType *BPT =
473 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
474 ArrayRef<QualType> Params =
475 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
476 unsigned ArgCounter = 0;
477 bool IllegalParams = false;
478 // Iterate through the block parameters until either one is found that is not
479 // a local void*, or the block is valid.
480 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
481 I != E; ++I, ++ArgCounter) {
482 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
483 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
484 LangAS::opencl_local) {
485 // Get the location of the error. If a block literal has been passed
486 // (BlockExpr) then we can point straight to the offending argument,
487 // else we just point to the variable reference.
488 SourceLocation ErrorLoc;
489 if (isa<BlockExpr>(BlockArg)) {
490 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000491 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000492 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000493 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000494 }
495 S.Diag(ErrorLoc,
496 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
497 IllegalParams = true;
498 }
499 }
500
501 return IllegalParams;
502}
503
Joey Gouly84ae3362017-07-31 15:15:59 +0000504static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
505 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000506 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
507 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000508 return true;
509 }
510 return false;
511}
512
Joey Goulyfa76b492017-08-01 13:27:09 +0000513static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
514 if (checkArgCount(S, TheCall, 2))
515 return true;
516
517 if (checkOpenCLSubgroupExt(S, TheCall))
518 return true;
519
520 // First argument is an ndrange_t type.
521 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000522 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000523 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000524 << TheCall->getDirectCallee() << "'ndrange_t'";
525 return true;
526 }
527
528 Expr *BlockArg = TheCall->getArg(1);
529 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000530 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000531 << TheCall->getDirectCallee() << "block";
532 return true;
533 }
534 return checkOpenCLBlockArgs(S, BlockArg);
535}
536
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
538/// get_kernel_work_group_size
539/// and get_kernel_preferred_work_group_size_multiple builtin functions.
540static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
541 if (checkArgCount(S, TheCall, 1))
542 return true;
543
544 Expr *BlockArg = TheCall->getArg(0);
545 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000546 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000547 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000548 return true;
549 }
550 return checkOpenCLBlockArgs(S, BlockArg);
551}
552
Simon Pilgrim2c518802017-03-30 14:13:19 +0000553/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000554static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
555 const QualType &IntType);
556
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000557static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000558 unsigned Start, unsigned End) {
559 bool IllegalParams = false;
560 for (unsigned I = Start; I <= End; ++I)
561 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
562 S.Context.getSizeType());
563 return IllegalParams;
564}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000565
566/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
567/// 'local void*' parameter of passed block.
568static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
569 Expr *BlockArg,
570 unsigned NumNonVarArgs) {
571 const BlockPointerType *BPT =
572 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
573 unsigned NumBlockParams =
574 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
575 unsigned TotalNumArgs = TheCall->getNumArgs();
576
577 // For each argument passed to the block, a corresponding uint needs to
578 // be passed to describe the size of the local memory.
579 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000580 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000581 diag::err_opencl_enqueue_kernel_local_size_args);
582 return true;
583 }
584
585 // Check that the sizes of the local memory are specified by integers.
586 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
587 TotalNumArgs - 1);
588}
589
590/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
591/// overload formats specified in Table 6.13.17.1.
592/// int enqueue_kernel(queue_t queue,
593/// kernel_enqueue_flags_t flags,
594/// const ndrange_t ndrange,
595/// void (^block)(void))
596/// int enqueue_kernel(queue_t queue,
597/// kernel_enqueue_flags_t flags,
598/// const ndrange_t ndrange,
599/// uint num_events_in_wait_list,
600/// clk_event_t *event_wait_list,
601/// clk_event_t *event_ret,
602/// void (^block)(void))
603/// int enqueue_kernel(queue_t queue,
604/// kernel_enqueue_flags_t flags,
605/// const ndrange_t ndrange,
606/// void (^block)(local void*, ...),
607/// uint size0, ...)
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)(local void*, ...),
615/// uint size0, ...)
616static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
617 unsigned NumArgs = TheCall->getNumArgs();
618
619 if (NumArgs < 4) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000620 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000621 return true;
622 }
623
624 Expr *Arg0 = TheCall->getArg(0);
625 Expr *Arg1 = TheCall->getArg(1);
626 Expr *Arg2 = TheCall->getArg(2);
627 Expr *Arg3 = TheCall->getArg(3);
628
629 // First argument always needs to be a queue_t type.
630 if (!Arg0->getType()->isQueueT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000631 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000632 diag::err_opencl_builtin_expected_type)
633 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000634 return true;
635 }
636
637 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
638 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000639 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000640 diag::err_opencl_builtin_expected_type)
641 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000642 return true;
643 }
644
645 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000646 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000647 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000648 diag::err_opencl_builtin_expected_type)
649 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000650 return true;
651 }
652
653 // With four arguments, there is only one form that the function could be
654 // called in: no events and no variable arguments.
655 if (NumArgs == 4) {
656 // check that the last argument is the right block type.
657 if (!isBlockPointer(Arg3)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000658 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000659 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000660 return true;
661 }
662 // we have a block type, check the prototype
663 const BlockPointerType *BPT =
664 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
665 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000666 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000667 diag::err_opencl_enqueue_kernel_blocks_no_args);
668 return true;
669 }
670 return false;
671 }
672 // we can have block + varargs.
673 if (isBlockPointer(Arg3))
674 return (checkOpenCLBlockArgs(S, Arg3) ||
675 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
676 // last two cases with either exactly 7 args or 7 args and varargs.
677 if (NumArgs >= 7) {
678 // check common block argument.
679 Expr *Arg6 = TheCall->getArg(6);
680 if (!isBlockPointer(Arg6)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000681 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000682 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000683 return true;
684 }
685 if (checkOpenCLBlockArgs(S, Arg6))
686 return true;
687
688 // Forth argument has to be any integer type.
689 if (!Arg3->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000690 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000691 diag::err_opencl_builtin_expected_type)
692 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000693 return true;
694 }
695 // check remaining common arguments.
696 Expr *Arg4 = TheCall->getArg(4);
697 Expr *Arg5 = TheCall->getArg(5);
698
Anastasia Stulova2b461202016-11-14 15:34:01 +0000699 // Fifth argument is always passed as a pointer to clk_event_t.
700 if (!Arg4->isNullPointerConstant(S.Context,
701 Expr::NPC_ValueDependentIsNotNull) &&
702 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000703 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000704 diag::err_opencl_builtin_expected_type)
705 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000706 << S.Context.getPointerType(S.Context.OCLClkEventTy);
707 return true;
708 }
709
Anastasia Stulova2b461202016-11-14 15:34:01 +0000710 // Sixth argument is always passed as a pointer to clk_event_t.
711 if (!Arg5->isNullPointerConstant(S.Context,
712 Expr::NPC_ValueDependentIsNotNull) &&
713 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000714 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000715 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000716 diag::err_opencl_builtin_expected_type)
717 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000718 << S.Context.getPointerType(S.Context.OCLClkEventTy);
719 return true;
720 }
721
722 if (NumArgs == 7)
723 return false;
724
725 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
726 }
727
728 // None of the specific case has been detected, give generic error
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000729 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000730 diag::err_opencl_enqueue_kernel_incorrect_args);
731 return true;
732}
733
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000735static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000736 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000737}
738
739/// Returns true if pipe element type is different from the pointer.
740static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
741 const Expr *Arg0 = Call->getArg(0);
742 // First argument type should always be pipe.
743 if (!Arg0->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000745 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000746 return true;
747 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000748 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000749 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
750 // Validates the access qualifier is compatible with the call.
751 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
752 // read_only and write_only, and assumed to be read_only if no qualifier is
753 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000754 switch (Call->getDirectCallee()->getBuiltinID()) {
755 case Builtin::BIread_pipe:
756 case Builtin::BIreserve_read_pipe:
757 case Builtin::BIcommit_read_pipe:
758 case Builtin::BIwork_group_reserve_read_pipe:
759 case Builtin::BIsub_group_reserve_read_pipe:
760 case Builtin::BIwork_group_commit_read_pipe:
761 case Builtin::BIsub_group_commit_read_pipe:
762 if (!(!AccessQual || AccessQual->isReadOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000763 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000764 diag::err_opencl_builtin_pipe_invalid_access_modifier)
765 << "read_only" << Arg0->getSourceRange();
766 return true;
767 }
768 break;
769 case Builtin::BIwrite_pipe:
770 case Builtin::BIreserve_write_pipe:
771 case Builtin::BIcommit_write_pipe:
772 case Builtin::BIwork_group_reserve_write_pipe:
773 case Builtin::BIsub_group_reserve_write_pipe:
774 case Builtin::BIwork_group_commit_write_pipe:
775 case Builtin::BIsub_group_commit_write_pipe:
776 if (!(AccessQual && AccessQual->isWriteOnly())) {
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 << "write_only" << Arg0->getSourceRange();
780 return true;
781 }
782 break;
783 default:
784 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000785 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000786 return false;
787}
788
789/// Returns true if pipe element type is different from the pointer.
790static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
791 const Expr *Arg0 = Call->getArg(0);
792 const Expr *ArgIdx = Call->getArg(Idx);
793 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000794 const QualType EltTy = PipeTy->getElementType();
795 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000796 // The Idx argument should be a pointer and the type of the pointer and
797 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000798 if (!ArgTy ||
799 !S.Context.hasSameType(
800 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000801 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000802 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000803 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 return true;
805 }
806 return false;
807}
808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000809// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000810// \param S Reference to the semantic analyzer.
811// \param Call A pointer to the builtin call.
812// \return True if a semantic error has been found, false otherwise.
813static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000814 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
815 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000816 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000817 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000818 if (checkOpenCLPipeArg(S, Call))
819 return true;
820 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000821 // read/write_pipe(pipe T, T*).
822 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000823 if (checkOpenCLPipePacketType(S, Call, 1))
824 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000825 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000826
827 case 4: {
828 if (checkOpenCLPipeArg(S, Call))
829 return true;
830 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000831 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
832 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000833 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000834 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000835 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000836 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000837 return true;
838 }
839
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000840 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000841 const Expr *Arg2 = Call->getArg(2);
842 if (!Arg2->getType()->isIntegerType() &&
843 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000844 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000845 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000846 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000847 return true;
848 }
849
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000850 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000851 if (checkOpenCLPipePacketType(S, Call, 3))
852 return true;
853 } break;
854 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000855 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000856 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000857 return true;
858 }
859
860 return false;
861}
862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000863// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000864// /_}reserve_{read/write}_pipe
865// \param S Reference to the semantic analyzer.
866// \param Call The call to the builtin function to be analyzed.
867// \return True if a semantic error was found, false otherwise.
868static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
869 if (checkArgCount(S, Call, 2))
870 return true;
871
872 if (checkOpenCLPipeArg(S, Call))
873 return true;
874
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000875 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000876 if (!Call->getArg(1)->getType()->isIntegerType() &&
877 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000878 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000879 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000880 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000881 return true;
882 }
883
Joey Gouly922ca232017-08-09 14:52:47 +0000884 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000885 // reserve_id_t, which is not defined in the builtin def file , we used int
886 // as return type and need to override the return type of these functions.
887 Call->setType(S.Context.OCLReserveIDTy);
888
889 return false;
890}
891
892// Performs a semantic analysis on {work_group_/sub_group_
893// /_}commit_{read/write}_pipe
894// \param S Reference to the semantic analyzer.
895// \param Call The call to the builtin function to be analyzed.
896// \return True if a semantic error was found, false otherwise.
897static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
898 if (checkArgCount(S, Call, 2))
899 return true;
900
901 if (checkOpenCLPipeArg(S, Call))
902 return true;
903
904 // Check reserve_id_t.
905 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000906 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000907 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
908 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
909 return true;
910 }
911
912 return false;
913}
914
915// Performs a semantic analysis on the call to built-in Pipe
916// Query Functions.
917// \param S Reference to the semantic analyzer.
918// \param Call The call to the builtin function to be analyzed.
919// \return True if a semantic error was found, false otherwise.
920static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
921 if (checkArgCount(S, Call, 1))
922 return true;
923
924 if (!Call->getArg(0)->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000925 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000926 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
927 return true;
928 }
929
930 return false;
931}
932
933// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
934// Performs semantic analysis for the to_global/local/private call.
935// \param S Reference to the semantic analyzer.
936// \param BuiltinID ID of the builtin function.
937// \param Call A pointer to the builtin call.
938// \return True if a semantic error has been found, false otherwise.
939static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
940 CallExpr *Call) {
941 if (Call->getNumArgs() != 1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000942 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000943 << Call->getDirectCallee() << Call->getSourceRange();
944 return true;
945 }
946
947 auto RT = Call->getArg(0)->getType();
948 if (!RT->isPointerType() || RT->getPointeeType()
949 .getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000950 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000951 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
952 return true;
953 }
954
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000955 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
956 S.Diag(Call->getArg(0)->getBeginLoc(),
957 diag::warn_opencl_generic_address_space_arg)
958 << Call->getDirectCallee()->getNameInfo().getAsString()
959 << Call->getArg(0)->getSourceRange();
960 }
961
Aaron Ballman68d50642018-06-19 14:53:20 +0000962 RT = RT->getPointeeType();
963 auto Qual = RT.getQualifiers();
964 switch (BuiltinID) {
965 case Builtin::BIto_global:
966 Qual.setAddressSpace(LangAS::opencl_global);
967 break;
968 case Builtin::BIto_local:
969 Qual.setAddressSpace(LangAS::opencl_local);
970 break;
971 case Builtin::BIto_private:
972 Qual.setAddressSpace(LangAS::opencl_private);
973 break;
974 default:
975 llvm_unreachable("Invalid builtin function");
976 }
977 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
978 RT.getUnqualifiedType(), Qual)));
979
980 return false;
981}
982
Eric Fiselier26187502018-12-14 21:11:28 +0000983static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
984 if (checkArgCount(S, TheCall, 1))
985 return ExprError();
986
987 // Compute __builtin_launder's parameter type from the argument.
988 // The parameter type is:
989 // * The type of the argument if it's not an array or function type,
990 // Otherwise,
991 // * The decayed argument type.
992 QualType ParamTy = [&]() {
993 QualType ArgTy = TheCall->getArg(0)->getType();
994 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
995 return S.Context.getPointerType(Ty->getElementType());
996 if (ArgTy->isFunctionType()) {
997 return S.Context.getPointerType(ArgTy);
998 }
999 return ArgTy;
1000 }();
1001
1002 TheCall->setType(ParamTy);
1003
1004 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1005 if (!ParamTy->isPointerType())
1006 return 0;
1007 if (ParamTy->isFunctionPointerType())
1008 return 1;
1009 if (ParamTy->isVoidPointerType())
1010 return 2;
1011 return llvm::Optional<unsigned>{};
1012 }();
1013 if (DiagSelect.hasValue()) {
1014 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1015 << DiagSelect.getValue() << TheCall->getSourceRange();
1016 return ExprError();
1017 }
1018
1019 // We either have an incomplete class type, or we have a class template
1020 // whose instantiation has not been forced. Example:
1021 //
1022 // template <class T> struct Foo { T value; };
1023 // Foo<int> *p = nullptr;
1024 // auto *d = __builtin_launder(p);
1025 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1026 diag::err_incomplete_type))
1027 return ExprError();
1028
1029 assert(ParamTy->getPointeeType()->isObjectType() &&
1030 "Unhandled non-object pointer case");
1031
1032 InitializedEntity Entity =
1033 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1034 ExprResult Arg =
1035 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1036 if (Arg.isInvalid())
1037 return ExprError();
1038 TheCall->setArg(0, Arg.get());
1039
1040 return TheCall;
1041}
1042
Aaron Ballman68d50642018-06-19 14:53:20 +00001043// Emit an error and return true if the current architecture is not in the list
1044// of supported architectures.
1045static bool
1046CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1047 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1048 llvm::Triple::ArchType CurArch =
1049 S.getASTContext().getTargetInfo().getTriple().getArch();
1050 if (llvm::is_contained(SupportedArchs, CurArch))
1051 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001052 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +00001053 << TheCall->getSourceRange();
1054 return true;
1055}
1056
1057ExprResult
1058Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1059 CallExpr *TheCall) {
1060 ExprResult TheCallResult(TheCall);
1061
1062 // Find out if any arguments are required to be integer constant expressions.
1063 unsigned ICEArguments = 0;
1064 ASTContext::GetBuiltinTypeError Error;
1065 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1066 if (Error != ASTContext::GE_None)
1067 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
Fangrui Song6907ce22018-07-30 19:24:48 +00001068
Aaron Ballman68d50642018-06-19 14:53:20 +00001069 // If any arguments are required to be ICE's, check and diagnose.
1070 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1071 // Skip arguments not required to be ICE's.
1072 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001073
Aaron Ballman68d50642018-06-19 14:53:20 +00001074 llvm::APSInt Result;
1075 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1076 return true;
1077 ICEArguments &= ~(1 << ArgNo);
1078 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001079
Aaron Ballman68d50642018-06-19 14:53:20 +00001080 switch (BuiltinID) {
1081 case Builtin::BI__builtin___CFStringMakeConstantString:
1082 assert(TheCall->getNumArgs() == 1 &&
1083 "Wrong # arguments to builtin CFStringMakeConstantString");
1084 if (CheckObjCString(TheCall->getArg(0)))
1085 return ExprError();
1086 break;
1087 case Builtin::BI__builtin_ms_va_start:
1088 case Builtin::BI__builtin_stdarg_start:
1089 case Builtin::BI__builtin_va_start:
1090 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1091 return ExprError();
1092 break;
1093 case Builtin::BI__va_start: {
1094 switch (Context.getTargetInfo().getTriple().getArch()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +00001095 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +00001096 case llvm::Triple::arm:
1097 case llvm::Triple::thumb:
1098 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1099 return ExprError();
1100 break;
1101 default:
1102 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1103 return ExprError();
1104 break;
1105 }
1106 break;
1107 }
1108
1109 // The acquire, release, and no fence variants are ARM and AArch64 only.
1110 case Builtin::BI_interlockedbittestandset_acq:
1111 case Builtin::BI_interlockedbittestandset_rel:
1112 case Builtin::BI_interlockedbittestandset_nf:
1113 case Builtin::BI_interlockedbittestandreset_acq:
1114 case Builtin::BI_interlockedbittestandreset_rel:
1115 case Builtin::BI_interlockedbittestandreset_nf:
1116 if (CheckBuiltinTargetSupport(
1117 *this, BuiltinID, TheCall,
1118 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1119 return ExprError();
1120 break;
1121
1122 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1123 case Builtin::BI_bittest64:
1124 case Builtin::BI_bittestandcomplement64:
1125 case Builtin::BI_bittestandreset64:
1126 case Builtin::BI_bittestandset64:
1127 case Builtin::BI_interlockedbittestandreset64:
1128 case Builtin::BI_interlockedbittestandset64:
1129 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1130 {llvm::Triple::x86_64, llvm::Triple::arm,
1131 llvm::Triple::thumb, llvm::Triple::aarch64}))
1132 return ExprError();
1133 break;
1134
1135 case Builtin::BI__builtin_isgreater:
1136 case Builtin::BI__builtin_isgreaterequal:
1137 case Builtin::BI__builtin_isless:
1138 case Builtin::BI__builtin_islessequal:
1139 case Builtin::BI__builtin_islessgreater:
1140 case Builtin::BI__builtin_isunordered:
1141 if (SemaBuiltinUnorderedCompare(TheCall))
1142 return ExprError();
1143 break;
1144 case Builtin::BI__builtin_fpclassify:
1145 if (SemaBuiltinFPClassification(TheCall, 6))
1146 return ExprError();
1147 break;
1148 case Builtin::BI__builtin_isfinite:
1149 case Builtin::BI__builtin_isinf:
1150 case Builtin::BI__builtin_isinf_sign:
1151 case Builtin::BI__builtin_isnan:
1152 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00001153 case Builtin::BI__builtin_signbit:
1154 case Builtin::BI__builtin_signbitf:
1155 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +00001156 if (SemaBuiltinFPClassification(TheCall, 1))
1157 return ExprError();
1158 break;
1159 case Builtin::BI__builtin_shufflevector:
1160 return SemaBuiltinShuffleVector(TheCall);
1161 // TheCall will be freed by the smart pointer here, but that's fine, since
1162 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1163 case Builtin::BI__builtin_prefetch:
1164 if (SemaBuiltinPrefetch(TheCall))
1165 return ExprError();
1166 break;
1167 case Builtin::BI__builtin_alloca_with_align:
1168 if (SemaBuiltinAllocaWithAlign(TheCall))
1169 return ExprError();
1170 break;
1171 case Builtin::BI__assume:
1172 case Builtin::BI__builtin_assume:
1173 if (SemaBuiltinAssume(TheCall))
1174 return ExprError();
1175 break;
1176 case Builtin::BI__builtin_assume_aligned:
1177 if (SemaBuiltinAssumeAligned(TheCall))
1178 return ExprError();
1179 break;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00001180 case Builtin::BI__builtin_dynamic_object_size:
Aaron Ballman68d50642018-06-19 14:53:20 +00001181 case Builtin::BI__builtin_object_size:
1182 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1183 return ExprError();
1184 break;
1185 case Builtin::BI__builtin_longjmp:
1186 if (SemaBuiltinLongjmp(TheCall))
1187 return ExprError();
1188 break;
1189 case Builtin::BI__builtin_setjmp:
1190 if (SemaBuiltinSetjmp(TheCall))
1191 return ExprError();
1192 break;
1193 case Builtin::BI_setjmp:
1194 case Builtin::BI_setjmpex:
1195 if (checkArgCount(*this, TheCall, 1))
1196 return true;
1197 break;
1198 case Builtin::BI__builtin_classify_type:
1199 if (checkArgCount(*this, TheCall, 1)) return true;
1200 TheCall->setType(Context.IntTy);
1201 break;
Jorge Gorbe Moya1dbd42ab2019-04-27 00:32:04 +00001202 case Builtin::BI__builtin_constant_p:
Aaron Ballman68d50642018-06-19 14:53:20 +00001203 if (checkArgCount(*this, TheCall, 1)) return true;
1204 TheCall->setType(Context.IntTy);
1205 break;
Eric Fiselier26187502018-12-14 21:11:28 +00001206 case Builtin::BI__builtin_launder:
1207 return SemaBuiltinLaunder(*this, TheCall);
Aaron Ballman68d50642018-06-19 14:53:20 +00001208 case Builtin::BI__sync_fetch_and_add:
1209 case Builtin::BI__sync_fetch_and_add_1:
1210 case Builtin::BI__sync_fetch_and_add_2:
1211 case Builtin::BI__sync_fetch_and_add_4:
1212 case Builtin::BI__sync_fetch_and_add_8:
1213 case Builtin::BI__sync_fetch_and_add_16:
1214 case Builtin::BI__sync_fetch_and_sub:
1215 case Builtin::BI__sync_fetch_and_sub_1:
1216 case Builtin::BI__sync_fetch_and_sub_2:
1217 case Builtin::BI__sync_fetch_and_sub_4:
1218 case Builtin::BI__sync_fetch_and_sub_8:
1219 case Builtin::BI__sync_fetch_and_sub_16:
1220 case Builtin::BI__sync_fetch_and_or:
1221 case Builtin::BI__sync_fetch_and_or_1:
1222 case Builtin::BI__sync_fetch_and_or_2:
1223 case Builtin::BI__sync_fetch_and_or_4:
1224 case Builtin::BI__sync_fetch_and_or_8:
1225 case Builtin::BI__sync_fetch_and_or_16:
1226 case Builtin::BI__sync_fetch_and_and:
1227 case Builtin::BI__sync_fetch_and_and_1:
1228 case Builtin::BI__sync_fetch_and_and_2:
1229 case Builtin::BI__sync_fetch_and_and_4:
1230 case Builtin::BI__sync_fetch_and_and_8:
1231 case Builtin::BI__sync_fetch_and_and_16:
1232 case Builtin::BI__sync_fetch_and_xor:
1233 case Builtin::BI__sync_fetch_and_xor_1:
1234 case Builtin::BI__sync_fetch_and_xor_2:
1235 case Builtin::BI__sync_fetch_and_xor_4:
1236 case Builtin::BI__sync_fetch_and_xor_8:
1237 case Builtin::BI__sync_fetch_and_xor_16:
1238 case Builtin::BI__sync_fetch_and_nand:
1239 case Builtin::BI__sync_fetch_and_nand_1:
1240 case Builtin::BI__sync_fetch_and_nand_2:
1241 case Builtin::BI__sync_fetch_and_nand_4:
1242 case Builtin::BI__sync_fetch_and_nand_8:
1243 case Builtin::BI__sync_fetch_and_nand_16:
1244 case Builtin::BI__sync_add_and_fetch:
1245 case Builtin::BI__sync_add_and_fetch_1:
1246 case Builtin::BI__sync_add_and_fetch_2:
1247 case Builtin::BI__sync_add_and_fetch_4:
1248 case Builtin::BI__sync_add_and_fetch_8:
1249 case Builtin::BI__sync_add_and_fetch_16:
1250 case Builtin::BI__sync_sub_and_fetch:
1251 case Builtin::BI__sync_sub_and_fetch_1:
1252 case Builtin::BI__sync_sub_and_fetch_2:
1253 case Builtin::BI__sync_sub_and_fetch_4:
1254 case Builtin::BI__sync_sub_and_fetch_8:
1255 case Builtin::BI__sync_sub_and_fetch_16:
1256 case Builtin::BI__sync_and_and_fetch:
1257 case Builtin::BI__sync_and_and_fetch_1:
1258 case Builtin::BI__sync_and_and_fetch_2:
1259 case Builtin::BI__sync_and_and_fetch_4:
1260 case Builtin::BI__sync_and_and_fetch_8:
1261 case Builtin::BI__sync_and_and_fetch_16:
1262 case Builtin::BI__sync_or_and_fetch:
1263 case Builtin::BI__sync_or_and_fetch_1:
1264 case Builtin::BI__sync_or_and_fetch_2:
1265 case Builtin::BI__sync_or_and_fetch_4:
1266 case Builtin::BI__sync_or_and_fetch_8:
1267 case Builtin::BI__sync_or_and_fetch_16:
1268 case Builtin::BI__sync_xor_and_fetch:
1269 case Builtin::BI__sync_xor_and_fetch_1:
1270 case Builtin::BI__sync_xor_and_fetch_2:
1271 case Builtin::BI__sync_xor_and_fetch_4:
1272 case Builtin::BI__sync_xor_and_fetch_8:
1273 case Builtin::BI__sync_xor_and_fetch_16:
1274 case Builtin::BI__sync_nand_and_fetch:
1275 case Builtin::BI__sync_nand_and_fetch_1:
1276 case Builtin::BI__sync_nand_and_fetch_2:
1277 case Builtin::BI__sync_nand_and_fetch_4:
1278 case Builtin::BI__sync_nand_and_fetch_8:
1279 case Builtin::BI__sync_nand_and_fetch_16:
1280 case Builtin::BI__sync_val_compare_and_swap:
1281 case Builtin::BI__sync_val_compare_and_swap_1:
1282 case Builtin::BI__sync_val_compare_and_swap_2:
1283 case Builtin::BI__sync_val_compare_and_swap_4:
1284 case Builtin::BI__sync_val_compare_and_swap_8:
1285 case Builtin::BI__sync_val_compare_and_swap_16:
1286 case Builtin::BI__sync_bool_compare_and_swap:
1287 case Builtin::BI__sync_bool_compare_and_swap_1:
1288 case Builtin::BI__sync_bool_compare_and_swap_2:
1289 case Builtin::BI__sync_bool_compare_and_swap_4:
1290 case Builtin::BI__sync_bool_compare_and_swap_8:
1291 case Builtin::BI__sync_bool_compare_and_swap_16:
1292 case Builtin::BI__sync_lock_test_and_set:
1293 case Builtin::BI__sync_lock_test_and_set_1:
1294 case Builtin::BI__sync_lock_test_and_set_2:
1295 case Builtin::BI__sync_lock_test_and_set_4:
1296 case Builtin::BI__sync_lock_test_and_set_8:
1297 case Builtin::BI__sync_lock_test_and_set_16:
1298 case Builtin::BI__sync_lock_release:
1299 case Builtin::BI__sync_lock_release_1:
1300 case Builtin::BI__sync_lock_release_2:
1301 case Builtin::BI__sync_lock_release_4:
1302 case Builtin::BI__sync_lock_release_8:
1303 case Builtin::BI__sync_lock_release_16:
1304 case Builtin::BI__sync_swap:
1305 case Builtin::BI__sync_swap_1:
1306 case Builtin::BI__sync_swap_2:
1307 case Builtin::BI__sync_swap_4:
1308 case Builtin::BI__sync_swap_8:
1309 case Builtin::BI__sync_swap_16:
1310 return SemaBuiltinAtomicOverloaded(TheCallResult);
JF Bastiene77b48b2018-09-10 20:42:56 +00001311 case Builtin::BI__sync_synchronize:
1312 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1313 << TheCall->getCallee()->getSourceRange();
1314 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001315 case Builtin::BI__builtin_nontemporal_load:
1316 case Builtin::BI__builtin_nontemporal_store:
1317 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1318#define BUILTIN(ID, TYPE, ATTRS)
1319#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1320 case Builtin::BI##ID: \
1321 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1322#include "clang/Basic/Builtins.def"
1323 case Builtin::BI__annotation:
1324 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1325 return ExprError();
1326 break;
1327 case Builtin::BI__builtin_annotation:
1328 if (SemaBuiltinAnnotation(*this, TheCall))
1329 return ExprError();
1330 break;
1331 case Builtin::BI__builtin_addressof:
1332 if (SemaBuiltinAddressof(*this, TheCall))
1333 return ExprError();
1334 break;
1335 case Builtin::BI__builtin_add_overflow:
1336 case Builtin::BI__builtin_sub_overflow:
1337 case Builtin::BI__builtin_mul_overflow:
1338 if (SemaBuiltinOverflow(*this, TheCall))
1339 return ExprError();
1340 break;
1341 case Builtin::BI__builtin_operator_new:
1342 case Builtin::BI__builtin_operator_delete: {
1343 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1344 ExprResult Res =
1345 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1346 if (Res.isInvalid())
1347 CorrectDelayedTyposInExpr(TheCallResult.get());
1348 return Res;
1349 }
1350 case Builtin::BI__builtin_dump_struct: {
1351 // We first want to ensure we are called with 2 arguments
1352 if (checkArgCount(*this, TheCall, 2))
1353 return ExprError();
1354 // Ensure that the first argument is of type 'struct XX *'
1355 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1356 const QualType PtrArgType = PtrArg->getType();
1357 if (!PtrArgType->isPointerType() ||
1358 !PtrArgType->getPointeeType()->isRecordType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001359 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001360 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1361 << "structure pointer";
1362 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001363 }
1364
1365 // Ensure that the second argument is of type 'FunctionType'
1366 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1367 const QualType FnPtrArgType = FnPtrArg->getType();
1368 if (!FnPtrArgType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001369 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1370 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1371 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001372 return ExprError();
1373 }
1374
1375 const auto *FuncType =
1376 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1377
1378 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001379 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1380 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1381 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001382 return ExprError();
1383 }
1384
1385 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1386 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001387 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001388 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1389 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1390 return ExprError();
1391 }
1392 QualType PT = FT->getParamType(0);
1393 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1394 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1395 !PT->getPointeeType().isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001396 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001397 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1398 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1399 return ExprError();
1400 }
1401 }
1402
1403 TheCall->setType(Context.IntTy);
1404 break;
1405 }
Peter Collingbournef7706832014-12-12 23:41:25 +00001406 case Builtin::BI__builtin_call_with_static_chain:
1407 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1408 return ExprError();
1409 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001410 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001411 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001412 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1413 diag::err_seh___except_block))
1414 return ExprError();
1415 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001416 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001417 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001418 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1419 diag::err_seh___except_filter))
1420 return ExprError();
1421 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001422 case Builtin::BI__GetExceptionInfo:
1423 if (checkArgCount(*this, TheCall, 1))
1424 return ExprError();
1425
1426 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001427 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001428 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1429 TheCall))
1430 return ExprError();
1431
1432 TheCall->setType(Context.VoidPtrTy);
1433 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001434 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001435 case Builtin::BIread_pipe:
1436 case Builtin::BIwrite_pipe:
1437 // Since those two functions are declared with var args, we need a semantic
1438 // check for the argument.
1439 if (SemaBuiltinRWPipe(*this, TheCall))
1440 return ExprError();
1441 break;
1442 case Builtin::BIreserve_read_pipe:
1443 case Builtin::BIreserve_write_pipe:
1444 case Builtin::BIwork_group_reserve_read_pipe:
1445 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001446 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1447 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001448 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001449 case Builtin::BIsub_group_reserve_read_pipe:
1450 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001451 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1452 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001453 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001454 break;
1455 case Builtin::BIcommit_read_pipe:
1456 case Builtin::BIcommit_write_pipe:
1457 case Builtin::BIwork_group_commit_read_pipe:
1458 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001459 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1460 return ExprError();
1461 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001462 case Builtin::BIsub_group_commit_read_pipe:
1463 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001464 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1465 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001466 return ExprError();
1467 break;
1468 case Builtin::BIget_pipe_num_packets:
1469 case Builtin::BIget_pipe_max_packets:
1470 if (SemaBuiltinPipePackets(*this, TheCall))
1471 return ExprError();
1472 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001473 case Builtin::BIto_global:
1474 case Builtin::BIto_local:
1475 case Builtin::BIto_private:
1476 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1477 return ExprError();
1478 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001479 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1480 case Builtin::BIenqueue_kernel:
1481 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1482 return ExprError();
1483 break;
1484 case Builtin::BIget_kernel_work_group_size:
1485 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1486 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1487 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001488 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001489 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1490 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1491 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1492 return ExprError();
1493 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001494 case Builtin::BI__builtin_os_log_format:
1495 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001496 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001497 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001498 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001499 }
Richard Smith760520b2014-06-03 23:27:44 +00001500
Nate Begeman4904e322010-06-08 02:47:44 +00001501 // Since the target specific builtins for each arch overlap, only check those
1502 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001503 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001504 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001505 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001506 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001507 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001508 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001509 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1510 return ExprError();
1511 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001512 case llvm::Triple::aarch64:
1513 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001514 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001515 return ExprError();
1516 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001517 case llvm::Triple::hexagon:
1518 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1519 return ExprError();
1520 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001521 case llvm::Triple::mips:
1522 case llvm::Triple::mipsel:
1523 case llvm::Triple::mips64:
1524 case llvm::Triple::mips64el:
1525 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1526 return ExprError();
1527 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001528 case llvm::Triple::systemz:
1529 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1530 return ExprError();
1531 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001532 case llvm::Triple::x86:
1533 case llvm::Triple::x86_64:
1534 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1535 return ExprError();
1536 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001537 case llvm::Triple::ppc:
1538 case llvm::Triple::ppc64:
1539 case llvm::Triple::ppc64le:
1540 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1541 return ExprError();
1542 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001543 default:
1544 break;
1545 }
1546 }
1547
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001548 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001549}
1550
Nate Begeman91e1fea2010-06-14 05:21:25 +00001551// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001552static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001553 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001554 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001555 switch (Type.getEltType()) {
1556 case NeonTypeFlags::Int8:
1557 case NeonTypeFlags::Poly8:
1558 return shift ? 7 : (8 << IsQuad) - 1;
1559 case NeonTypeFlags::Int16:
1560 case NeonTypeFlags::Poly16:
1561 return shift ? 15 : (4 << IsQuad) - 1;
1562 case NeonTypeFlags::Int32:
1563 return shift ? 31 : (2 << IsQuad) - 1;
1564 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001565 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001566 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001567 case NeonTypeFlags::Poly128:
1568 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001569 case NeonTypeFlags::Float16:
1570 assert(!shift && "cannot shift float types!");
1571 return (4 << IsQuad) - 1;
1572 case NeonTypeFlags::Float32:
1573 assert(!shift && "cannot shift float types!");
1574 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001575 case NeonTypeFlags::Float64:
1576 assert(!shift && "cannot shift float types!");
1577 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001578 }
David Blaikie8a40f702012-01-17 06:56:22 +00001579 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001580}
1581
Bob Wilsone4d77232011-11-08 05:04:11 +00001582/// getNeonEltType - Return the QualType corresponding to the elements of
1583/// the vector type specified by the NeonTypeFlags. This is used to check
1584/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001585static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001586 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001587 switch (Flags.getEltType()) {
1588 case NeonTypeFlags::Int8:
1589 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1590 case NeonTypeFlags::Int16:
1591 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1592 case NeonTypeFlags::Int32:
1593 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1594 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001595 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001596 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1597 else
1598 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1599 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001600 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001601 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001602 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001603 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001604 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001605 if (IsInt64Long)
1606 return Context.UnsignedLongTy;
1607 else
1608 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001609 case NeonTypeFlags::Poly128:
1610 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001611 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001612 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001613 case NeonTypeFlags::Float32:
1614 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001615 case NeonTypeFlags::Float64:
1616 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001617 }
David Blaikie8a40f702012-01-17 06:56:22 +00001618 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001619}
1620
Tim Northover12670412014-02-19 10:37:05 +00001621bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001622 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001623 uint64_t mask = 0;
1624 unsigned TV = 0;
1625 int PtrArgNum = -1;
1626 bool HasConstPtr = false;
1627 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001628#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001629#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001630#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001631#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001632 }
1633
1634 // For NEON intrinsics which are overloaded on vector element type, validate
1635 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001636 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001637 if (mask) {
1638 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1639 return true;
1640
1641 TV = Result.getLimitedValue(64);
1642 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001643 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1644 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001645 }
1646
1647 if (PtrArgNum >= 0) {
1648 // Check that pointer arguments have the specified type.
1649 Expr *Arg = TheCall->getArg(PtrArgNum);
1650 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1651 Arg = ICE->getSubExpr();
1652 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1653 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001654
Tim Northovera2ee4332014-03-29 15:09:45 +00001655 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001656 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1657 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001658 bool IsInt64Long =
1659 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1660 QualType EltTy =
1661 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001662 if (HasConstPtr)
1663 EltTy = EltTy.withConst();
1664 QualType LHSTy = Context.getPointerType(EltTy);
1665 AssignConvertType ConvTy;
1666 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1667 if (RHS.isInvalid())
1668 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001669 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001670 RHS.get(), AA_Assigning))
1671 return true;
1672 }
1673
1674 // For NEON intrinsics which take an immediate value as part of the
1675 // instruction, range check them here.
1676 unsigned i = 0, l = 0, u = 0;
1677 switch (BuiltinID) {
1678 default:
1679 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001680 #define GET_NEON_IMMEDIATE_CHECK
1681 #include "clang/Basic/arm_neon.inc"
1682 #include "clang/Basic/arm_fp16.inc"
1683 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001684 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001685
Richard Sandiford28940af2014-04-16 08:47:51 +00001686 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001687}
1688
Tim Northovera2ee4332014-03-29 15:09:45 +00001689bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1690 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001691 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001692 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001693 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001694 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001695 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001696 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1697 BuiltinID == AArch64::BI__builtin_arm_strex ||
1698 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001699 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001700 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001701 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1702 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1703 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001704
1705 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1706
1707 // Ensure that we have the proper number of arguments.
1708 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1709 return true;
1710
1711 // Inspect the pointer argument of the atomic builtin. This should always be
1712 // a pointer type, whose element is an integral scalar or pointer type.
1713 // Because it is a pointer type, we don't have to worry about any implicit
1714 // casts here.
1715 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1716 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1717 if (PointerArgRes.isInvalid())
1718 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001719 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001720
1721 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1722 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001723 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1724 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001725 return true;
1726 }
1727
1728 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1729 // task is to insert the appropriate casts into the AST. First work out just
1730 // what the appropriate type is.
1731 QualType ValType = pointerType->getPointeeType();
1732 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1733 if (IsLdrex)
1734 AddrType.addConst();
1735
1736 // Issue a warning if the cast is dodgy.
1737 CastKind CastNeeded = CK_NoOp;
1738 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1739 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001740 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1741 << PointerArg->getType() << Context.getPointerType(AddrType)
1742 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001743 }
1744
1745 // Finally, do the cast and replace the argument with the corrected version.
1746 AddrType = Context.getPointerType(AddrType);
1747 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1748 if (PointerArgRes.isInvalid())
1749 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001750 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001751
1752 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1753
1754 // In general, we allow ints, floats and pointers to be loaded and stored.
1755 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1756 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001757 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1758 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001759 return true;
1760 }
1761
1762 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001763 if (Context.getTypeSize(ValType) > MaxWidth) {
1764 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001765 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1766 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001767 return true;
1768 }
1769
1770 switch (ValType.getObjCLifetime()) {
1771 case Qualifiers::OCL_None:
1772 case Qualifiers::OCL_ExplicitNone:
1773 // okay
1774 break;
1775
1776 case Qualifiers::OCL_Weak:
1777 case Qualifiers::OCL_Strong:
1778 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001779 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1780 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001781 return true;
1782 }
1783
Tim Northover6aacd492013-07-16 09:47:53 +00001784 if (IsLdrex) {
1785 TheCall->setType(ValType);
1786 return false;
1787 }
1788
1789 // Initialize the argument to be stored.
1790 ExprResult ValArg = TheCall->getArg(0);
1791 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1792 Context, ValType, /*consume*/ false);
1793 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1794 if (ValArg.isInvalid())
1795 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001796 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001797
1798 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1799 // but the custom checker bypasses all default analysis.
1800 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001801 return false;
1802}
1803
Nate Begeman4904e322010-06-08 02:47:44 +00001804bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001805 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001806 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1807 BuiltinID == ARM::BI__builtin_arm_strex ||
1808 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001809 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001810 }
1811
Yi Kong26d104a2014-08-13 19:18:14 +00001812 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1813 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1814 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1815 }
1816
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001817 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1818 BuiltinID == ARM::BI__builtin_arm_wsr64)
1819 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1820
1821 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1822 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1823 BuiltinID == ARM::BI__builtin_arm_wsr ||
1824 BuiltinID == ARM::BI__builtin_arm_wsrp)
1825 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1826
Tim Northover12670412014-02-19 10:37:05 +00001827 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1828 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001829
Yi Kong4efadfb2014-07-03 16:01:25 +00001830 // For intrinsics which take an immediate value as part of the instruction,
1831 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001832 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001833 switch (BuiltinID) {
1834 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001835 case ARM::BI__builtin_arm_ssat:
1836 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1837 case ARM::BI__builtin_arm_usat:
1838 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1839 case ARM::BI__builtin_arm_ssat16:
1840 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1841 case ARM::BI__builtin_arm_usat16:
1842 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001843 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001844 case ARM::BI__builtin_arm_vcvtr_d:
1845 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001846 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001847 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001848 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001849 case ARM::BI__builtin_arm_dbg:
1850 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001851 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001852}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001853
Tim Northover573cbee2014-05-24 12:52:07 +00001854bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001855 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001856 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001857 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1858 BuiltinID == AArch64::BI__builtin_arm_strex ||
1859 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001860 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1861 }
1862
Yi Konga5548432014-08-13 19:18:20 +00001863 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1864 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1865 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1866 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1867 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1868 }
1869
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001870 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1871 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001872 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001873
Javed Absar18b0c402019-04-26 21:08:11 +00001874 // Memory Tagging Extensions (MTE) Intrinsics
1875 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1876 BuiltinID == AArch64::BI__builtin_arm_addg ||
1877 BuiltinID == AArch64::BI__builtin_arm_gmi ||
1878 BuiltinID == AArch64::BI__builtin_arm_ldg ||
1879 BuiltinID == AArch64::BI__builtin_arm_stg ||
1880 BuiltinID == AArch64::BI__builtin_arm_subp) {
1881 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1882 }
1883
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001884 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1885 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1886 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1887 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1888 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1889
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001890 // Only check the valid encoding range. Any constant in this range would be
1891 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1892 // an exception for incorrect registers. This matches MSVC behavior.
1893 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1894 BuiltinID == AArch64::BI_WriteStatusReg)
1895 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1896
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001897 if (BuiltinID == AArch64::BI__getReg)
1898 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1899
Tim Northovera2ee4332014-03-29 15:09:45 +00001900 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1901 return true;
1902
Yi Kong19a29ac2014-07-17 10:52:06 +00001903 // For intrinsics which take an immediate value as part of the instruction,
1904 // range check them here.
1905 unsigned i = 0, l = 0, u = 0;
1906 switch (BuiltinID) {
1907 default: return false;
1908 case AArch64::BI__builtin_arm_dmb:
1909 case AArch64::BI__builtin_arm_dsb:
1910 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1911 }
1912
Yi Kong19a29ac2014-07-17 10:52:06 +00001913 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001914}
1915
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001916bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001917 struct BuiltinAndString {
1918 unsigned BuiltinID;
1919 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001920 };
1921
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001922 static BuiltinAndString ValidCPU[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001923 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1924 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1925 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1926 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1927 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1928 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1929 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1930 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1940 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1941 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1942 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1943 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1944 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1945 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001946 };
1947
1948 static BuiltinAndString ValidHVX[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001949 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1950 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1951 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1952 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1953 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1954 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1955 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1956 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1957 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1958 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1959 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1960 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1961 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1962 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1963 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1964 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1965 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1966 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1967 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1968 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1969 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1970 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1971 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1972 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1973 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1974 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1975 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1976 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002517 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002521 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2553 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2554 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2555 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2556 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2557 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2558 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2559 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2560 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2561 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2562 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2563 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2564 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2565 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2566 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2567 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2568 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2569 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2570 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2571 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2572 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2573 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2574 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2575 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2576 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2577 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2578 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2579 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2580 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2581 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2582 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2583 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2584 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2585 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2586 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2587 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2588 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2589 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2590 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2591 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2592 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2593 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2594 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2595 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2596 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2597 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2598 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2599 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2600 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2601 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2602 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2603 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2604 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2605 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2606 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2607 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2608 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2609 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2610 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2611 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2612 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2613 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2614 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2615 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2616 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2617 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2618 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2619 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2620 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2621 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2622 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2623 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2624 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2625 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2626 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2627 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2628 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2629 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2643 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2644 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2645 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2646 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2647 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2648 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2649 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2650 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2651 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2652 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2653 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2654 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2655 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2656 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2657 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2658 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2659 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2660 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2661 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2662 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2663 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2664 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2665 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2666 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2667 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2668 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2669 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2670 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2671 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2672 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2673 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2674 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2675 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2676 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2677 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2678 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2679 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2680 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002681 };
2682
2683 // Sort the tables on first execution so we can binary search them.
2684 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2685 return LHS.BuiltinID < RHS.BuiltinID;
2686 };
2687 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002688 (llvm::sort(ValidCPU, SortCmp),
2689 llvm::sort(ValidHVX, SortCmp), true);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002690 (void)SortOnce;
2691 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2692 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002693 };
2694
2695 const TargetInfo &TI = Context.getTargetInfo();
2696
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002697 const BuiltinAndString *FC =
2698 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2699 LowerBoundCmp);
2700 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002701 const TargetOptions &Opts = TI.getTargetOpts();
2702 StringRef CPU = Opts.CPU;
2703 if (!CPU.empty()) {
2704 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2705 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002706 SmallVector<StringRef, 3> CPUs;
2707 StringRef(FC->Str).split(CPUs, ',');
2708 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002710 diag::err_hexagon_builtin_unsupported_cpu);
2711 }
2712 }
2713
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002714 const BuiltinAndString *FH =
2715 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2716 LowerBoundCmp);
2717 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002718 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002719 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002720 diag::err_hexagon_builtin_requires_hvx);
2721
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002722 SmallVector<StringRef, 3> HVXs;
2723 StringRef(FH->Str).split(HVXs, ',');
2724 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002725 [&TI] (StringRef V) {
2726 std::string F = "hvx" + V.str();
2727 return TI.hasFeature(F);
2728 });
2729 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002730 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002731 diag::err_hexagon_builtin_unsupported_hvx);
2732 }
2733
2734 return false;
2735}
2736
2737bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002738 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002739 uint8_t OpNum;
2740 bool IsSigned;
2741 uint8_t BitWidth;
2742 uint8_t Align;
2743 };
2744 struct BuiltinInfo {
2745 unsigned BuiltinID;
2746 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002747 };
2748
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002749 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002750 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2751 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2752 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2753 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2754 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2755 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2756 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2757 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2758 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2759 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2760 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2761
2762 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2763 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2764 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2765 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2766 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2767 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2768 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2769 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2770 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2771 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2772 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2773
2774 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2775 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2776 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2777 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2778 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2779 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2780 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2781 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2782 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2783 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2784 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2785 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2787 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2790 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2791 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2792 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2793 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2795 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2796 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2797 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2798 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2799 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2804 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2826 {{ 1, false, 6, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2834 {{ 1, false, 5, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2841 { 2, false, 5, 0 }} },
2842 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2843 { 2, false, 6, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2845 { 3, false, 5, 0 }} },
2846 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2847 { 3, false, 6, 0 }} },
2848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2864 {{ 2, false, 4, 0 },
2865 { 3, false, 5, 0 }} },
2866 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2867 {{ 2, false, 4, 0 },
2868 { 3, false, 5, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2870 {{ 2, false, 4, 0 },
2871 { 3, false, 5, 0 }} },
2872 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2873 {{ 2, false, 4, 0 },
2874 { 3, false, 5, 0 }} },
2875 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2876 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2878 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2879 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2881 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2882 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2886 { 2, false, 5, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2888 { 2, false, 6, 0 }} },
2889 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2890 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2892 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2893 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2894 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2895 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2896 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2898 {{ 1, false, 4, 0 }} },
2899 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2900 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2901 {{ 1, false, 4, 0 }} },
2902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2910 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2914 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2915 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2916 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2917 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2918 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2921 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2922 {{ 3, false, 1, 0 }} },
2923 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2924 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2925 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2926 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2927 {{ 3, false, 1, 0 }} },
2928 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2929 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2930 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2931 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2932 {{ 3, false, 1, 0 }} },
2933 };
2934
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002935 // Use a dynamically initialized static to sort the table exactly once on
2936 // first run.
2937 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002938 (llvm::sort(Infos,
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002939 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2940 return LHS.BuiltinID < RHS.BuiltinID;
2941 }),
2942 true);
2943 (void)SortOnce;
2944
2945 const BuiltinInfo *F =
2946 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2947 [](const BuiltinInfo &BI, unsigned BuiltinID) {
2948 return BI.BuiltinID < BuiltinID;
2949 });
2950 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002951 return false;
2952
2953 bool Error = false;
2954
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002955 for (const ArgInfo &A : F->Infos) {
2956 // Ignore empty ArgInfo elements.
2957 if (A.BitWidth == 0)
2958 continue;
2959
2960 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2961 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002962 if (!A.Align) {
2963 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2964 } else {
2965 unsigned M = 1 << A.Align;
2966 Min *= M;
2967 Max *= M;
2968 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2969 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2970 }
2971 }
2972 return Error;
2973}
2974
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002975bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2976 CallExpr *TheCall) {
2977 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2978 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2979}
2980
2981
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002982// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2983// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2984// ordering for DSP is unspecified. MSA is ordered by the data format used
2985// by the underlying instruction i.e., df/m, df/n and then by size.
2986//
2987// FIXME: The size tests here should instead be tablegen'd along with the
2988// definitions from include/clang/Basic/BuiltinsMips.def.
2989// FIXME: GCC is strict on signedness for some of these intrinsics, we should
2990// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002991bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002992 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002993 switch (BuiltinID) {
2994 default: return false;
2995 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2996 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00002997 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2998 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2999 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3000 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3001 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003002 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003003 // df/m field.
3004 // These intrinsics take an unsigned 3 bit immediate.
3005 case Mips::BI__builtin_msa_bclri_b:
3006 case Mips::BI__builtin_msa_bnegi_b:
3007 case Mips::BI__builtin_msa_bseti_b:
3008 case Mips::BI__builtin_msa_sat_s_b:
3009 case Mips::BI__builtin_msa_sat_u_b:
3010 case Mips::BI__builtin_msa_slli_b:
3011 case Mips::BI__builtin_msa_srai_b:
3012 case Mips::BI__builtin_msa_srari_b:
3013 case Mips::BI__builtin_msa_srli_b:
3014 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3015 case Mips::BI__builtin_msa_binsli_b:
3016 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3017 // These intrinsics take an unsigned 4 bit immediate.
3018 case Mips::BI__builtin_msa_bclri_h:
3019 case Mips::BI__builtin_msa_bnegi_h:
3020 case Mips::BI__builtin_msa_bseti_h:
3021 case Mips::BI__builtin_msa_sat_s_h:
3022 case Mips::BI__builtin_msa_sat_u_h:
3023 case Mips::BI__builtin_msa_slli_h:
3024 case Mips::BI__builtin_msa_srai_h:
3025 case Mips::BI__builtin_msa_srari_h:
3026 case Mips::BI__builtin_msa_srli_h:
3027 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3028 case Mips::BI__builtin_msa_binsli_h:
3029 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003030 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003031 // The first block of intrinsics actually have an unsigned 5 bit field,
3032 // not a df/n field.
3033 case Mips::BI__builtin_msa_clei_u_b:
3034 case Mips::BI__builtin_msa_clei_u_h:
3035 case Mips::BI__builtin_msa_clei_u_w:
3036 case Mips::BI__builtin_msa_clei_u_d:
3037 case Mips::BI__builtin_msa_clti_u_b:
3038 case Mips::BI__builtin_msa_clti_u_h:
3039 case Mips::BI__builtin_msa_clti_u_w:
3040 case Mips::BI__builtin_msa_clti_u_d:
3041 case Mips::BI__builtin_msa_maxi_u_b:
3042 case Mips::BI__builtin_msa_maxi_u_h:
3043 case Mips::BI__builtin_msa_maxi_u_w:
3044 case Mips::BI__builtin_msa_maxi_u_d:
3045 case Mips::BI__builtin_msa_mini_u_b:
3046 case Mips::BI__builtin_msa_mini_u_h:
3047 case Mips::BI__builtin_msa_mini_u_w:
3048 case Mips::BI__builtin_msa_mini_u_d:
3049 case Mips::BI__builtin_msa_addvi_b:
3050 case Mips::BI__builtin_msa_addvi_h:
3051 case Mips::BI__builtin_msa_addvi_w:
3052 case Mips::BI__builtin_msa_addvi_d:
3053 case Mips::BI__builtin_msa_bclri_w:
3054 case Mips::BI__builtin_msa_bnegi_w:
3055 case Mips::BI__builtin_msa_bseti_w:
3056 case Mips::BI__builtin_msa_sat_s_w:
3057 case Mips::BI__builtin_msa_sat_u_w:
3058 case Mips::BI__builtin_msa_slli_w:
3059 case Mips::BI__builtin_msa_srai_w:
3060 case Mips::BI__builtin_msa_srari_w:
3061 case Mips::BI__builtin_msa_srli_w:
3062 case Mips::BI__builtin_msa_srlri_w:
3063 case Mips::BI__builtin_msa_subvi_b:
3064 case Mips::BI__builtin_msa_subvi_h:
3065 case Mips::BI__builtin_msa_subvi_w:
3066 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3067 case Mips::BI__builtin_msa_binsli_w:
3068 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3069 // These intrinsics take an unsigned 6 bit immediate.
3070 case Mips::BI__builtin_msa_bclri_d:
3071 case Mips::BI__builtin_msa_bnegi_d:
3072 case Mips::BI__builtin_msa_bseti_d:
3073 case Mips::BI__builtin_msa_sat_s_d:
3074 case Mips::BI__builtin_msa_sat_u_d:
3075 case Mips::BI__builtin_msa_slli_d:
3076 case Mips::BI__builtin_msa_srai_d:
3077 case Mips::BI__builtin_msa_srari_d:
3078 case Mips::BI__builtin_msa_srli_d:
3079 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3080 case Mips::BI__builtin_msa_binsli_d:
3081 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3082 // These intrinsics take a signed 5 bit immediate.
3083 case Mips::BI__builtin_msa_ceqi_b:
3084 case Mips::BI__builtin_msa_ceqi_h:
3085 case Mips::BI__builtin_msa_ceqi_w:
3086 case Mips::BI__builtin_msa_ceqi_d:
3087 case Mips::BI__builtin_msa_clti_s_b:
3088 case Mips::BI__builtin_msa_clti_s_h:
3089 case Mips::BI__builtin_msa_clti_s_w:
3090 case Mips::BI__builtin_msa_clti_s_d:
3091 case Mips::BI__builtin_msa_clei_s_b:
3092 case Mips::BI__builtin_msa_clei_s_h:
3093 case Mips::BI__builtin_msa_clei_s_w:
3094 case Mips::BI__builtin_msa_clei_s_d:
3095 case Mips::BI__builtin_msa_maxi_s_b:
3096 case Mips::BI__builtin_msa_maxi_s_h:
3097 case Mips::BI__builtin_msa_maxi_s_w:
3098 case Mips::BI__builtin_msa_maxi_s_d:
3099 case Mips::BI__builtin_msa_mini_s_b:
3100 case Mips::BI__builtin_msa_mini_s_h:
3101 case Mips::BI__builtin_msa_mini_s_w:
3102 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3103 // These intrinsics take an unsigned 8 bit immediate.
3104 case Mips::BI__builtin_msa_andi_b:
3105 case Mips::BI__builtin_msa_nori_b:
3106 case Mips::BI__builtin_msa_ori_b:
3107 case Mips::BI__builtin_msa_shf_b:
3108 case Mips::BI__builtin_msa_shf_h:
3109 case Mips::BI__builtin_msa_shf_w:
3110 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3111 case Mips::BI__builtin_msa_bseli_b:
3112 case Mips::BI__builtin_msa_bmnzi_b:
3113 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3114 // df/n format
3115 // These intrinsics take an unsigned 4 bit immediate.
3116 case Mips::BI__builtin_msa_copy_s_b:
3117 case Mips::BI__builtin_msa_copy_u_b:
3118 case Mips::BI__builtin_msa_insve_b:
3119 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003120 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3121 // These intrinsics take an unsigned 3 bit immediate.
3122 case Mips::BI__builtin_msa_copy_s_h:
3123 case Mips::BI__builtin_msa_copy_u_h:
3124 case Mips::BI__builtin_msa_insve_h:
3125 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003126 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3127 // These intrinsics take an unsigned 2 bit immediate.
3128 case Mips::BI__builtin_msa_copy_s_w:
3129 case Mips::BI__builtin_msa_copy_u_w:
3130 case Mips::BI__builtin_msa_insve_w:
3131 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003132 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3133 // These intrinsics take an unsigned 1 bit immediate.
3134 case Mips::BI__builtin_msa_copy_s_d:
3135 case Mips::BI__builtin_msa_copy_u_d:
3136 case Mips::BI__builtin_msa_insve_d:
3137 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003138 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3139 // Memory offsets and immediate loads.
3140 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00003141 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003142 case Mips::BI__builtin_msa_ldi_h:
3143 case Mips::BI__builtin_msa_ldi_w:
3144 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
Aleksandar Beserminjie5921162018-11-07 11:37:05 +00003145 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3146 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3147 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3148 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3149 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3150 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3151 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3152 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003153 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003154
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003155 if (!m)
3156 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3157
3158 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3159 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003160}
3161
Kit Bartone50adcb2015-03-30 19:40:59 +00003162bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3163 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003164 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3165 BuiltinID == PPC::BI__builtin_divdeu ||
3166 BuiltinID == PPC::BI__builtin_bpermd;
3167 bool IsTarget64Bit = Context.getTargetInfo()
3168 .getTypeWidth(Context
3169 .getTargetInfo()
3170 .getIntPtrType()) == 64;
3171 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3172 BuiltinID == PPC::BI__builtin_divweu ||
3173 BuiltinID == PPC::BI__builtin_divde ||
3174 BuiltinID == PPC::BI__builtin_divdeu;
3175
3176 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003177 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3178 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003179
3180 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3181 (BuiltinID == PPC::BI__builtin_bpermd &&
3182 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003183 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003184 << TheCall->getSourceRange();
3185
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003186 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3187 if (!Context.getTargetInfo().hasFeature("vsx"))
3188 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3189 << TheCall->getSourceRange();
3190 return false;
3191 };
3192
Kit Bartone50adcb2015-03-30 19:40:59 +00003193 switch (BuiltinID) {
3194 default: return false;
3195 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3196 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3197 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3198 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3199 case PPC::BI__builtin_tbegin:
3200 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3201 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3202 case PPC::BI__builtin_tabortwc:
3203 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3204 case PPC::BI__builtin_tabortwci:
3205 case PPC::BI__builtin_tabortdci:
3206 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3207 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003208 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003209 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003210 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003211 case PPC::BI__builtin_unpack_vector_int128:
3212 return SemaVSXCheck(TheCall) ||
3213 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3214 case PPC::BI__builtin_pack_vector_int128:
3215 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003216 }
3217 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3218}
3219
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003220bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3221 CallExpr *TheCall) {
3222 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3223 Expr *Arg = TheCall->getArg(0);
3224 llvm::APSInt AbortCode(32);
3225 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3226 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003227 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003228 << Arg->getSourceRange();
3229 }
3230
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003231 // For intrinsics which take an immediate value as part of the instruction,
3232 // range check them here.
3233 unsigned i = 0, l = 0, u = 0;
3234 switch (BuiltinID) {
3235 default: return false;
3236 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3237 case SystemZ::BI__builtin_s390_verimb:
3238 case SystemZ::BI__builtin_s390_verimh:
3239 case SystemZ::BI__builtin_s390_verimf:
3240 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3241 case SystemZ::BI__builtin_s390_vfaeb:
3242 case SystemZ::BI__builtin_s390_vfaeh:
3243 case SystemZ::BI__builtin_s390_vfaef:
3244 case SystemZ::BI__builtin_s390_vfaebs:
3245 case SystemZ::BI__builtin_s390_vfaehs:
3246 case SystemZ::BI__builtin_s390_vfaefs:
3247 case SystemZ::BI__builtin_s390_vfaezb:
3248 case SystemZ::BI__builtin_s390_vfaezh:
3249 case SystemZ::BI__builtin_s390_vfaezf:
3250 case SystemZ::BI__builtin_s390_vfaezbs:
3251 case SystemZ::BI__builtin_s390_vfaezhs:
3252 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003253 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003254 case SystemZ::BI__builtin_s390_vfidb:
3255 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3256 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003257 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003258 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3259 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3260 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3261 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3262 case SystemZ::BI__builtin_s390_vstrcb:
3263 case SystemZ::BI__builtin_s390_vstrch:
3264 case SystemZ::BI__builtin_s390_vstrcf:
3265 case SystemZ::BI__builtin_s390_vstrczb:
3266 case SystemZ::BI__builtin_s390_vstrczh:
3267 case SystemZ::BI__builtin_s390_vstrczf:
3268 case SystemZ::BI__builtin_s390_vstrcbs:
3269 case SystemZ::BI__builtin_s390_vstrchs:
3270 case SystemZ::BI__builtin_s390_vstrcfs:
3271 case SystemZ::BI__builtin_s390_vstrczbs:
3272 case SystemZ::BI__builtin_s390_vstrczhs:
3273 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003274 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3275 case SystemZ::BI__builtin_s390_vfminsb:
3276 case SystemZ::BI__builtin_s390_vfmaxsb:
3277 case SystemZ::BI__builtin_s390_vfmindb:
3278 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003279 }
3280 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003281}
3282
Craig Topper5ba2c502015-11-07 08:08:31 +00003283/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3284/// This checks that the target supports __builtin_cpu_supports and
3285/// that the string argument is constant and valid.
3286static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3287 Expr *Arg = TheCall->getArg(0);
3288
3289 // Check if the argument is a string literal.
3290 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003291 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003292 << Arg->getSourceRange();
3293
3294 // Check the contents of the string.
3295 StringRef Feature =
3296 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3297 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003298 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003299 << Arg->getSourceRange();
3300 return false;
3301}
3302
Craig Topper699ae0c2017-08-10 20:28:30 +00003303/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3304/// This checks that the target supports __builtin_cpu_is and
3305/// that the string argument is constant and valid.
3306static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3307 Expr *Arg = TheCall->getArg(0);
3308
3309 // Check if the argument is a string literal.
3310 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003311 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003312 << Arg->getSourceRange();
3313
3314 // Check the contents of the string.
3315 StringRef Feature =
3316 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3317 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003318 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003319 << Arg->getSourceRange();
3320 return false;
3321}
3322
Craig Toppera7e253e2016-09-23 04:48:31 +00003323// Check if the rounding mode is legal.
3324bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3325 // Indicates if this instruction has rounding control or just SAE.
3326 bool HasRC = false;
3327
3328 unsigned ArgNum = 0;
3329 switch (BuiltinID) {
3330 default:
3331 return false;
3332 case X86::BI__builtin_ia32_vcvttsd2si32:
3333 case X86::BI__builtin_ia32_vcvttsd2si64:
3334 case X86::BI__builtin_ia32_vcvttsd2usi32:
3335 case X86::BI__builtin_ia32_vcvttsd2usi64:
3336 case X86::BI__builtin_ia32_vcvttss2si32:
3337 case X86::BI__builtin_ia32_vcvttss2si64:
3338 case X86::BI__builtin_ia32_vcvttss2usi32:
3339 case X86::BI__builtin_ia32_vcvttss2usi64:
3340 ArgNum = 1;
3341 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003342 case X86::BI__builtin_ia32_maxpd512:
3343 case X86::BI__builtin_ia32_maxps512:
3344 case X86::BI__builtin_ia32_minpd512:
3345 case X86::BI__builtin_ia32_minps512:
3346 ArgNum = 2;
3347 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003348 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3349 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3350 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3351 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3352 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3353 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3354 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3355 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3356 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3357 case X86::BI__builtin_ia32_exp2pd_mask:
3358 case X86::BI__builtin_ia32_exp2ps_mask:
3359 case X86::BI__builtin_ia32_getexppd512_mask:
3360 case X86::BI__builtin_ia32_getexpps512_mask:
3361 case X86::BI__builtin_ia32_rcp28pd_mask:
3362 case X86::BI__builtin_ia32_rcp28ps_mask:
3363 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3364 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3365 case X86::BI__builtin_ia32_vcomisd:
3366 case X86::BI__builtin_ia32_vcomiss:
3367 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3368 ArgNum = 3;
3369 break;
3370 case X86::BI__builtin_ia32_cmppd512_mask:
3371 case X86::BI__builtin_ia32_cmpps512_mask:
3372 case X86::BI__builtin_ia32_cmpsd_mask:
3373 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003374 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003375 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3376 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003377 case X86::BI__builtin_ia32_maxsd_round_mask:
3378 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003379 case X86::BI__builtin_ia32_minsd_round_mask:
3380 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003381 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3382 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3383 case X86::BI__builtin_ia32_reducepd512_mask:
3384 case X86::BI__builtin_ia32_reduceps512_mask:
3385 case X86::BI__builtin_ia32_rndscalepd_mask:
3386 case X86::BI__builtin_ia32_rndscaleps_mask:
3387 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3388 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3389 ArgNum = 4;
3390 break;
3391 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003392 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003393 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003394 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003395 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003396 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003397 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003398 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003399 case X86::BI__builtin_ia32_rangepd512_mask:
3400 case X86::BI__builtin_ia32_rangeps512_mask:
3401 case X86::BI__builtin_ia32_rangesd128_round_mask:
3402 case X86::BI__builtin_ia32_rangess128_round_mask:
3403 case X86::BI__builtin_ia32_reducesd_mask:
3404 case X86::BI__builtin_ia32_reducess_mask:
3405 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3406 case X86::BI__builtin_ia32_rndscaless_round_mask:
3407 ArgNum = 5;
3408 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003409 case X86::BI__builtin_ia32_vcvtsd2si64:
3410 case X86::BI__builtin_ia32_vcvtsd2si32:
3411 case X86::BI__builtin_ia32_vcvtsd2usi32:
3412 case X86::BI__builtin_ia32_vcvtsd2usi64:
3413 case X86::BI__builtin_ia32_vcvtss2si32:
3414 case X86::BI__builtin_ia32_vcvtss2si64:
3415 case X86::BI__builtin_ia32_vcvtss2usi32:
3416 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003417 case X86::BI__builtin_ia32_sqrtpd512:
3418 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003419 ArgNum = 1;
3420 HasRC = true;
3421 break;
Craig Topper3614b412018-06-10 06:01:42 +00003422 case X86::BI__builtin_ia32_addpd512:
3423 case X86::BI__builtin_ia32_addps512:
3424 case X86::BI__builtin_ia32_divpd512:
3425 case X86::BI__builtin_ia32_divps512:
3426 case X86::BI__builtin_ia32_mulpd512:
3427 case X86::BI__builtin_ia32_mulps512:
3428 case X86::BI__builtin_ia32_subpd512:
3429 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003430 case X86::BI__builtin_ia32_cvtsi2sd64:
3431 case X86::BI__builtin_ia32_cvtsi2ss32:
3432 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003433 case X86::BI__builtin_ia32_cvtusi2sd64:
3434 case X86::BI__builtin_ia32_cvtusi2ss32:
3435 case X86::BI__builtin_ia32_cvtusi2ss64:
3436 ArgNum = 2;
3437 HasRC = true;
3438 break;
3439 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3440 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3441 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003442 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003443 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003444 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003445 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003446 case X86::BI__builtin_ia32_cvtps2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003447 case X86::BI__builtin_ia32_cvtps2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003448 case X86::BI__builtin_ia32_cvtps2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003449 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3450 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3451 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3452 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3453 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3454 ArgNum = 3;
3455 HasRC = true;
3456 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003457 case X86::BI__builtin_ia32_addss_round_mask:
3458 case X86::BI__builtin_ia32_addsd_round_mask:
3459 case X86::BI__builtin_ia32_divss_round_mask:
3460 case X86::BI__builtin_ia32_divsd_round_mask:
3461 case X86::BI__builtin_ia32_mulss_round_mask:
3462 case X86::BI__builtin_ia32_mulsd_round_mask:
3463 case X86::BI__builtin_ia32_subss_round_mask:
3464 case X86::BI__builtin_ia32_subsd_round_mask:
3465 case X86::BI__builtin_ia32_scalefpd512_mask:
3466 case X86::BI__builtin_ia32_scalefps512_mask:
3467 case X86::BI__builtin_ia32_scalefsd_round_mask:
3468 case X86::BI__builtin_ia32_scalefss_round_mask:
3469 case X86::BI__builtin_ia32_getmantpd512_mask:
3470 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003471 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3472 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3473 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003474 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3475 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3476 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3477 case X86::BI__builtin_ia32_vfmaddss3_mask:
3478 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3479 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003480 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3481 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3482 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3483 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3484 case X86::BI__builtin_ia32_vfmaddps512_mask:
3485 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3486 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3487 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3488 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3489 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3490 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3491 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3492 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3493 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3494 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3495 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003496 ArgNum = 4;
3497 HasRC = true;
3498 break;
3499 case X86::BI__builtin_ia32_getmantsd_round_mask:
3500 case X86::BI__builtin_ia32_getmantss_round_mask:
3501 ArgNum = 5;
3502 HasRC = true;
3503 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003504 }
3505
3506 llvm::APSInt Result;
3507
3508 // We can't check the value of a dependent argument.
3509 Expr *Arg = TheCall->getArg(ArgNum);
3510 if (Arg->isTypeDependent() || Arg->isValueDependent())
3511 return false;
3512
3513 // Check constant-ness first.
3514 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3515 return true;
3516
3517 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3518 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3519 // combined with ROUND_NO_EXC.
3520 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3521 Result == 8/*ROUND_NO_EXC*/ ||
3522 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3523 return false;
3524
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003525 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3526 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003527}
3528
Craig Topperdf5beb22017-03-13 17:16:50 +00003529// Check if the gather/scatter scale is legal.
3530bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3531 CallExpr *TheCall) {
3532 unsigned ArgNum = 0;
3533 switch (BuiltinID) {
3534 default:
3535 return false;
3536 case X86::BI__builtin_ia32_gatherpfdpd:
3537 case X86::BI__builtin_ia32_gatherpfdps:
3538 case X86::BI__builtin_ia32_gatherpfqpd:
3539 case X86::BI__builtin_ia32_gatherpfqps:
3540 case X86::BI__builtin_ia32_scatterpfdpd:
3541 case X86::BI__builtin_ia32_scatterpfdps:
3542 case X86::BI__builtin_ia32_scatterpfqpd:
3543 case X86::BI__builtin_ia32_scatterpfqps:
3544 ArgNum = 3;
3545 break;
3546 case X86::BI__builtin_ia32_gatherd_pd:
3547 case X86::BI__builtin_ia32_gatherd_pd256:
3548 case X86::BI__builtin_ia32_gatherq_pd:
3549 case X86::BI__builtin_ia32_gatherq_pd256:
3550 case X86::BI__builtin_ia32_gatherd_ps:
3551 case X86::BI__builtin_ia32_gatherd_ps256:
3552 case X86::BI__builtin_ia32_gatherq_ps:
3553 case X86::BI__builtin_ia32_gatherq_ps256:
3554 case X86::BI__builtin_ia32_gatherd_q:
3555 case X86::BI__builtin_ia32_gatherd_q256:
3556 case X86::BI__builtin_ia32_gatherq_q:
3557 case X86::BI__builtin_ia32_gatherq_q256:
3558 case X86::BI__builtin_ia32_gatherd_d:
3559 case X86::BI__builtin_ia32_gatherd_d256:
3560 case X86::BI__builtin_ia32_gatherq_d:
3561 case X86::BI__builtin_ia32_gatherq_d256:
3562 case X86::BI__builtin_ia32_gather3div2df:
3563 case X86::BI__builtin_ia32_gather3div2di:
3564 case X86::BI__builtin_ia32_gather3div4df:
3565 case X86::BI__builtin_ia32_gather3div4di:
3566 case X86::BI__builtin_ia32_gather3div4sf:
3567 case X86::BI__builtin_ia32_gather3div4si:
3568 case X86::BI__builtin_ia32_gather3div8sf:
3569 case X86::BI__builtin_ia32_gather3div8si:
3570 case X86::BI__builtin_ia32_gather3siv2df:
3571 case X86::BI__builtin_ia32_gather3siv2di:
3572 case X86::BI__builtin_ia32_gather3siv4df:
3573 case X86::BI__builtin_ia32_gather3siv4di:
3574 case X86::BI__builtin_ia32_gather3siv4sf:
3575 case X86::BI__builtin_ia32_gather3siv4si:
3576 case X86::BI__builtin_ia32_gather3siv8sf:
3577 case X86::BI__builtin_ia32_gather3siv8si:
3578 case X86::BI__builtin_ia32_gathersiv8df:
3579 case X86::BI__builtin_ia32_gathersiv16sf:
3580 case X86::BI__builtin_ia32_gatherdiv8df:
3581 case X86::BI__builtin_ia32_gatherdiv16sf:
3582 case X86::BI__builtin_ia32_gathersiv8di:
3583 case X86::BI__builtin_ia32_gathersiv16si:
3584 case X86::BI__builtin_ia32_gatherdiv8di:
3585 case X86::BI__builtin_ia32_gatherdiv16si:
3586 case X86::BI__builtin_ia32_scatterdiv2df:
3587 case X86::BI__builtin_ia32_scatterdiv2di:
3588 case X86::BI__builtin_ia32_scatterdiv4df:
3589 case X86::BI__builtin_ia32_scatterdiv4di:
3590 case X86::BI__builtin_ia32_scatterdiv4sf:
3591 case X86::BI__builtin_ia32_scatterdiv4si:
3592 case X86::BI__builtin_ia32_scatterdiv8sf:
3593 case X86::BI__builtin_ia32_scatterdiv8si:
3594 case X86::BI__builtin_ia32_scattersiv2df:
3595 case X86::BI__builtin_ia32_scattersiv2di:
3596 case X86::BI__builtin_ia32_scattersiv4df:
3597 case X86::BI__builtin_ia32_scattersiv4di:
3598 case X86::BI__builtin_ia32_scattersiv4sf:
3599 case X86::BI__builtin_ia32_scattersiv4si:
3600 case X86::BI__builtin_ia32_scattersiv8sf:
3601 case X86::BI__builtin_ia32_scattersiv8si:
3602 case X86::BI__builtin_ia32_scattersiv8df:
3603 case X86::BI__builtin_ia32_scattersiv16sf:
3604 case X86::BI__builtin_ia32_scatterdiv8df:
3605 case X86::BI__builtin_ia32_scatterdiv16sf:
3606 case X86::BI__builtin_ia32_scattersiv8di:
3607 case X86::BI__builtin_ia32_scattersiv16si:
3608 case X86::BI__builtin_ia32_scatterdiv8di:
3609 case X86::BI__builtin_ia32_scatterdiv16si:
3610 ArgNum = 4;
3611 break;
3612 }
3613
3614 llvm::APSInt Result;
3615
3616 // We can't check the value of a dependent argument.
3617 Expr *Arg = TheCall->getArg(ArgNum);
3618 if (Arg->isTypeDependent() || Arg->isValueDependent())
3619 return false;
3620
3621 // Check constant-ness first.
3622 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3623 return true;
3624
3625 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3626 return false;
3627
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003628 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3629 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003630}
3631
Craig Topper51738f82018-04-26 20:14:46 +00003632static bool isX86_32Builtin(unsigned BuiltinID) {
3633 // These builtins only work on x86-32 targets.
3634 switch (BuiltinID) {
3635 case X86::BI__builtin_ia32_readeflags_u32:
3636 case X86::BI__builtin_ia32_writeeflags_u32:
3637 return true;
3638 }
3639
3640 return false;
3641}
3642
Craig Topperf0ddc892016-09-23 04:48:27 +00003643bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3644 if (BuiltinID == X86::BI__builtin_cpu_supports)
3645 return SemaBuiltinCpuSupports(*this, TheCall);
3646
Craig Topper699ae0c2017-08-10 20:28:30 +00003647 if (BuiltinID == X86::BI__builtin_cpu_is)
3648 return SemaBuiltinCpuIs(*this, TheCall);
3649
Craig Topper51738f82018-04-26 20:14:46 +00003650 // Check for 32-bit only builtins on a 64-bit target.
3651 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3652 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003653 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003654 diag::err_32_bit_builtin_64_bit_tgt);
3655
Craig Toppera7e253e2016-09-23 04:48:31 +00003656 // If the intrinsic has rounding or SAE make sure its valid.
3657 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3658 return true;
3659
Craig Topperdf5beb22017-03-13 17:16:50 +00003660 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3661 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3662 return true;
3663
Craig Topperf0ddc892016-09-23 04:48:27 +00003664 // For intrinsics which take an immediate value as part of the instruction,
3665 // range check them here.
3666 int i = 0, l = 0, u = 0;
3667 switch (BuiltinID) {
3668 default:
3669 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003670 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003671 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003672 case X86::BI__builtin_ia32_vextractf128_pd256:
3673 case X86::BI__builtin_ia32_vextractf128_ps256:
3674 case X86::BI__builtin_ia32_vextractf128_si256:
3675 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003676 case X86::BI__builtin_ia32_extractf64x4_mask:
3677 case X86::BI__builtin_ia32_extracti64x4_mask:
3678 case X86::BI__builtin_ia32_extractf32x8_mask:
3679 case X86::BI__builtin_ia32_extracti32x8_mask:
3680 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3681 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3682 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3683 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003684 i = 1; l = 0; u = 1;
3685 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003686 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003687 case X86::BI__builtin_ia32_vinsertf128_pd256:
3688 case X86::BI__builtin_ia32_vinsertf128_ps256:
3689 case X86::BI__builtin_ia32_vinsertf128_si256:
3690 case X86::BI__builtin_ia32_insert128i256:
3691 case X86::BI__builtin_ia32_insertf32x8:
3692 case X86::BI__builtin_ia32_inserti32x8:
3693 case X86::BI__builtin_ia32_insertf64x4:
3694 case X86::BI__builtin_ia32_inserti64x4:
3695 case X86::BI__builtin_ia32_insertf64x2_256:
3696 case X86::BI__builtin_ia32_inserti64x2_256:
3697 case X86::BI__builtin_ia32_insertf32x4_256:
3698 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003699 i = 2; l = 0; u = 1;
3700 break;
Craig Topperacf56012018-06-08 00:59:27 +00003701 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003702 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003703 case X86::BI__builtin_ia32_vec_ext_v4si:
3704 case X86::BI__builtin_ia32_vec_ext_v4sf:
3705 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003706 case X86::BI__builtin_ia32_extractf32x4_mask:
3707 case X86::BI__builtin_ia32_extracti32x4_mask:
3708 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3709 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003710 i = 1; l = 0; u = 3;
3711 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003712 case X86::BI_mm_prefetch:
3713 case X86::BI__builtin_ia32_vec_ext_v8hi:
3714 case X86::BI__builtin_ia32_vec_ext_v8si:
3715 i = 1; l = 0; u = 7;
3716 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003717 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003718 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003719 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003720 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003721 case X86::BI__builtin_ia32_vec_set_v4si:
3722 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003723 case X86::BI__builtin_ia32_shuf_f32x4_256:
3724 case X86::BI__builtin_ia32_shuf_f64x2_256:
3725 case X86::BI__builtin_ia32_shuf_i32x4_256:
3726 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003727 case X86::BI__builtin_ia32_insertf64x2_512:
3728 case X86::BI__builtin_ia32_inserti64x2_512:
3729 case X86::BI__builtin_ia32_insertf32x4:
3730 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003731 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003732 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003733 case X86::BI__builtin_ia32_vpermil2pd:
3734 case X86::BI__builtin_ia32_vpermil2pd256:
3735 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003736 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003737 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003738 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003739 case X86::BI__builtin_ia32_cmpb128_mask:
3740 case X86::BI__builtin_ia32_cmpw128_mask:
3741 case X86::BI__builtin_ia32_cmpd128_mask:
3742 case X86::BI__builtin_ia32_cmpq128_mask:
3743 case X86::BI__builtin_ia32_cmpb256_mask:
3744 case X86::BI__builtin_ia32_cmpw256_mask:
3745 case X86::BI__builtin_ia32_cmpd256_mask:
3746 case X86::BI__builtin_ia32_cmpq256_mask:
3747 case X86::BI__builtin_ia32_cmpb512_mask:
3748 case X86::BI__builtin_ia32_cmpw512_mask:
3749 case X86::BI__builtin_ia32_cmpd512_mask:
3750 case X86::BI__builtin_ia32_cmpq512_mask:
3751 case X86::BI__builtin_ia32_ucmpb128_mask:
3752 case X86::BI__builtin_ia32_ucmpw128_mask:
3753 case X86::BI__builtin_ia32_ucmpd128_mask:
3754 case X86::BI__builtin_ia32_ucmpq128_mask:
3755 case X86::BI__builtin_ia32_ucmpb256_mask:
3756 case X86::BI__builtin_ia32_ucmpw256_mask:
3757 case X86::BI__builtin_ia32_ucmpd256_mask:
3758 case X86::BI__builtin_ia32_ucmpq256_mask:
3759 case X86::BI__builtin_ia32_ucmpb512_mask:
3760 case X86::BI__builtin_ia32_ucmpw512_mask:
3761 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003762 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003763 case X86::BI__builtin_ia32_vpcomub:
3764 case X86::BI__builtin_ia32_vpcomuw:
3765 case X86::BI__builtin_ia32_vpcomud:
3766 case X86::BI__builtin_ia32_vpcomuq:
3767 case X86::BI__builtin_ia32_vpcomb:
3768 case X86::BI__builtin_ia32_vpcomw:
3769 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003770 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003771 case X86::BI__builtin_ia32_vec_set_v8hi:
3772 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003773 i = 2; l = 0; u = 7;
3774 break;
Craig Topperacf56012018-06-08 00:59:27 +00003775 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003776 case X86::BI__builtin_ia32_roundps:
3777 case X86::BI__builtin_ia32_roundpd:
3778 case X86::BI__builtin_ia32_roundps256:
3779 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003780 case X86::BI__builtin_ia32_getmantpd128_mask:
3781 case X86::BI__builtin_ia32_getmantpd256_mask:
3782 case X86::BI__builtin_ia32_getmantps128_mask:
3783 case X86::BI__builtin_ia32_getmantps256_mask:
3784 case X86::BI__builtin_ia32_getmantpd512_mask:
3785 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003786 case X86::BI__builtin_ia32_vec_ext_v16qi:
3787 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003788 i = 1; l = 0; u = 15;
3789 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003790 case X86::BI__builtin_ia32_pblendd128:
3791 case X86::BI__builtin_ia32_blendps:
3792 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003793 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003794 case X86::BI__builtin_ia32_roundss:
3795 case X86::BI__builtin_ia32_roundsd:
3796 case X86::BI__builtin_ia32_rangepd128_mask:
3797 case X86::BI__builtin_ia32_rangepd256_mask:
3798 case X86::BI__builtin_ia32_rangepd512_mask:
3799 case X86::BI__builtin_ia32_rangeps128_mask:
3800 case X86::BI__builtin_ia32_rangeps256_mask:
3801 case X86::BI__builtin_ia32_rangeps512_mask:
3802 case X86::BI__builtin_ia32_getmantsd_round_mask:
3803 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003804 case X86::BI__builtin_ia32_vec_set_v16qi:
3805 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003806 i = 2; l = 0; u = 15;
3807 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003808 case X86::BI__builtin_ia32_vec_ext_v32qi:
3809 i = 1; l = 0; u = 31;
3810 break;
Craig Topper39c87102016-05-18 03:18:12 +00003811 case X86::BI__builtin_ia32_cmpps:
3812 case X86::BI__builtin_ia32_cmpss:
3813 case X86::BI__builtin_ia32_cmppd:
3814 case X86::BI__builtin_ia32_cmpsd:
3815 case X86::BI__builtin_ia32_cmpps256:
3816 case X86::BI__builtin_ia32_cmppd256:
3817 case X86::BI__builtin_ia32_cmpps128_mask:
3818 case X86::BI__builtin_ia32_cmppd128_mask:
3819 case X86::BI__builtin_ia32_cmpps256_mask:
3820 case X86::BI__builtin_ia32_cmppd256_mask:
3821 case X86::BI__builtin_ia32_cmpps512_mask:
3822 case X86::BI__builtin_ia32_cmppd512_mask:
3823 case X86::BI__builtin_ia32_cmpsd_mask:
3824 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003825 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003826 i = 2; l = 0; u = 31;
3827 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003828 case X86::BI__builtin_ia32_permdf256:
3829 case X86::BI__builtin_ia32_permdi256:
3830 case X86::BI__builtin_ia32_permdf512:
3831 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003832 case X86::BI__builtin_ia32_vpermilps:
3833 case X86::BI__builtin_ia32_vpermilps256:
3834 case X86::BI__builtin_ia32_vpermilpd512:
3835 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003836 case X86::BI__builtin_ia32_pshufd:
3837 case X86::BI__builtin_ia32_pshufd256:
3838 case X86::BI__builtin_ia32_pshufd512:
3839 case X86::BI__builtin_ia32_pshufhw:
3840 case X86::BI__builtin_ia32_pshufhw256:
3841 case X86::BI__builtin_ia32_pshufhw512:
3842 case X86::BI__builtin_ia32_pshuflw:
3843 case X86::BI__builtin_ia32_pshuflw256:
3844 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003845 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003846 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003847 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003848 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3849 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003850 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3851 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3852 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3853 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3854 case X86::BI__builtin_ia32_rndscaleps_mask:
3855 case X86::BI__builtin_ia32_rndscalepd_mask:
3856 case X86::BI__builtin_ia32_reducepd128_mask:
3857 case X86::BI__builtin_ia32_reducepd256_mask:
3858 case X86::BI__builtin_ia32_reducepd512_mask:
3859 case X86::BI__builtin_ia32_reduceps128_mask:
3860 case X86::BI__builtin_ia32_reduceps256_mask:
3861 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003862 case X86::BI__builtin_ia32_prold512:
3863 case X86::BI__builtin_ia32_prolq512:
3864 case X86::BI__builtin_ia32_prold128:
3865 case X86::BI__builtin_ia32_prold256:
3866 case X86::BI__builtin_ia32_prolq128:
3867 case X86::BI__builtin_ia32_prolq256:
3868 case X86::BI__builtin_ia32_prord512:
3869 case X86::BI__builtin_ia32_prorq512:
3870 case X86::BI__builtin_ia32_prord128:
3871 case X86::BI__builtin_ia32_prord256:
3872 case X86::BI__builtin_ia32_prorq128:
3873 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003874 case X86::BI__builtin_ia32_fpclasspd128_mask:
3875 case X86::BI__builtin_ia32_fpclasspd256_mask:
3876 case X86::BI__builtin_ia32_fpclassps128_mask:
3877 case X86::BI__builtin_ia32_fpclassps256_mask:
3878 case X86::BI__builtin_ia32_fpclassps512_mask:
3879 case X86::BI__builtin_ia32_fpclasspd512_mask:
3880 case X86::BI__builtin_ia32_fpclasssd_mask:
3881 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003882 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3883 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3884 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3885 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3886 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3887 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003888 case X86::BI__builtin_ia32_kshiftliqi:
3889 case X86::BI__builtin_ia32_kshiftlihi:
3890 case X86::BI__builtin_ia32_kshiftlisi:
3891 case X86::BI__builtin_ia32_kshiftlidi:
3892 case X86::BI__builtin_ia32_kshiftriqi:
3893 case X86::BI__builtin_ia32_kshiftrihi:
3894 case X86::BI__builtin_ia32_kshiftrisi:
3895 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003896 i = 1; l = 0; u = 255;
3897 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003898 case X86::BI__builtin_ia32_vperm2f128_pd256:
3899 case X86::BI__builtin_ia32_vperm2f128_ps256:
3900 case X86::BI__builtin_ia32_vperm2f128_si256:
3901 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003902 case X86::BI__builtin_ia32_pblendw128:
3903 case X86::BI__builtin_ia32_pblendw256:
3904 case X86::BI__builtin_ia32_blendps256:
3905 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003906 case X86::BI__builtin_ia32_palignr128:
3907 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003908 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003909 case X86::BI__builtin_ia32_alignq512:
3910 case X86::BI__builtin_ia32_alignd512:
3911 case X86::BI__builtin_ia32_alignd128:
3912 case X86::BI__builtin_ia32_alignd256:
3913 case X86::BI__builtin_ia32_alignq128:
3914 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003915 case X86::BI__builtin_ia32_vcomisd:
3916 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00003917 case X86::BI__builtin_ia32_shuf_f32x4:
3918 case X86::BI__builtin_ia32_shuf_f64x2:
3919 case X86::BI__builtin_ia32_shuf_i32x4:
3920 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00003921 case X86::BI__builtin_ia32_shufpd512:
3922 case X86::BI__builtin_ia32_shufps:
3923 case X86::BI__builtin_ia32_shufps256:
3924 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00003925 case X86::BI__builtin_ia32_dbpsadbw128:
3926 case X86::BI__builtin_ia32_dbpsadbw256:
3927 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00003928 case X86::BI__builtin_ia32_vpshldd128:
3929 case X86::BI__builtin_ia32_vpshldd256:
3930 case X86::BI__builtin_ia32_vpshldd512:
3931 case X86::BI__builtin_ia32_vpshldq128:
3932 case X86::BI__builtin_ia32_vpshldq256:
3933 case X86::BI__builtin_ia32_vpshldq512:
3934 case X86::BI__builtin_ia32_vpshldw128:
3935 case X86::BI__builtin_ia32_vpshldw256:
3936 case X86::BI__builtin_ia32_vpshldw512:
3937 case X86::BI__builtin_ia32_vpshrdd128:
3938 case X86::BI__builtin_ia32_vpshrdd256:
3939 case X86::BI__builtin_ia32_vpshrdd512:
3940 case X86::BI__builtin_ia32_vpshrdq128:
3941 case X86::BI__builtin_ia32_vpshrdq256:
3942 case X86::BI__builtin_ia32_vpshrdq512:
3943 case X86::BI__builtin_ia32_vpshrdw128:
3944 case X86::BI__builtin_ia32_vpshrdw256:
3945 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00003946 i = 2; l = 0; u = 255;
3947 break;
3948 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3949 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3950 case X86::BI__builtin_ia32_fixupimmps512_mask:
3951 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3952 case X86::BI__builtin_ia32_fixupimmsd_mask:
3953 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3954 case X86::BI__builtin_ia32_fixupimmss_mask:
3955 case X86::BI__builtin_ia32_fixupimmss_maskz:
3956 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3957 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3958 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3959 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3960 case X86::BI__builtin_ia32_fixupimmps128_mask:
3961 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3962 case X86::BI__builtin_ia32_fixupimmps256_mask:
3963 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3964 case X86::BI__builtin_ia32_pternlogd512_mask:
3965 case X86::BI__builtin_ia32_pternlogd512_maskz:
3966 case X86::BI__builtin_ia32_pternlogq512_mask:
3967 case X86::BI__builtin_ia32_pternlogq512_maskz:
3968 case X86::BI__builtin_ia32_pternlogd128_mask:
3969 case X86::BI__builtin_ia32_pternlogd128_maskz:
3970 case X86::BI__builtin_ia32_pternlogd256_mask:
3971 case X86::BI__builtin_ia32_pternlogd256_maskz:
3972 case X86::BI__builtin_ia32_pternlogq128_mask:
3973 case X86::BI__builtin_ia32_pternlogq128_maskz:
3974 case X86::BI__builtin_ia32_pternlogq256_mask:
3975 case X86::BI__builtin_ia32_pternlogq256_maskz:
3976 i = 3; l = 0; u = 255;
3977 break;
Craig Topper9625db02017-03-12 22:19:10 +00003978 case X86::BI__builtin_ia32_gatherpfdpd:
3979 case X86::BI__builtin_ia32_gatherpfdps:
3980 case X86::BI__builtin_ia32_gatherpfqpd:
3981 case X86::BI__builtin_ia32_gatherpfqps:
3982 case X86::BI__builtin_ia32_scatterpfdpd:
3983 case X86::BI__builtin_ia32_scatterpfdps:
3984 case X86::BI__builtin_ia32_scatterpfqpd:
3985 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00003986 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00003987 break;
Craig Topper39c87102016-05-18 03:18:12 +00003988 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3989 case X86::BI__builtin_ia32_rndscaless_round_mask:
3990 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00003991 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003992 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00003993
3994 // Note that we don't force a hard error on the range check here, allowing
3995 // template-generated or macro-generated dead code to potentially have out-of-
3996 // range values. These need to code generate, but don't need to necessarily
3997 // make any sense. We use a warning that defaults to an error.
3998 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003999}
4000
Richard Smith55ce3522012-06-25 20:30:08 +00004001/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4002/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4003/// Returns true when the format fits the function and the FormatStringInfo has
4004/// been populated.
4005bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4006 FormatStringInfo *FSI) {
4007 FSI->HasVAListArg = Format->getFirstArg() == 0;
4008 FSI->FormatIdx = Format->getFormatIdx() - 1;
4009 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004010
Richard Smith55ce3522012-06-25 20:30:08 +00004011 // The way the format attribute works in GCC, the implicit this argument
4012 // of member functions is counted. However, it doesn't appear in our own
4013 // lists, so decrement format_idx in that case.
4014 if (IsCXXMember) {
4015 if(FSI->FormatIdx == 0)
4016 return false;
4017 --FSI->FormatIdx;
4018 if (FSI->FirstDataArg != 0)
4019 --FSI->FirstDataArg;
4020 }
4021 return true;
4022}
Mike Stump11289f42009-09-09 15:08:12 +00004023
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004024/// Checks if a the given expression evaluates to null.
4025///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004026/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00004027static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004028 // If the expression has non-null type, it doesn't evaluate to null.
4029 if (auto nullability
4030 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4031 if (*nullability == NullabilityKind::NonNull)
4032 return false;
4033 }
4034
Ted Kremeneka146db32014-01-17 06:24:47 +00004035 // As a special case, transparent unions initialized with zero are
4036 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004037 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00004038 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4039 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004040 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00004041 if (const InitListExpr *ILE =
4042 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004043 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00004044 }
4045
4046 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00004047 return (!Expr->isValueDependent() &&
4048 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4049 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004050}
4051
4052static void CheckNonNullArgument(Sema &S,
4053 const Expr *ArgExpr,
4054 SourceLocation CallSiteLoc) {
4055 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00004056 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4057 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00004058}
4059
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004060bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4061 FormatStringInfo FSI;
4062 if ((GetFormatStringType(Format) == FST_NSString) &&
4063 getFormatStringInfo(Format, false, &FSI)) {
4064 Idx = FSI.FormatIdx;
4065 return true;
4066 }
4067 return false;
4068}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004069
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004070/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004071/// as formatting string to formatting method.
4072static void
4073DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4074 const NamedDecl *FDecl,
4075 Expr **Args,
4076 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004077 unsigned Idx = 0;
4078 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004079 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4080 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004081 Idx = 2;
4082 Format = true;
4083 }
4084 else
4085 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4086 if (S.GetFormatNSStringIdx(I, Idx)) {
4087 Format = true;
4088 break;
4089 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004090 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004091 if (!Format || NumArgs <= Idx)
4092 return;
4093 const Expr *FormatExpr = Args[Idx];
4094 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4095 FormatExpr = CSCE->getSubExpr();
4096 const StringLiteral *FormatString;
4097 if (const ObjCStringLiteral *OSL =
4098 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4099 FormatString = OSL->getString();
4100 else
4101 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4102 if (!FormatString)
4103 return;
4104 if (S.FormatStringHasSArg(FormatString)) {
4105 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4106 << "%s" << 1 << 1;
4107 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4108 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004109 }
4110}
4111
Douglas Gregorb4866e82015-06-19 18:13:19 +00004112/// Determine whether the given type has a non-null nullability annotation.
4113static bool isNonNullType(ASTContext &ctx, QualType type) {
4114 if (auto nullability = type->getNullability(ctx))
4115 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00004116
Douglas Gregorb4866e82015-06-19 18:13:19 +00004117 return false;
4118}
4119
Ted Kremenek2bc73332014-01-17 06:24:43 +00004120static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00004121 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004122 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00004123 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00004124 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004125 assert((FDecl || Proto) && "Need a function declaration or prototype");
4126
Ted Kremenek9aedc152014-01-17 06:24:56 +00004127 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00004128 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00004129 if (FDecl) {
4130 // Handle the nonnull attribute on the function/method declaration itself.
4131 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4132 if (!NonNull->args_size()) {
4133 // Easy case: all pointer arguments are nonnull.
4134 for (const auto *Arg : Args)
4135 if (S.isValidPointerAttrType(Arg->getType()))
4136 CheckNonNullArgument(S, Arg, CallSiteLoc);
4137 return;
4138 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004139
Joel E. Denny81508102018-03-13 14:51:22 +00004140 for (const ParamIdx &Idx : NonNull->args()) {
4141 unsigned IdxAST = Idx.getASTIndex();
4142 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00004143 continue;
4144 if (NonNullArgs.empty())
4145 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00004146 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004147 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004148 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004149 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004150
Douglas Gregorb4866e82015-06-19 18:13:19 +00004151 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4152 // Handle the nonnull attribute on the parameters of the
4153 // function/method.
4154 ArrayRef<ParmVarDecl*> parms;
4155 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4156 parms = FD->parameters();
4157 else
4158 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004159
Douglas Gregorb4866e82015-06-19 18:13:19 +00004160 unsigned ParamIndex = 0;
4161 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4162 I != E; ++I, ++ParamIndex) {
4163 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004164 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004165 isNonNullType(S.Context, PVD->getType())) {
4166 if (NonNullArgs.empty())
4167 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004168
Douglas Gregorb4866e82015-06-19 18:13:19 +00004169 NonNullArgs.set(ParamIndex);
4170 }
4171 }
4172 } else {
4173 // If we have a non-function, non-method declaration but no
4174 // function prototype, try to dig out the function prototype.
4175 if (!Proto) {
4176 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4177 QualType type = VD->getType().getNonReferenceType();
4178 if (auto pointerType = type->getAs<PointerType>())
4179 type = pointerType->getPointeeType();
4180 else if (auto blockType = type->getAs<BlockPointerType>())
4181 type = blockType->getPointeeType();
4182 // FIXME: data member pointers?
4183
4184 // Dig out the function prototype, if there is one.
4185 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004186 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004187 }
4188
4189 // Fill in non-null argument information from the nullability
4190 // information on the parameter types (if we have them).
4191 if (Proto) {
4192 unsigned Index = 0;
4193 for (auto paramType : Proto->getParamTypes()) {
4194 if (isNonNullType(S.Context, paramType)) {
4195 if (NonNullArgs.empty())
4196 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004197
Douglas Gregorb4866e82015-06-19 18:13:19 +00004198 NonNullArgs.set(Index);
4199 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004200
Douglas Gregorb4866e82015-06-19 18:13:19 +00004201 ++Index;
4202 }
4203 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004204 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004205
Douglas Gregorb4866e82015-06-19 18:13:19 +00004206 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004207 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004208 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004209 if (NonNullArgs[ArgIndex])
4210 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004211 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004212}
4213
Richard Smith55ce3522012-06-25 20:30:08 +00004214/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004215/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4216/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004217void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004218 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4219 bool IsMemberFunction, SourceLocation Loc,
4220 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004221 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004222 if (CurContext->isDependentContext())
4223 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004224
Ted Kremenekb8176da2010-09-09 04:33:05 +00004225 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004226 llvm::SmallBitVector CheckedVarArgs;
4227 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004228 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004229 // Only create vector if there are format attributes.
4230 CheckedVarArgs.resize(Args.size());
4231
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004232 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004233 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004234 }
Richard Smithd7293d72013-08-05 18:49:43 +00004235 }
Richard Smith55ce3522012-06-25 20:30:08 +00004236
4237 // Refuse POD arguments that weren't caught by the format string
4238 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004239 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4240 if (CallType != VariadicDoesNotApply &&
4241 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004242 unsigned NumParams = Proto ? Proto->getNumParams()
4243 : FDecl && isa<FunctionDecl>(FDecl)
4244 ? cast<FunctionDecl>(FDecl)->getNumParams()
4245 : FDecl && isa<ObjCMethodDecl>(FDecl)
4246 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4247 : 0;
4248
Alp Toker9cacbab2014-01-20 20:26:09 +00004249 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004250 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004251 if (const Expr *Arg = Args[ArgIdx]) {
4252 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4253 checkVariadicArgument(Arg, CallType);
4254 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004255 }
Richard Smithd7293d72013-08-05 18:49:43 +00004256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Douglas Gregorb4866e82015-06-19 18:13:19 +00004258 if (FDecl || Proto) {
4259 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004260
Richard Trieu41bc0992013-06-22 00:20:41 +00004261 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004262 if (FDecl) {
4263 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004264 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004265 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004266 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004267
4268 if (FD)
4269 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004270}
4271
4272/// CheckConstructorCall - Check a constructor call for correctness and safety
4273/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004274void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4275 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004276 const FunctionProtoType *Proto,
4277 SourceLocation Loc) {
4278 VariadicCallType CallType =
4279 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004280 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4281 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004282}
4283
4284/// CheckFunctionCall - Check a direct function call for various correctness
4285/// and safety properties not strictly enforced by the C type system.
4286bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4287 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004288 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4289 isa<CXXMethodDecl>(FDecl);
4290 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4291 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004292 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4293 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004294 Expr** Args = TheCall->getArgs();
4295 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004296
4297 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004298 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004299 // If this is a call to a member operator, hide the first argument
4300 // from checkCall.
4301 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004302 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004303 ++Args;
4304 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004305 } else if (IsMemberFunction)
4306 ImplicitThis =
4307 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4308
4309 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004310 IsMemberFunction, TheCall->getRParenLoc(),
4311 TheCall->getCallee()->getSourceRange(), CallType);
4312
4313 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4314 // None of the checks below are needed for functions that don't have
4315 // simple names (e.g., C++ conversion functions).
4316 if (!FnInfo)
4317 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004318
Richard Trieua7f30b12016-12-06 01:42:28 +00004319 CheckAbsoluteValueFunction(TheCall, FDecl);
4320 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004321
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004322 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004323 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004324
Anna Zaks22122702012-01-17 00:37:07 +00004325 unsigned CMId = FDecl->getMemoryFunctionKind();
4326 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004327 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004328
Anna Zaks201d4892012-01-13 21:52:01 +00004329 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004330 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004331 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004332 else if (CMId == Builtin::BIstrncat)
4333 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004334 else
Anna Zaks22122702012-01-17 00:37:07 +00004335 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004336
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004337 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004338}
4339
Fangrui Song6907ce22018-07-30 19:24:48 +00004340bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004341 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004342 VariadicCallType CallType =
4343 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004344
George Burgess IVce6284b2017-01-28 02:19:40 +00004345 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4346 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004347 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004348
4349 return false;
4350}
4351
Richard Trieu664c4c62013-06-20 21:03:13 +00004352bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4353 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004354 QualType Ty;
4355 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004356 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004357 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004358 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004359 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004360 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004361
Douglas Gregorb4866e82015-06-19 18:13:19 +00004362 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4363 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004364 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004365
Richard Trieu664c4c62013-06-20 21:03:13 +00004366 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004367 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004368 CallType = VariadicDoesNotApply;
4369 } else if (Ty->isBlockPointerType()) {
4370 CallType = VariadicBlock;
4371 } else { // Ty->isFunctionPointerType()
4372 CallType = VariadicFunction;
4373 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004374
George Burgess IVce6284b2017-01-28 02:19:40 +00004375 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004376 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4377 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004378 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004379
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004380 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004381}
4382
Richard Trieu41bc0992013-06-22 00:20:41 +00004383/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4384/// such as function pointers returned from functions.
4385bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004386 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004387 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004388 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004389 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004390 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004391 TheCall->getCallee()->getSourceRange(), CallType);
4392
4393 return false;
4394}
4395
Tim Northovere94a34c2014-03-11 10:49:14 +00004396static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004397 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004398 return false;
4399
JF Bastiendda2cb12016-04-18 18:01:49 +00004400 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004401 switch (Op) {
4402 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004403 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004404 llvm_unreachable("There is no ordering argument for an init");
4405
4406 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004407 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004408 case AtomicExpr::AO__atomic_load_n:
4409 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004410 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4411 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004412
4413 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004414 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004415 case AtomicExpr::AO__atomic_store:
4416 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004417 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4418 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4419 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004420
4421 default:
4422 return true;
4423 }
4424}
4425
Richard Smithfeea8832012-04-12 05:08:17 +00004426ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4427 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004428 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4429 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004430
Yaxun Liu39195062017-08-04 18:16:31 +00004431 // All the non-OpenCL operations take one of the following forms.
4432 // The OpenCL operations take the __c11 forms with one extra argument for
4433 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004434 enum {
4435 // C __c11_atomic_init(A *, C)
4436 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004437
Richard Smithfeea8832012-04-12 05:08:17 +00004438 // C __c11_atomic_load(A *, int)
4439 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004440
Richard Smithfeea8832012-04-12 05:08:17 +00004441 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004442 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004443
Eric Fiselier8d662442016-03-30 23:39:56 +00004444 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004445 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004446
Richard Smithfeea8832012-04-12 05:08:17 +00004447 // C __c11_atomic_add(A *, M, int)
4448 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004449
Richard Smithfeea8832012-04-12 05:08:17 +00004450 // C __atomic_exchange_n(A *, CP, int)
4451 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004452
Richard Smithfeea8832012-04-12 05:08:17 +00004453 // void __atomic_exchange(A *, C *, CP, int)
4454 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004455
Richard Smithfeea8832012-04-12 05:08:17 +00004456 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4457 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004458
Richard Smithfeea8832012-04-12 05:08:17 +00004459 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4460 GNUCmpXchg
4461 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004462
Yaxun Liu39195062017-08-04 18:16:31 +00004463 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004464 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4465 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004466 // where:
4467 // C is an appropriate type,
4468 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4469 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4470 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4471 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004472
Yaxun Liu39195062017-08-04 18:16:31 +00004473 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4474 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4475 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004476 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4477 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4478 AtomicExpr::AO__atomic_load,
4479 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004480 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4481 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4482 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4483 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4484 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004485 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4486 Op == AtomicExpr::AO__atomic_store_n ||
4487 Op == AtomicExpr::AO__atomic_exchange_n ||
4488 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4489 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004490 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004491
4492 switch (Op) {
4493 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004494 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004495 Form = Init;
4496 break;
4497
4498 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004499 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004500 case AtomicExpr::AO__atomic_load_n:
4501 Form = Load;
4502 break;
4503
Richard Smithfeea8832012-04-12 05:08:17 +00004504 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004505 Form = LoadCopy;
4506 break;
4507
4508 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004509 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004510 case AtomicExpr::AO__atomic_store:
4511 case AtomicExpr::AO__atomic_store_n:
4512 Form = Copy;
4513 break;
4514
4515 case AtomicExpr::AO__c11_atomic_fetch_add:
4516 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004517 case AtomicExpr::AO__opencl_atomic_fetch_add:
4518 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4519 case AtomicExpr::AO__opencl_atomic_fetch_min:
4520 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004521 case AtomicExpr::AO__atomic_fetch_add:
4522 case AtomicExpr::AO__atomic_fetch_sub:
4523 case AtomicExpr::AO__atomic_add_fetch:
4524 case AtomicExpr::AO__atomic_sub_fetch:
4525 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004526 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004527 case AtomicExpr::AO__c11_atomic_fetch_and:
4528 case AtomicExpr::AO__c11_atomic_fetch_or:
4529 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004530 case AtomicExpr::AO__opencl_atomic_fetch_and:
4531 case AtomicExpr::AO__opencl_atomic_fetch_or:
4532 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004533 case AtomicExpr::AO__atomic_fetch_and:
4534 case AtomicExpr::AO__atomic_fetch_or:
4535 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004536 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004537 case AtomicExpr::AO__atomic_and_fetch:
4538 case AtomicExpr::AO__atomic_or_fetch:
4539 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004540 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004541 Form = Arithmetic;
4542 break;
4543
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004544 case AtomicExpr::AO__atomic_fetch_min:
4545 case AtomicExpr::AO__atomic_fetch_max:
4546 IsMinMax = true;
4547 Form = Arithmetic;
4548 break;
4549
Richard Smithfeea8832012-04-12 05:08:17 +00004550 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004551 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004552 case AtomicExpr::AO__atomic_exchange_n:
4553 Form = Xchg;
4554 break;
4555
4556 case AtomicExpr::AO__atomic_exchange:
4557 Form = GNUXchg;
4558 break;
4559
4560 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4561 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004562 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4563 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004564 Form = C11CmpXchg;
4565 break;
4566
4567 case AtomicExpr::AO__atomic_compare_exchange:
4568 case AtomicExpr::AO__atomic_compare_exchange_n:
4569 Form = GNUCmpXchg;
4570 break;
4571 }
4572
Yaxun Liu39195062017-08-04 18:16:31 +00004573 unsigned AdjustedNumArgs = NumArgs[Form];
4574 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4575 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004576 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00004577 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004578 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4579 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4580 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004581 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00004582 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004583 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004584 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004585 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4586 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004587 return ExprError();
4588 }
4589
Richard Smithfeea8832012-04-12 05:08:17 +00004590 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004591 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00004592 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4593 if (ConvertedPtr.isInvalid())
4594 return ExprError();
4595
4596 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004597 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4598 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004599 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4600 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004601 return ExprError();
4602 }
4603
Richard Smithfeea8832012-04-12 05:08:17 +00004604 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4605 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4606 QualType ValType = AtomTy; // 'C'
4607 if (IsC11) {
4608 if (!AtomTy->isAtomicType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004609 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4610 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004611 return ExprError();
4612 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004613 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004614 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004615 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004616 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4617 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004618 return ExprError();
4619 }
Richard Smithfeea8832012-04-12 05:08:17 +00004620 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004621 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004622 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004623 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4624 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004625 return ExprError();
4626 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004627 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004628
Richard Smithfeea8832012-04-12 05:08:17 +00004629 // For an arithmetic operation, the implied arithmetic must be well-formed.
4630 if (Form == Arithmetic) {
4631 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004632 if (IsAddSub && !ValType->isIntegerType()
4633 && !ValType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004634 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4635 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004636 return ExprError();
4637 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004638 if (IsMinMax) {
4639 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4640 if (!BT || (BT->getKind() != BuiltinType::Int &&
4641 BT->getKind() != BuiltinType::UInt)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004642 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004643 return ExprError();
4644 }
4645 }
4646 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004647 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4648 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004649 return ExprError();
4650 }
David Majnemere85cff82015-01-28 05:48:06 +00004651 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004652 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004653 diag::err_incomplete_type)) {
4654 return ExprError();
4655 }
Richard Smithfeea8832012-04-12 05:08:17 +00004656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4657 // For __atomic_*_n operations, the value type must be a scalar integral or
4658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004659 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4660 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004661 return ExprError();
4662 }
4663
Eli Friedmanaa769812013-09-11 03:49:34 +00004664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4665 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004666 // For GNU atomics, require a trivially-copyable type. This is not part of
4667 // the GNU atomics specification, but we enforce it for sanity.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004668 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4669 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004670 return ExprError();
4671 }
4672
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004673 switch (ValType.getObjCLifetime()) {
4674 case Qualifiers::OCL_None:
4675 case Qualifiers::OCL_ExplicitNone:
4676 // okay
4677 break;
4678
4679 case Qualifiers::OCL_Weak:
4680 case Qualifiers::OCL_Strong:
4681 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004682 // FIXME: Can this happen? By this point, ValType should be known
4683 // to be trivially copyable.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004684 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4685 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004686 return ExprError();
4687 }
4688
JF Bastien7f0a05a2018-05-25 00:07:09 +00004689 // All atomic operations have an overload which takes a pointer to a volatile
4690 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4691 // into the result or the other operands. Similarly atomic_load takes a
4692 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004693 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004694 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004695 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004696 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4697 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004698 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004699 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004700 ResultType = Context.BoolTy;
4701
Richard Smithfeea8832012-04-12 05:08:17 +00004702 // The type of a parameter passed 'by value'. In the GNU atomics, such
4703 // arguments are actually passed as pointers.
4704 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004705 bool IsPassedByAddress = false;
4706 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004707 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004708 IsPassedByAddress = true;
4709 }
Richard Smithfeea8832012-04-12 05:08:17 +00004710
JF Bastien7f0a05a2018-05-25 00:07:09 +00004711 // The first argument's non-CV pointer type is used to deduce the type of
4712 // subsequent arguments, except for:
4713 // - weak flag (always converted to bool)
4714 // - memory order (always converted to int)
4715 // - scope (always converted to int)
4716 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004717 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004718 if (i < NumVals[Form] + 1) {
4719 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004720 case 0:
4721 // The first argument is always a pointer. It has a fixed type.
4722 // It is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004723 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004724 // Nothing else to do: we already know all we want about this pointer.
4725 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004726 case 1:
4727 // The second argument is the non-atomic operand. For arithmetic, this
4728 // is always passed by value, and for a compare_exchange it is always
4729 // passed by address. For the rest, GNU uses by-address and C11 uses
4730 // by-value.
4731 assert(Form != Load);
4732 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4733 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004734 else if (Form == Copy || Form == Xchg) {
4735 if (IsPassedByAddress)
4736 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004737 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004738 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004739 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004740 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004741 else {
4742 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00004743 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004744 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
Alexander Richardson6d989432017-10-15 18:48:14 +00004745 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004746 // Keep address space of non-atomic pointer type.
4747 if (const PointerType *PtrTy =
4748 ValArg->getType()->getAs<PointerType>()) {
4749 AS = PtrTy->getPointeeType().getAddressSpace();
4750 }
4751 Ty = Context.getPointerType(
4752 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4753 }
Richard Smithfeea8832012-04-12 05:08:17 +00004754 break;
4755 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004756 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004757 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4758 if (IsPassedByAddress)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004759 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004760 Ty = ByValType;
4761 break;
4762 case 3:
4763 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4764 Ty = Context.BoolTy;
4765 break;
4766 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004767 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004768 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004769 Ty = Context.IntTy;
4770 }
Richard Smithfeea8832012-04-12 05:08:17 +00004771
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004772 InitializedEntity Entity =
4773 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00004774 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004775 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4776 if (Arg.isInvalid())
4777 return true;
4778 TheCall->setArg(i, Arg.get());
4779 }
4780
Richard Smithfeea8832012-04-12 05:08:17 +00004781 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004782 SmallVector<Expr*, 5> SubExprs;
4783 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004784 switch (Form) {
4785 case Init:
4786 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00004787 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004788 break;
4789 case Load:
4790 SubExprs.push_back(TheCall->getArg(1)); // Order
4791 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004792 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004793 case Copy:
4794 case Arithmetic:
4795 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004796 SubExprs.push_back(TheCall->getArg(2)); // Order
4797 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004798 break;
4799 case GNUXchg:
4800 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4801 SubExprs.push_back(TheCall->getArg(3)); // Order
4802 SubExprs.push_back(TheCall->getArg(1)); // Val1
4803 SubExprs.push_back(TheCall->getArg(2)); // Val2
4804 break;
4805 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004806 SubExprs.push_back(TheCall->getArg(3)); // Order
4807 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004808 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00004809 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004810 break;
4811 case GNUCmpXchg:
4812 SubExprs.push_back(TheCall->getArg(4)); // Order
4813 SubExprs.push_back(TheCall->getArg(1)); // Val1
4814 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4815 SubExprs.push_back(TheCall->getArg(2)); // Val2
4816 SubExprs.push_back(TheCall->getArg(3)); // Weak
4817 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004818 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004819
4820 if (SubExprs.size() >= 2 && Form != Init) {
4821 llvm::APSInt Result(32);
4822 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4823 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004824 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004825 diag::warn_atomic_op_has_invalid_memory_order)
4826 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004827 }
4828
Yaxun Liu30d652a2017-08-15 16:02:49 +00004829 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4830 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4831 llvm::APSInt Result(32);
4832 if (Scope->isIntegerConstantExpr(Result, Context) &&
4833 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004834 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004835 << Scope->getSourceRange();
4836 }
4837 SubExprs.push_back(Scope);
4838 }
4839
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004840 AtomicExpr *AE =
4841 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4842 ResultType, Op, TheCall->getRParenLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00004843
Fariborz Jahanian615de762013-05-28 17:37:39 +00004844 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004845 Op == AtomicExpr::AO__c11_atomic_store ||
4846 Op == AtomicExpr::AO__opencl_atomic_load ||
4847 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004848 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004849 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004850 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004851 Op == AtomicExpr::AO__opencl_atomic_load)
4852 ? 0
4853 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004854
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004855 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004856}
4857
John McCall29ad95b2011-08-27 01:09:30 +00004858/// checkBuiltinArgument - Given a call to a builtin function, perform
4859/// normal type-checking on the given argument, updating the call in
4860/// place. This is useful when a builtin function requires custom
4861/// type-checking for some of its arguments but not necessarily all of
4862/// them.
4863///
4864/// Returns true on error.
4865static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4866 FunctionDecl *Fn = E->getDirectCallee();
4867 assert(Fn && "builtin call without direct callee!");
4868
4869 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4870 InitializedEntity Entity =
4871 InitializedEntity::InitializeParameter(S.Context, Param);
4872
4873 ExprResult Arg = E->getArg(0);
4874 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4875 if (Arg.isInvalid())
4876 return true;
4877
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004878 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00004879 return false;
4880}
4881
JF Bastiene77b48b2018-09-10 20:42:56 +00004882/// We have a call to a function like __sync_fetch_and_add, which is an
4883/// overloaded function based on the pointer type of its first argument.
4884/// The main ActOnCallExpr routines have already promoted the types of
4885/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00004886///
4887/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00004888/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00004889ExprResult
4890Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00004891 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4892 Expr *Callee = TheCall->getCallee();
4893 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00004894 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4895
4896 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004897 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004898 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00004899 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004900 return ExprError();
4901 }
Mike Stump11289f42009-09-09 15:08:12 +00004902
Chris Lattnerdc046542009-05-08 06:58:22 +00004903 // Inspect the first argument of the atomic builtin. This should always be
4904 // a pointer type, whose element is an integral scalar or pointer type.
4905 // Because it is a pointer type, we don't have to worry about any implicit
4906 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004907 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00004908 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00004909 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4910 if (FirstArgResult.isInvalid())
4911 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004912 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00004913 TheCall->setArg(0, FirstArg);
4914
John McCall31168b02011-06-15 23:02:42 +00004915 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4916 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004917 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4918 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004919 return ExprError();
4920 }
Mike Stump11289f42009-09-09 15:08:12 +00004921
John McCall31168b02011-06-15 23:02:42 +00004922 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00004923 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004924 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004925 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4926 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004927 return ExprError();
4928 }
Chris Lattnerdc046542009-05-08 06:58:22 +00004929
Aaron Ballmana383c942018-05-05 17:38:42 +00004930 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004931 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00004932 << FirstArg->getType() << FirstArg->getSourceRange();
4933 return ExprError();
4934 }
4935
John McCall31168b02011-06-15 23:02:42 +00004936 switch (ValType.getObjCLifetime()) {
4937 case Qualifiers::OCL_None:
4938 case Qualifiers::OCL_ExplicitNone:
4939 // okay
4940 break;
4941
4942 case Qualifiers::OCL_Weak:
4943 case Qualifiers::OCL_Strong:
4944 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004945 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4946 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004947 return ExprError();
4948 }
4949
John McCallb50451a2011-10-05 07:41:44 +00004950 // Strip any qualifiers off ValType.
4951 ValType = ValType.getUnqualifiedType();
4952
Chandler Carruth3973af72010-07-18 20:54:12 +00004953 // The majority of builtins return a value, but a few have special return
4954 // types, so allow them to override appropriately below.
4955 QualType ResultType = ValType;
4956
Chris Lattnerdc046542009-05-08 06:58:22 +00004957 // We need to figure out which concrete builtin this maps onto. For example,
4958 // __sync_fetch_and_add with a 2 byte object turns into
4959 // __sync_fetch_and_add_2.
4960#define BUILTIN_ROW(x) \
4961 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4962 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00004963
Chris Lattnerdc046542009-05-08 06:58:22 +00004964 static const unsigned BuiltinIndices[][5] = {
4965 BUILTIN_ROW(__sync_fetch_and_add),
4966 BUILTIN_ROW(__sync_fetch_and_sub),
4967 BUILTIN_ROW(__sync_fetch_and_or),
4968 BUILTIN_ROW(__sync_fetch_and_and),
4969 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00004970 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00004971
Chris Lattnerdc046542009-05-08 06:58:22 +00004972 BUILTIN_ROW(__sync_add_and_fetch),
4973 BUILTIN_ROW(__sync_sub_and_fetch),
4974 BUILTIN_ROW(__sync_and_and_fetch),
4975 BUILTIN_ROW(__sync_or_and_fetch),
4976 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00004977 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00004978
Chris Lattnerdc046542009-05-08 06:58:22 +00004979 BUILTIN_ROW(__sync_val_compare_and_swap),
4980 BUILTIN_ROW(__sync_bool_compare_and_swap),
4981 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00004982 BUILTIN_ROW(__sync_lock_release),
4983 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00004984 };
Mike Stump11289f42009-09-09 15:08:12 +00004985#undef BUILTIN_ROW
4986
Chris Lattnerdc046542009-05-08 06:58:22 +00004987 // Determine the index of the size.
4988 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00004989 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00004990 case 1: SizeIndex = 0; break;
4991 case 2: SizeIndex = 1; break;
4992 case 4: SizeIndex = 2; break;
4993 case 8: SizeIndex = 3; break;
4994 case 16: SizeIndex = 4; break;
4995 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004996 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4997 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004998 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00004999 }
Mike Stump11289f42009-09-09 15:08:12 +00005000
Chris Lattnerdc046542009-05-08 06:58:22 +00005001 // Each of these builtins has one pointer argument, followed by some number of
5002 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5003 // that we ignore. Find out which row of BuiltinIndices to read from as well
5004 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005005 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00005006 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00005007 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00005008 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00005009 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00005010 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00005011 case Builtin::BI__sync_fetch_and_add_1:
5012 case Builtin::BI__sync_fetch_and_add_2:
5013 case Builtin::BI__sync_fetch_and_add_4:
5014 case Builtin::BI__sync_fetch_and_add_8:
5015 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005016 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00005017 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005018
5019 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00005020 case Builtin::BI__sync_fetch_and_sub_1:
5021 case Builtin::BI__sync_fetch_and_sub_2:
5022 case Builtin::BI__sync_fetch_and_sub_4:
5023 case Builtin::BI__sync_fetch_and_sub_8:
5024 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005025 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00005026 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005027
5028 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00005029 case Builtin::BI__sync_fetch_and_or_1:
5030 case Builtin::BI__sync_fetch_and_or_2:
5031 case Builtin::BI__sync_fetch_and_or_4:
5032 case Builtin::BI__sync_fetch_and_or_8:
5033 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005034 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00005035 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005036
5037 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00005038 case Builtin::BI__sync_fetch_and_and_1:
5039 case Builtin::BI__sync_fetch_and_and_2:
5040 case Builtin::BI__sync_fetch_and_and_4:
5041 case Builtin::BI__sync_fetch_and_and_8:
5042 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005043 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00005044 break;
Mike Stump11289f42009-09-09 15:08:12 +00005045
Fangrui Song6907ce22018-07-30 19:24:48 +00005046 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00005047 case Builtin::BI__sync_fetch_and_xor_1:
5048 case Builtin::BI__sync_fetch_and_xor_2:
5049 case Builtin::BI__sync_fetch_and_xor_4:
5050 case Builtin::BI__sync_fetch_and_xor_8:
5051 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005052 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00005053 break;
5054
Fangrui Song6907ce22018-07-30 19:24:48 +00005055 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00005056 case Builtin::BI__sync_fetch_and_nand_1:
5057 case Builtin::BI__sync_fetch_and_nand_2:
5058 case Builtin::BI__sync_fetch_and_nand_4:
5059 case Builtin::BI__sync_fetch_and_nand_8:
5060 case Builtin::BI__sync_fetch_and_nand_16:
5061 BuiltinIndex = 5;
5062 WarnAboutSemanticsChange = true;
5063 break;
5064
Fangrui Song6907ce22018-07-30 19:24:48 +00005065 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005066 case Builtin::BI__sync_add_and_fetch_1:
5067 case Builtin::BI__sync_add_and_fetch_2:
5068 case Builtin::BI__sync_add_and_fetch_4:
5069 case Builtin::BI__sync_add_and_fetch_8:
5070 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005071 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00005072 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005073
5074 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005075 case Builtin::BI__sync_sub_and_fetch_1:
5076 case Builtin::BI__sync_sub_and_fetch_2:
5077 case Builtin::BI__sync_sub_and_fetch_4:
5078 case Builtin::BI__sync_sub_and_fetch_8:
5079 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005080 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00005081 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005082
5083 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005084 case Builtin::BI__sync_and_and_fetch_1:
5085 case Builtin::BI__sync_and_and_fetch_2:
5086 case Builtin::BI__sync_and_and_fetch_4:
5087 case Builtin::BI__sync_and_and_fetch_8:
5088 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005089 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00005090 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005091
5092 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005093 case Builtin::BI__sync_or_and_fetch_1:
5094 case Builtin::BI__sync_or_and_fetch_2:
5095 case Builtin::BI__sync_or_and_fetch_4:
5096 case Builtin::BI__sync_or_and_fetch_8:
5097 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005098 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00005099 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005100
5101 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005102 case Builtin::BI__sync_xor_and_fetch_1:
5103 case Builtin::BI__sync_xor_and_fetch_2:
5104 case Builtin::BI__sync_xor_and_fetch_4:
5105 case Builtin::BI__sync_xor_and_fetch_8:
5106 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005107 BuiltinIndex = 10;
5108 break;
5109
Fangrui Song6907ce22018-07-30 19:24:48 +00005110 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00005111 case Builtin::BI__sync_nand_and_fetch_1:
5112 case Builtin::BI__sync_nand_and_fetch_2:
5113 case Builtin::BI__sync_nand_and_fetch_4:
5114 case Builtin::BI__sync_nand_and_fetch_8:
5115 case Builtin::BI__sync_nand_and_fetch_16:
5116 BuiltinIndex = 11;
5117 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00005118 break;
Mike Stump11289f42009-09-09 15:08:12 +00005119
Chris Lattnerdc046542009-05-08 06:58:22 +00005120 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005121 case Builtin::BI__sync_val_compare_and_swap_1:
5122 case Builtin::BI__sync_val_compare_and_swap_2:
5123 case Builtin::BI__sync_val_compare_and_swap_4:
5124 case Builtin::BI__sync_val_compare_and_swap_8:
5125 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005126 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00005127 NumFixed = 2;
5128 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005129
Chris Lattnerdc046542009-05-08 06:58:22 +00005130 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005131 case Builtin::BI__sync_bool_compare_and_swap_1:
5132 case Builtin::BI__sync_bool_compare_and_swap_2:
5133 case Builtin::BI__sync_bool_compare_and_swap_4:
5134 case Builtin::BI__sync_bool_compare_and_swap_8:
5135 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005136 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00005137 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00005138 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005139 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005140
JF Bastien7f0a05a2018-05-25 00:07:09 +00005141 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00005142 case Builtin::BI__sync_lock_test_and_set_1:
5143 case Builtin::BI__sync_lock_test_and_set_2:
5144 case Builtin::BI__sync_lock_test_and_set_4:
5145 case Builtin::BI__sync_lock_test_and_set_8:
5146 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005147 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00005148 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005149
Chris Lattnerdc046542009-05-08 06:58:22 +00005150 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00005151 case Builtin::BI__sync_lock_release_1:
5152 case Builtin::BI__sync_lock_release_2:
5153 case Builtin::BI__sync_lock_release_4:
5154 case Builtin::BI__sync_lock_release_8:
5155 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005156 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005157 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005158 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005159 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005160
5161 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005162 case Builtin::BI__sync_swap_1:
5163 case Builtin::BI__sync_swap_2:
5164 case Builtin::BI__sync_swap_4:
5165 case Builtin::BI__sync_swap_8:
5166 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005167 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005168 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005169 }
Mike Stump11289f42009-09-09 15:08:12 +00005170
Chris Lattnerdc046542009-05-08 06:58:22 +00005171 // Now that we know how many fixed arguments we expect, first check that we
5172 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005173 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005174 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5175 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005176 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005177 return ExprError();
5178 }
Mike Stump11289f42009-09-09 15:08:12 +00005179
JF Bastiene77b48b2018-09-10 20:42:56 +00005180 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5181 << Callee->getSourceRange();
5182
Hal Finkeld2208b52014-10-02 20:53:50 +00005183 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005184 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005185 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005186 }
5187
Chris Lattner5b9241b2009-05-08 15:36:58 +00005188 // Get the decl for the concrete builtin from this, we can tell what the
5189 // concrete integer type we should convert to is.
5190 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005191 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005192 FunctionDecl *NewBuiltinDecl;
5193 if (NewBuiltinID == BuiltinID)
5194 NewBuiltinDecl = FDecl;
5195 else {
5196 // Perform builtin lookup to avoid redeclaring it.
5197 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005198 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005199 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5200 assert(Res.getFoundDecl());
5201 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005202 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005203 return ExprError();
5204 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005205
John McCallcf142162010-08-07 06:22:56 +00005206 // The first argument --- the pointer --- has a fixed type; we
5207 // deduce the types of the rest of the arguments accordingly. Walk
5208 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005209 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005210 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005211
Chris Lattnerdc046542009-05-08 06:58:22 +00005212 // GCC does an implicit conversion to the pointer or integer ValType. This
5213 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005214 // Initialize the argument.
5215 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5216 ValType, /*consume*/ false);
5217 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005218 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005219 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005220
Chris Lattnerdc046542009-05-08 06:58:22 +00005221 // Okay, we have something that *can* be converted to the right type. Check
5222 // to see if there is a potentially weird extension going on here. This can
5223 // happen when you do an atomic operation on something like an char* and
5224 // pass in 42. The 42 gets converted to char. This is even more strange
5225 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005226 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005227 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005228 }
Mike Stump11289f42009-09-09 15:08:12 +00005229
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005230 // Create a new DeclRefExpr to refer to the new decl.
5231 DeclRefExpr* NewDRE = DeclRefExpr::Create(
5232 Context,
5233 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00005234 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005235 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00005236 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005237 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00005238 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005239 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00005240
Chris Lattnerdc046542009-05-08 06:58:22 +00005241 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005242 // FIXME: This loses syntactic information.
5243 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5244 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5245 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005246 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005247
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005248 // Change the result type of the call to match the original value type. This
5249 // is arbitrary, but the codegen for these builtins ins design to handle it
5250 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005251 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005252
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005253 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005254}
5255
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005256/// SemaBuiltinNontemporalOverloaded - We have a call to
5257/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5258/// overloaded function based on the pointer type of its last argument.
5259///
5260/// This function goes through and does final semantic checking for these
5261/// builtins.
5262ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5263 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5264 DeclRefExpr *DRE =
5265 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5266 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5267 unsigned BuiltinID = FDecl->getBuiltinID();
5268 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5269 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5270 "Unexpected nontemporal load/store builtin!");
5271 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5272 unsigned numArgs = isStore ? 2 : 1;
5273
5274 // Ensure that we have the proper number of arguments.
5275 if (checkArgCount(*this, TheCall, numArgs))
5276 return ExprError();
5277
5278 // Inspect the last argument of the nontemporal builtin. This should always
5279 // be a pointer type, from which we imply the type of the memory access.
5280 // Because it is a pointer type, we don't have to worry about any implicit
5281 // casts here.
5282 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5283 ExprResult PointerArgResult =
5284 DefaultFunctionArrayLvalueConversion(PointerArg);
5285
5286 if (PointerArgResult.isInvalid())
5287 return ExprError();
5288 PointerArg = PointerArgResult.get();
5289 TheCall->setArg(numArgs - 1, PointerArg);
5290
5291 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5292 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005293 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005294 << PointerArg->getType() << PointerArg->getSourceRange();
5295 return ExprError();
5296 }
5297
5298 QualType ValType = pointerType->getPointeeType();
5299
5300 // Strip any qualifiers off ValType.
5301 ValType = ValType.getUnqualifiedType();
5302 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5303 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5304 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005305 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005306 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5307 << PointerArg->getType() << PointerArg->getSourceRange();
5308 return ExprError();
5309 }
5310
5311 if (!isStore) {
5312 TheCall->setType(ValType);
5313 return TheCallResult;
5314 }
5315
5316 ExprResult ValArg = TheCall->getArg(0);
5317 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5318 Context, ValType, /*consume*/ false);
5319 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5320 if (ValArg.isInvalid())
5321 return ExprError();
5322
5323 TheCall->setArg(0, ValArg.get());
5324 TheCall->setType(Context.VoidTy);
5325 return TheCallResult;
5326}
5327
Chris Lattner6436fb62009-02-18 06:01:06 +00005328/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005329/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005330/// Note: It might also make sense to do the UTF-16 conversion here (would
5331/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005332bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005333 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005334 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5335
Douglas Gregorfb65e592011-07-27 05:40:30 +00005336 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005337 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5338 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005339 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005340 }
Mike Stump11289f42009-09-09 15:08:12 +00005341
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005342 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005343 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005344 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005345 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5346 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5347 llvm::UTF16 *ToPtr = &ToBuf[0];
5348
5349 llvm::ConversionResult Result =
5350 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5351 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005352 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005353 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005354 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5355 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005356 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005357 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005358}
5359
Mehdi Amini06d367c2016-10-24 20:39:34 +00005360/// CheckObjCString - Checks that the format string argument to the os_log()
5361/// and os_trace() functions is correct, and converts it to const char *.
5362ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5363 Arg = Arg->IgnoreParenCasts();
5364 auto *Literal = dyn_cast<StringLiteral>(Arg);
5365 if (!Literal) {
5366 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5367 Literal = ObjcLiteral->getString();
5368 }
5369 }
5370
5371 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5372 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005373 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005374 << Arg->getSourceRange());
5375 }
5376
5377 ExprResult Result(Literal);
5378 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5379 InitializedEntity Entity =
5380 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5381 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5382 return Result;
5383}
5384
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005385/// Check that the user is calling the appropriate va_start builtin for the
5386/// target and calling convention.
5387static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5388 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5389 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00005390 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005391 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005392 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5393 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005394 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005395 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5396 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5397 if (IsMSVAStart) {
5398 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005399 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005400 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005401 diag::err_ms_va_start_used_in_sysv_function);
5402 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005403 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005404 // On x64 Windows, don't allow this in System V ABI functions.
5405 // (Yes, that means there's no corresponding way to support variadic
5406 // System V ABI functions on Windows.)
5407 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005408 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005409 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005410 diag::err_va_start_used_in_wrong_abi_function)
5411 << !IsWindows;
5412 }
5413 return false;
5414 }
5415
5416 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005417 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005418 return false;
5419}
5420
5421static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5422 ParmVarDecl **LastParam = nullptr) {
5423 // Determine whether the current function, block, or obj-c method is variadic
5424 // and get its parameter list.
5425 bool IsVariadic = false;
5426 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005427 DeclContext *Caller = S.CurContext;
5428 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5429 IsVariadic = Block->isVariadic();
5430 Params = Block->parameters();
5431 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005432 IsVariadic = FD->isVariadic();
5433 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005434 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005435 IsVariadic = MD->isVariadic();
5436 // FIXME: This isn't correct for methods (results in bogus warning).
5437 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005438 } else if (isa<CapturedDecl>(Caller)) {
5439 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005440 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005441 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005442 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005443 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005444 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005445 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005446 }
5447
5448 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005449 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005450 return true;
5451 }
5452
5453 if (LastParam)
5454 *LastParam = Params.empty() ? nullptr : Params.back();
5455
5456 return false;
5457}
5458
Aaron Ballman68d50642018-06-19 14:53:20 +00005459/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5460/// for validity. Emit an error and return true on failure; return false
5461/// on success.
5462bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5463 Expr *Fn = TheCall->getCallee();
5464
5465 if (checkVAStartABI(*this, BuiltinID, Fn))
5466 return true;
5467
5468 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005469 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005470 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005471 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5472 << Fn->getSourceRange()
5473 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005474 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005475 return true;
5476 }
5477
5478 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005479 return Diag(TheCall->getEndLoc(),
5480 diag::err_typecheck_call_too_few_args_at_least)
5481 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005482 }
5483
5484 // Type-check the first argument normally.
5485 if (checkBuiltinArgument(*this, TheCall, 0))
5486 return true;
5487
5488 // Check that the current function is variadic, and get its last parameter.
5489 ParmVarDecl *LastParam;
5490 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5491 return true;
5492
5493 // Verify that the second argument to the builtin is the last argument of the
5494 // current function or method.
5495 bool SecondArgIsLastNamedArgument = false;
5496 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5497
5498 // These are valid if SecondArgIsLastNamedArgument is false after the next
5499 // block.
5500 QualType Type;
5501 SourceLocation ParamLoc;
5502 bool IsCRegister = false;
5503
5504 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5505 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5506 SecondArgIsLastNamedArgument = PV == LastParam;
5507
5508 Type = PV->getType();
5509 ParamLoc = PV->getLocation();
5510 IsCRegister =
5511 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5512 }
5513 }
5514
5515 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005516 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005517 diag::warn_second_arg_of_va_start_not_last_named_param);
5518 else if (IsCRegister || Type->isReferenceType() ||
5519 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5520 // Promotable integers are UB, but enumerations need a bit of
5521 // extra checking to see what their promotable type actually is.
5522 if (!Type->isPromotableIntegerType())
5523 return false;
5524 if (!Type->isEnumeralType())
5525 return true;
5526 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5527 return !(ED &&
5528 Context.typesAreCompatible(ED->getPromotionType(), Type));
5529 }()) {
5530 unsigned Reason = 0;
5531 if (Type->isReferenceType()) Reason = 1;
5532 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005533 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005534 Diag(ParamLoc, diag::note_parameter_type) << Type;
5535 }
5536
5537 TheCall->setType(Context.VoidTy);
5538 return false;
5539}
5540
5541bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5542 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5543 // const char *named_addr);
5544
5545 Expr *Func = Call->getCallee();
5546
5547 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005548 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005549 diag::err_typecheck_call_too_few_args_at_least)
5550 << 0 /*function call*/ << 3 << Call->getNumArgs();
5551
5552 // Type-check the first argument normally.
5553 if (checkBuiltinArgument(*this, Call, 0))
5554 return true;
5555
5556 // Check that the current function is variadic.
5557 if (checkVAStartIsInVariadicFunction(*this, Func))
5558 return true;
5559
5560 // __va_start on Windows does not validate the parameter qualifiers
5561
5562 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5563 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5564
5565 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5566 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5567
5568 const QualType &ConstCharPtrTy =
5569 Context.getPointerType(Context.CharTy.withConst());
5570 if (!Arg1Ty->isPointerType() ||
5571 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005572 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5573 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5574 << 0 /* qualifier difference */
5575 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005576 << 2 << Arg1->getType() << ConstCharPtrTy;
5577
5578 const QualType SizeTy = Context.getSizeType();
5579 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005580 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5581 << Arg2->getType() << SizeTy << 1 /* different class */
5582 << 0 /* qualifier difference */
5583 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005584 << 3 << Arg2->getType() << SizeTy;
5585
5586 return false;
5587}
5588
5589/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5590/// friends. This is declared to take (...), so we have to check everything.
5591bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5592 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005593 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5594 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005595 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005596 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005597 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005598 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5599 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005600 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005601
5602 ExprResult OrigArg0 = TheCall->getArg(0);
5603 ExprResult OrigArg1 = TheCall->getArg(1);
5604
5605 // Do standard promotions between the two arguments, returning their common
5606 // type.
5607 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5608 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5609 return true;
5610
5611 // Make sure any conversions are pushed back into the call; this is
5612 // type safe since unordered compare builtins are declared as "_Bool
5613 // foo(...)".
5614 TheCall->setArg(0, OrigArg0.get());
5615 TheCall->setArg(1, OrigArg1.get());
5616
5617 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5618 return false;
5619
5620 // If the common type isn't a real floating type, then the arguments were
5621 // invalid for this operation.
5622 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005623 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005624 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005625 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5626 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005627 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005628
5629 return false;
5630}
5631
5632/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5633/// __builtin_isnan and friends. This is declared to take (...), so we have
5634/// to check everything. We expect the last argument to be a floating point
5635/// value.
5636bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5637 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005638 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5639 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005640 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005641 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005642 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005643 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5644 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005645 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005646
5647 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5648
5649 if (OrigArg->isTypeDependent())
5650 return false;
5651
5652 // This operation requires a non-_Complex floating-point number.
5653 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005654 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005655 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005656 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005657
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005658 // If this is an implicit conversion from float -> float, double, or
5659 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005660 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5661 // Only remove standard FloatCasts, leaving other casts inplace
5662 if (Cast->getCastKind() == CK_FloatingCast) {
5663 Expr *CastArg = Cast->getSubExpr();
5664 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005665 assert(
5666 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5667 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5668 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5669 "promotion from float to either float, double, or long double is "
5670 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005671 Cast->setSubExpr(nullptr);
5672 TheCall->setArg(NumArgs-1, CastArg);
5673 }
5674 }
5675 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005676
Aaron Ballman68d50642018-06-19 14:53:20 +00005677 return false;
5678}
5679
5680// Customized Sema Checking for VSX builtins that have the following signature:
5681// vector [...] builtinName(vector [...], vector [...], const int);
5682// Which takes the same type of vectors (any legal vector type) for the first
5683// two arguments and takes compile time constant for the third argument.
5684// Example builtins are :
5685// vector double vec_xxpermdi(vector double, vector double, int);
5686// vector short vec_xxsldwi(vector short, vector short, int);
5687bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5688 unsigned ExpectedNumArgs = 3;
5689 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005690 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005691 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005692 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005693 << TheCall->getSourceRange();
5694
5695 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005696 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005697 diag::err_typecheck_call_too_many_args_at_most)
5698 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5699 << TheCall->getSourceRange();
5700
5701 // Check the third argument is a compile time constant
5702 llvm::APSInt Value;
5703 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005704 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005705 diag::err_vsx_builtin_nonconstant_argument)
5706 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005707 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005708 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005709
5710 QualType Arg1Ty = TheCall->getArg(0)->getType();
5711 QualType Arg2Ty = TheCall->getArg(1)->getType();
5712
5713 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005714 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005715 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5716 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5717 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5718 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005719 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005720 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005721 }
5722
5723 // Check the first two arguments are the same type.
5724 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5725 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5726 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005727 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005728 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005729 }
5730
5731 // When default clang type checking is turned off and the customized type
5732 // checking is used, the returning type of the function must be explicitly
5733 // set. Otherwise it is _Bool by default.
5734 TheCall->setType(Arg1Ty);
5735
5736 return false;
5737}
5738
5739/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5740// This is declared to take (...), so we have to check everything.
5741ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5742 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005743 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005744 diag::err_typecheck_call_too_few_args_at_least)
5745 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5746 << TheCall->getSourceRange());
5747
5748 // Determine which of the following types of shufflevector we're checking:
5749 // 1) unary, vector mask: (lhs, mask)
5750 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5751 QualType resType = TheCall->getArg(0)->getType();
5752 unsigned numElements = 0;
5753
5754 if (!TheCall->getArg(0)->isTypeDependent() &&
5755 !TheCall->getArg(1)->isTypeDependent()) {
5756 QualType LHSType = TheCall->getArg(0)->getType();
5757 QualType RHSType = TheCall->getArg(1)->getType();
5758
5759 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005760 return ExprError(
5761 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5762 << TheCall->getDirectCallee()
5763 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005764 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005765
5766 numElements = LHSType->getAs<VectorType>()->getNumElements();
5767 unsigned numResElements = TheCall->getNumArgs() - 2;
5768
5769 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5770 // with mask. If so, verify that RHS is an integer vector type with the
5771 // same number of elts as lhs.
5772 if (TheCall->getNumArgs() == 2) {
5773 if (!RHSType->hasIntegerRepresentation() ||
5774 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005775 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005776 diag::err_vec_builtin_incompatible_vector)
5777 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005778 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005779 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005780 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005781 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005782 diag::err_vec_builtin_incompatible_vector)
5783 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005784 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005785 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005786 } else if (numElements != numResElements) {
5787 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5788 resType = Context.getVectorType(eltType, numResElements,
5789 VectorType::GenericVector);
5790 }
5791 }
5792
5793 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5794 if (TheCall->getArg(i)->isTypeDependent() ||
5795 TheCall->getArg(i)->isValueDependent())
5796 continue;
5797
5798 llvm::APSInt Result(32);
5799 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005800 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005801 diag::err_shufflevector_nonconstant_argument)
5802 << TheCall->getArg(i)->getSourceRange());
5803
5804 // Allow -1 which will be translated to undef in the IR.
5805 if (Result.isSigned() && Result.isAllOnesValue())
5806 continue;
5807
5808 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005809 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005810 diag::err_shufflevector_argument_too_large)
5811 << TheCall->getArg(i)->getSourceRange());
5812 }
5813
5814 SmallVector<Expr*, 32> exprs;
5815
5816 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5817 exprs.push_back(TheCall->getArg(i));
5818 TheCall->setArg(i, nullptr);
5819 }
5820
5821 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005822 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005823 TheCall->getRParenLoc());
5824}
5825
5826/// SemaConvertVectorExpr - Handle __builtin_convertvector
5827ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5828 SourceLocation BuiltinLoc,
5829 SourceLocation RParenLoc) {
5830 ExprValueKind VK = VK_RValue;
5831 ExprObjectKind OK = OK_Ordinary;
5832 QualType DstTy = TInfo->getType();
5833 QualType SrcTy = E->getType();
5834
5835 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5836 return ExprError(Diag(BuiltinLoc,
5837 diag::err_convertvector_non_vector)
5838 << E->getSourceRange());
5839 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5840 return ExprError(Diag(BuiltinLoc,
5841 diag::err_convertvector_non_vector_type));
5842
5843 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5844 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5845 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5846 if (SrcElts != DstElts)
5847 return ExprError(Diag(BuiltinLoc,
5848 diag::err_convertvector_incompatible_vector)
5849 << E->getSourceRange());
5850 }
5851
5852 return new (Context)
5853 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5854}
5855
5856/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5857// This is declared to take (const void*, ...) and can take two
5858// optional constant int args.
5859bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5860 unsigned NumArgs = TheCall->getNumArgs();
5861
5862 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005863 return Diag(TheCall->getEndLoc(),
5864 diag::err_typecheck_call_too_many_args_at_most)
5865 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005866
5867 // Argument 0 is checked for us and the remaining arguments must be
5868 // constant integers.
5869 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00005870 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005871 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005872
Warren Hunt20e4a5d2014-02-21 23:08:53 +00005873 return false;
5874}
5875
Hal Finkelf0417332014-07-17 14:25:55 +00005876/// SemaBuiltinAssume - Handle __assume (MS Extension).
5877// __assume does not evaluate its arguments, and should warn if its argument
5878// has side effects.
5879bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5880 Expr *Arg = TheCall->getArg(0);
5881 if (Arg->isInstantiationDependent()) return false;
5882
5883 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005884 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5885 << Arg->getSourceRange()
5886 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00005887
5888 return false;
5889}
5890
David Majnemer86b1bfa2016-10-31 18:07:57 +00005891/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00005892/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5893/// than 8.
5894bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5895 // The alignment must be a constant integer.
5896 Expr *Arg = TheCall->getArg(1);
5897
5898 // We can't check the value of a dependent argument.
5899 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00005900 if (const auto *UE =
5901 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00005902 if (UE->getKind() == UETT_AlignOf ||
5903 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005904 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5905 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00005906
David Majnemer51169932016-10-31 05:37:48 +00005907 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5908
5909 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005910 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5911 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005912
5913 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005914 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5915 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005916
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005917 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005918 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5919 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005920 }
5921
5922 return false;
5923}
5924
5925/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00005926/// as (const void*, size_t, ...) and can take one optional constant int arg.
5927bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5928 unsigned NumArgs = TheCall->getNumArgs();
5929
5930 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005931 return Diag(TheCall->getEndLoc(),
5932 diag::err_typecheck_call_too_many_args_at_most)
5933 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005934
5935 // The alignment must be a constant integer.
5936 Expr *Arg = TheCall->getArg(1);
5937
5938 // We can't check the value of a dependent argument.
5939 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5940 llvm::APSInt Result;
5941 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5942 return true;
5943
5944 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005945 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5946 << Arg->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005947 }
5948
5949 if (NumArgs > 2) {
5950 ExprResult Arg(TheCall->getArg(2));
5951 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5952 Context.getSizeType(), false);
5953 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5954 if (Arg.isInvalid()) return true;
5955 TheCall->setArg(2, Arg.get());
5956 }
Hal Finkelf0417332014-07-17 14:25:55 +00005957
5958 return false;
5959}
5960
Mehdi Amini06d367c2016-10-24 20:39:34 +00005961bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5962 unsigned BuiltinID =
5963 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5964 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5965
5966 unsigned NumArgs = TheCall->getNumArgs();
5967 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5968 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005969 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005970 << 0 /* function call */ << NumRequiredArgs << NumArgs
5971 << TheCall->getSourceRange();
5972 }
5973 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005974 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005975 diag::err_typecheck_call_too_many_args_at_most)
5976 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5977 << TheCall->getSourceRange();
5978 }
5979 unsigned i = 0;
5980
5981 // For formatting call, check buffer arg.
5982 if (!IsSizeCall) {
5983 ExprResult Arg(TheCall->getArg(i));
5984 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5985 Context, Context.VoidPtrTy, false);
5986 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5987 if (Arg.isInvalid())
5988 return true;
5989 TheCall->setArg(i, Arg.get());
5990 i++;
5991 }
5992
5993 // Check string literal arg.
5994 unsigned FormatIdx = i;
5995 {
5996 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5997 if (Arg.isInvalid())
5998 return true;
5999 TheCall->setArg(i, Arg.get());
6000 i++;
6001 }
6002
6003 // Make sure variadic args are scalar.
6004 unsigned FirstDataArg = i;
6005 while (i < NumArgs) {
6006 ExprResult Arg = DefaultVariadicArgumentPromotion(
6007 TheCall->getArg(i), VariadicFunction, nullptr);
6008 if (Arg.isInvalid())
6009 return true;
6010 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6011 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006012 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006013 << i << (int)ArgSize.getQuantity() << 0xff
6014 << TheCall->getSourceRange();
6015 }
6016 TheCall->setArg(i, Arg.get());
6017 i++;
6018 }
6019
6020 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6021 // call to avoid duplicate diagnostics.
6022 if (!IsSizeCall) {
6023 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6024 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6025 bool Success = CheckFormatArguments(
6026 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006027 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006028 CheckedVarArgs);
6029 if (!Success)
6030 return true;
6031 }
6032
6033 if (IsSizeCall) {
6034 TheCall->setType(Context.getSizeType());
6035 } else {
6036 TheCall->setType(Context.VoidPtrTy);
6037 }
6038 return false;
6039}
6040
Eric Christopher8d0c6212010-04-17 02:26:23 +00006041/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6042/// TheCall is a constant expression.
6043bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6044 llvm::APSInt &Result) {
6045 Expr *Arg = TheCall->getArg(ArgNum);
6046 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6047 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00006048
Eric Christopher8d0c6212010-04-17 02:26:23 +00006049 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006050
Eric Christopher8d0c6212010-04-17 02:26:23 +00006051 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006052 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6053 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00006054
Chris Lattnerd545ad12009-09-23 06:06:36 +00006055 return false;
6056}
6057
Richard Sandiford28940af2014-04-16 08:47:51 +00006058/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6059/// TheCall is a constant expression in the range [Low, High].
6060bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006061 int Low, int High, bool RangeIsError) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00006062 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006063
6064 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00006065 Expr *Arg = TheCall->getArg(ArgNum);
6066 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006067 return false;
6068
Eric Christopher8d0c6212010-04-17 02:26:23 +00006069 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00006070 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00006071 return true;
6072
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006073 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6074 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006075 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006076 << Result.toString(10) << Low << High << Arg->getSourceRange();
6077 else
6078 // Defer the warning until we know if the code will be emitted so that
6079 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006080 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6081 PDiag(diag::warn_argument_invalid_range)
6082 << Result.toString(10) << Low << High
6083 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006084 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00006085
6086 return false;
6087}
6088
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006089/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6090/// TheCall is a constant expression is a multiple of Num..
6091bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6092 unsigned Num) {
6093 llvm::APSInt Result;
6094
6095 // We can't check the value of a dependent argument.
6096 Expr *Arg = TheCall->getArg(ArgNum);
6097 if (Arg->isTypeDependent() || Arg->isValueDependent())
6098 return false;
6099
6100 // Check constant-ness first.
6101 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6102 return true;
6103
6104 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006105 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6106 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006107
6108 return false;
6109}
6110
Javed Absar18b0c402019-04-26 21:08:11 +00006111/// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6112bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6113 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6114 if (checkArgCount(*this, TheCall, 2))
6115 return true;
6116 Expr *Arg0 = TheCall->getArg(0);
6117 Expr *Arg1 = TheCall->getArg(1);
6118
6119 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6120 if (FirstArg.isInvalid())
6121 return true;
6122 QualType FirstArgType = FirstArg.get()->getType();
6123 if (!FirstArgType->isAnyPointerType())
6124 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6125 << "first" << FirstArgType << Arg0->getSourceRange();
6126 TheCall->setArg(0, FirstArg.get());
6127
6128 ExprResult SecArg = DefaultLvalueConversion(Arg1);
6129 if (SecArg.isInvalid())
6130 return true;
6131 QualType SecArgType = SecArg.get()->getType();
6132 if (!SecArgType->isIntegerType())
6133 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6134 << "second" << SecArgType << Arg1->getSourceRange();
6135
6136 // Derive the return type from the pointer argument.
6137 TheCall->setType(FirstArgType);
6138 return false;
6139 }
6140
6141 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6142 if (checkArgCount(*this, TheCall, 2))
6143 return true;
6144
6145 Expr *Arg0 = TheCall->getArg(0);
6146 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6147 if (FirstArg.isInvalid())
6148 return true;
6149 QualType FirstArgType = FirstArg.get()->getType();
6150 if (!FirstArgType->isAnyPointerType())
6151 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6152 << "first" << FirstArgType << Arg0->getSourceRange();
6153 TheCall->setArg(0, FirstArg.get());
6154
6155 // Derive the return type from the pointer argument.
6156 TheCall->setType(FirstArgType);
6157
6158 // Second arg must be an constant in range [0,15]
6159 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6160 }
6161
6162 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6163 if (checkArgCount(*this, TheCall, 2))
6164 return true;
6165 Expr *Arg0 = TheCall->getArg(0);
6166 Expr *Arg1 = TheCall->getArg(1);
6167
6168 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6169 if (FirstArg.isInvalid())
6170 return true;
6171 QualType FirstArgType = FirstArg.get()->getType();
6172 if (!FirstArgType->isAnyPointerType())
6173 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6174 << "first" << FirstArgType << Arg0->getSourceRange();
6175
6176 QualType SecArgType = Arg1->getType();
6177 if (!SecArgType->isIntegerType())
6178 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6179 << "second" << SecArgType << Arg1->getSourceRange();
6180 TheCall->setType(Context.IntTy);
6181 return false;
6182 }
6183
6184 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6185 BuiltinID == AArch64::BI__builtin_arm_stg) {
6186 if (checkArgCount(*this, TheCall, 1))
6187 return true;
6188 Expr *Arg0 = TheCall->getArg(0);
6189 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6190 if (FirstArg.isInvalid())
6191 return true;
6192
6193 QualType FirstArgType = FirstArg.get()->getType();
6194 if (!FirstArgType->isAnyPointerType())
6195 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6196 << "first" << FirstArgType << Arg0->getSourceRange();
6197 TheCall->setArg(0, FirstArg.get());
6198
6199 // Derive the return type from the pointer argument.
6200 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6201 TheCall->setType(FirstArgType);
6202 return false;
6203 }
6204
6205 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6206 Expr *ArgA = TheCall->getArg(0);
6207 Expr *ArgB = TheCall->getArg(1);
6208
6209 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6210 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6211
6212 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6213 return true;
6214
6215 QualType ArgTypeA = ArgExprA.get()->getType();
6216 QualType ArgTypeB = ArgExprB.get()->getType();
6217
6218 auto isNull = [&] (Expr *E) -> bool {
6219 return E->isNullPointerConstant(
6220 Context, Expr::NPC_ValueDependentIsNotNull); };
6221
6222 // argument should be either a pointer or null
6223 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6224 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6225 << "first" << ArgTypeA << ArgA->getSourceRange();
6226
6227 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6228 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6229 << "second" << ArgTypeB << ArgB->getSourceRange();
6230
6231 // Ensure Pointee types are compatible
6232 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6233 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6234 QualType pointeeA = ArgTypeA->getPointeeType();
6235 QualType pointeeB = ArgTypeB->getPointeeType();
6236 if (!Context.typesAreCompatible(
6237 Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6238 Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6239 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6240 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6241 << ArgB->getSourceRange();
6242 }
6243 }
6244
6245 // at least one argument should be pointer type
6246 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6247 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6248 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6249
6250 if (isNull(ArgA)) // adopt type of the other pointer
6251 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6252
6253 if (isNull(ArgB))
6254 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6255
6256 TheCall->setArg(0, ArgExprA.get());
6257 TheCall->setArg(1, ArgExprB.get());
6258 TheCall->setType(Context.LongLongTy);
6259 return false;
6260 }
6261 assert(false && "Unhandled ARM MTE intrinsic");
6262 return true;
6263}
6264
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006265/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6266/// TheCall is an ARM/AArch64 special register string literal.
6267bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6268 int ArgNum, unsigned ExpectedFieldNum,
6269 bool AllowName) {
6270 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6271 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6272 BuiltinID == ARM::BI__builtin_arm_rsr ||
6273 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6274 BuiltinID == ARM::BI__builtin_arm_wsr ||
6275 BuiltinID == ARM::BI__builtin_arm_wsrp;
6276 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6277 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6278 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6279 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6280 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6281 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6282 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6283
6284 // We can't check the value of a dependent argument.
6285 Expr *Arg = TheCall->getArg(ArgNum);
6286 if (Arg->isTypeDependent() || Arg->isValueDependent())
6287 return false;
6288
6289 // Check if the argument is a string literal.
6290 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006291 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006292 << Arg->getSourceRange();
6293
6294 // Check the type of special register given.
6295 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6296 SmallVector<StringRef, 6> Fields;
6297 Reg.split(Fields, ":");
6298
6299 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006300 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006301 << Arg->getSourceRange();
6302
6303 // If the string is the name of a register then we cannot check that it is
6304 // valid here but if the string is of one the forms described in ACLE then we
6305 // can check that the supplied fields are integers and within the valid
6306 // ranges.
6307 if (Fields.size() > 1) {
6308 bool FiveFields = Fields.size() == 5;
6309
6310 bool ValidString = true;
6311 if (IsARMBuiltin) {
6312 ValidString &= Fields[0].startswith_lower("cp") ||
6313 Fields[0].startswith_lower("p");
6314 if (ValidString)
6315 Fields[0] =
6316 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6317
6318 ValidString &= Fields[2].startswith_lower("c");
6319 if (ValidString)
6320 Fields[2] = Fields[2].drop_front(1);
6321
6322 if (FiveFields) {
6323 ValidString &= Fields[3].startswith_lower("c");
6324 if (ValidString)
6325 Fields[3] = Fields[3].drop_front(1);
6326 }
6327 }
6328
6329 SmallVector<int, 5> Ranges;
6330 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006331 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006332 else
6333 Ranges.append({15, 7, 15});
6334
6335 for (unsigned i=0; i<Fields.size(); ++i) {
6336 int IntField;
6337 ValidString &= !Fields[i].getAsInteger(10, IntField);
6338 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6339 }
6340
6341 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006342 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006343 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006344 } else if (IsAArch64Builtin && Fields.size() == 1) {
6345 // If the register name is one of those that appear in the condition below
6346 // and the special register builtin being used is one of the write builtins,
6347 // then we require that the argument provided for writing to the register
6348 // is an integer constant expression. This is because it will be lowered to
6349 // an MSR (immediate) instruction, so we need to know the immediate at
6350 // compile time.
6351 if (TheCall->getNumArgs() != 2)
6352 return false;
6353
6354 std::string RegLower = Reg.lower();
6355 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6356 RegLower != "pan" && RegLower != "uao")
6357 return false;
6358
6359 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6360 }
6361
6362 return false;
6363}
6364
Eli Friedmanc97d0142009-05-03 06:04:26 +00006365/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006366/// This checks that the target supports __builtin_longjmp and
6367/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006368bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006369 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006370 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006371 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006372
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006373 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006374 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006375
Eric Christopher8d0c6212010-04-17 02:26:23 +00006376 // TODO: This is less than ideal. Overload this to take a value.
6377 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6378 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006379
Eric Christopher8d0c6212010-04-17 02:26:23 +00006380 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006381 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006382 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006383
6384 return false;
6385}
6386
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006387/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6388/// This checks that the target supports __builtin_setjmp.
6389bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6390 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006391 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006392 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006393 return false;
6394}
6395
Richard Smithd7293d72013-08-05 18:49:43 +00006396namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006397
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006398class UncoveredArgHandler {
6399 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006400
6401 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006402 SmallVector<const Expr *, 4> DiagnosticExprs;
6403
6404public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006405 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006406
6407 bool hasUncoveredArg() const {
6408 return (FirstUncoveredArg >= 0);
6409 }
6410
6411 unsigned getUncoveredArg() const {
6412 assert(hasUncoveredArg() && "no uncovered argument");
6413 return FirstUncoveredArg;
6414 }
6415
6416 void setAllCovered() {
6417 // A string has been found with all arguments covered, so clear out
6418 // the diagnostics.
6419 DiagnosticExprs.clear();
6420 FirstUncoveredArg = AllCovered;
6421 }
6422
6423 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6424 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6425
6426 // Don't update if a previous string covers all arguments.
6427 if (FirstUncoveredArg == AllCovered)
6428 return;
6429
6430 // UncoveredArgHandler tracks the highest uncovered argument index
6431 // and with it all the strings that match this index.
6432 if (NewFirstUncoveredArg == FirstUncoveredArg)
6433 DiagnosticExprs.push_back(StrExpr);
6434 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6435 DiagnosticExprs.clear();
6436 DiagnosticExprs.push_back(StrExpr);
6437 FirstUncoveredArg = NewFirstUncoveredArg;
6438 }
6439 }
6440
6441 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6442};
6443
Richard Smithd7293d72013-08-05 18:49:43 +00006444enum StringLiteralCheckType {
6445 SLCT_NotALiteral,
6446 SLCT_UncheckedLiteral,
6447 SLCT_CheckedLiteral
6448};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006449
6450} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006451
Stephen Hines648c3692016-09-16 01:07:04 +00006452static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6453 BinaryOperatorKind BinOpKind,
6454 bool AddendIsRight) {
6455 unsigned BitWidth = Offset.getBitWidth();
6456 unsigned AddendBitWidth = Addend.getBitWidth();
6457 // There might be negative interim results.
6458 if (Addend.isUnsigned()) {
6459 Addend = Addend.zext(++AddendBitWidth);
6460 Addend.setIsSigned(true);
6461 }
6462 // Adjust the bit width of the APSInts.
6463 if (AddendBitWidth > BitWidth) {
6464 Offset = Offset.sext(AddendBitWidth);
6465 BitWidth = AddendBitWidth;
6466 } else if (BitWidth > AddendBitWidth) {
6467 Addend = Addend.sext(BitWidth);
6468 }
6469
6470 bool Ov = false;
6471 llvm::APSInt ResOffset = Offset;
6472 if (BinOpKind == BO_Add)
6473 ResOffset = Offset.sadd_ov(Addend, Ov);
6474 else {
6475 assert(AddendIsRight && BinOpKind == BO_Sub &&
6476 "operator must be add or sub with addend on the right");
6477 ResOffset = Offset.ssub_ov(Addend, Ov);
6478 }
6479
6480 // We add an offset to a pointer here so we should support an offset as big as
6481 // possible.
6482 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006483 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6484 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006485 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006486 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6487 return;
6488 }
6489
6490 Offset = ResOffset;
6491}
6492
6493namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006494
Stephen Hines648c3692016-09-16 01:07:04 +00006495// This is a wrapper class around StringLiteral to support offsetted string
6496// literals as format strings. It takes the offset into account when returning
6497// the string and its length or the source locations to display notes correctly.
6498class FormatStringLiteral {
6499 const StringLiteral *FExpr;
6500 int64_t Offset;
6501
6502 public:
6503 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6504 : FExpr(fexpr), Offset(Offset) {}
6505
6506 StringRef getString() const {
6507 return FExpr->getString().drop_front(Offset);
6508 }
6509
6510 unsigned getByteLength() const {
6511 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6512 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006513
Stephen Hines648c3692016-09-16 01:07:04 +00006514 unsigned getLength() const { return FExpr->getLength() - Offset; }
6515 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6516
6517 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6518
6519 QualType getType() const { return FExpr->getType(); }
6520
6521 bool isAscii() const { return FExpr->isAscii(); }
6522 bool isWide() const { return FExpr->isWide(); }
6523 bool isUTF8() const { return FExpr->isUTF8(); }
6524 bool isUTF16() const { return FExpr->isUTF16(); }
6525 bool isUTF32() const { return FExpr->isUTF32(); }
6526 bool isPascal() const { return FExpr->isPascal(); }
6527
6528 SourceLocation getLocationOfByte(
6529 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6530 const TargetInfo &Target, unsigned *StartToken = nullptr,
6531 unsigned *StartTokenByteOffset = nullptr) const {
6532 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6533 StartToken, StartTokenByteOffset);
6534 }
6535
Stephen Kelly724e9e52018-08-09 20:05:03 +00006536 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006537 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006538 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006539
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006540 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006541};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006542
6543} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006544
6545static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006546 const Expr *OrigFormatExpr,
6547 ArrayRef<const Expr *> Args,
6548 bool HasVAListArg, unsigned format_idx,
6549 unsigned firstDataArg,
6550 Sema::FormatStringType Type,
6551 bool inFunctionCall,
6552 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006553 llvm::SmallBitVector &CheckedVarArgs,
6554 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006555
Richard Smith55ce3522012-06-25 20:30:08 +00006556// Determine if an expression is a string literal or constant string.
6557// If this function returns false on the arguments to a function expecting a
6558// format string, we will usually need to emit a warning.
6559// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006560static StringLiteralCheckType
6561checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6562 bool HasVAListArg, unsigned format_idx,
6563 unsigned firstDataArg, Sema::FormatStringType Type,
6564 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006565 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006566 UncoveredArgHandler &UncoveredArg,
6567 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00006568 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006569 assert(Offset.isSigned() && "invalid offset");
6570
Douglas Gregorc25f7662009-05-19 22:10:17 +00006571 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006572 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006573
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006574 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006575
Richard Smithd7293d72013-08-05 18:49:43 +00006576 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006577 // Technically -Wformat-nonliteral does not warn about this case.
6578 // The behavior of printf and friends in this case is implementation
6579 // dependent. Ideally if the format string cannot be null then
6580 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006581 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006582
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006583 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006584 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006585 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006586 // The expression is a literal if both sub-expressions were, and it was
6587 // completely checked only if both sub-expressions were checked.
6588 const AbstractConditionalOperator *C =
6589 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006590
6591 // Determine whether it is necessary to check both sub-expressions, for
6592 // example, because the condition expression is a constant that can be
6593 // evaluated at compile time.
6594 bool CheckLeft = true, CheckRight = true;
6595
6596 bool Cond;
6597 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6598 if (Cond)
6599 CheckRight = false;
6600 else
6601 CheckLeft = false;
6602 }
6603
Stephen Hines648c3692016-09-16 01:07:04 +00006604 // We need to maintain the offsets for the right and the left hand side
6605 // separately to check if every possible indexed expression is a valid
6606 // string literal. They might have different offsets for different string
6607 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006608 StringLiteralCheckType Left;
6609 if (!CheckLeft)
6610 Left = SLCT_UncheckedLiteral;
6611 else {
6612 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6613 HasVAListArg, format_idx, firstDataArg,
6614 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00006615 CheckedVarArgs, UncoveredArg, Offset);
6616 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006617 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006618 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006619 }
6620
Richard Smith55ce3522012-06-25 20:30:08 +00006621 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00006622 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006623 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006624 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006625 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006626
6627 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006628 }
6629
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006630 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006631 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6632 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006633
John McCallc07a0c72011-02-17 10:25:35 +00006634 case Stmt::OpaqueValueExprClass:
6635 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6636 E = src;
6637 goto tryAgain;
6638 }
Richard Smith55ce3522012-06-25 20:30:08 +00006639 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006640
Ted Kremeneka8890832011-02-24 23:03:04 +00006641 case Stmt::PredefinedExprClass:
6642 // While __func__, etc., are technically not string literals, they
6643 // cannot contain format specifiers and thus are not a security
6644 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006645 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006646
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006647 case Stmt::DeclRefExprClass: {
6648 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006649
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006650 // As an exception, do not flag errors for variables binding to
6651 // const string literals.
6652 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6653 bool isConstant = false;
6654 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006655
Richard Smithd7293d72013-08-05 18:49:43 +00006656 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6657 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006658 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006659 isConstant = T.isConstant(S.Context) &&
6660 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006661 } else if (T->isObjCObjectPointerType()) {
6662 // In ObjC, there is usually no "const ObjectPointer" type,
6663 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006664 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006665 }
Mike Stump11289f42009-09-09 15:08:12 +00006666
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006667 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006668 if (const Expr *Init = VD->getAnyInitializer()) {
6669 // Look through initializers like const char c[] = { "foo" }
6670 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6671 if (InitList->isStringLiteralInit())
6672 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6673 }
Richard Smithd7293d72013-08-05 18:49:43 +00006674 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006675 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006676 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006677 /*InFunctionCall*/ false, CheckedVarArgs,
6678 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006679 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006680 }
Mike Stump11289f42009-09-09 15:08:12 +00006681
Anders Carlssonb012ca92009-06-28 19:55:58 +00006682 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6683 // special check to see if the format string is a function parameter
6684 // of the function calling the printf function. If the function
6685 // has an attribute indicating it is a printf-like function, then we
6686 // should suppress warnings concerning non-literals being used in a call
6687 // to a vprintf function. For example:
6688 //
6689 // void
6690 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6691 // va_list ap;
6692 // va_start(ap, fmt);
6693 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6694 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006695 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006696 if (HasVAListArg) {
6697 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6698 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6699 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006700 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006701 // adjust for implicit parameter
6702 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6703 if (MD->isInstance())
6704 ++PVIndex;
6705 // We also check if the formats are compatible.
6706 // We can't pass a 'scanf' string to a 'printf' function.
6707 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006708 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006709 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006710 }
6711 }
6712 }
6713 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006714 }
Mike Stump11289f42009-09-09 15:08:12 +00006715
Richard Smith55ce3522012-06-25 20:30:08 +00006716 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006717 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006718
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006719 case Stmt::CallExprClass:
6720 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006721 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006722 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006723 bool IsFirst = true;
6724 StringLiteralCheckType CommonResult;
6725 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006726 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006727 StringLiteralCheckType Result = checkFormatStringExpr(
6728 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6729 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6730 if (IsFirst) {
6731 CommonResult = Result;
6732 IsFirst = false;
6733 }
6734 }
6735 if (!IsFirst)
6736 return CommonResult;
6737
6738 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006739 unsigned BuiltinID = FD->getBuiltinID();
6740 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6741 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6742 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006743 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006744 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006745 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006746 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006747 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006748 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006749 }
6750 }
Mike Stump11289f42009-09-09 15:08:12 +00006751
Richard Smith55ce3522012-06-25 20:30:08 +00006752 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006753 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006754 case Stmt::ObjCMessageExprClass: {
6755 const auto *ME = cast<ObjCMessageExpr>(E);
6756 if (const auto *ND = ME->getMethodDecl()) {
6757 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006758 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00006759 return checkFormatStringExpr(
6760 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6761 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6762 }
6763 }
6764
6765 return SLCT_NotALiteral;
6766 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006767 case Stmt::ObjCStringLiteralClass:
6768 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00006769 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006770
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006771 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006772 StrE = ObjCFExpr->getString();
6773 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006774 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006775
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006776 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006777 if (Offset.isNegative() || Offset > StrE->getLength()) {
6778 // TODO: It would be better to have an explicit warning for out of
6779 // bounds literals.
6780 return SLCT_NotALiteral;
6781 }
6782 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6783 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006784 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006785 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00006786 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006787 }
Mike Stump11289f42009-09-09 15:08:12 +00006788
Richard Smith55ce3522012-06-25 20:30:08 +00006789 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006790 }
Stephen Hines648c3692016-09-16 01:07:04 +00006791 case Stmt::BinaryOperatorClass: {
Stephen Hines648c3692016-09-16 01:07:04 +00006792 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6793
6794 // A string literal + an int offset is still a string literal.
6795 if (BinOp->isAdditiveOp()) {
Fangrui Song407659a2018-11-30 23:41:18 +00006796 Expr::EvalResult LResult, RResult;
6797
Stephen Hines648c3692016-09-16 01:07:04 +00006798 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6799 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6800
6801 if (LIsInt != RIsInt) {
6802 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6803
6804 if (LIsInt) {
6805 if (BinOpKind == BO_Add) {
Fangrui Song407659a2018-11-30 23:41:18 +00006806 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006807 E = BinOp->getRHS();
6808 goto tryAgain;
6809 }
6810 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00006811 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006812 E = BinOp->getLHS();
6813 goto tryAgain;
6814 }
6815 }
Stephen Hines648c3692016-09-16 01:07:04 +00006816 }
George Burgess IVd273aab2016-09-22 00:00:26 +00006817
6818 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00006819 }
6820 case Stmt::UnaryOperatorClass: {
6821 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6822 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006823 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Fangrui Song407659a2018-11-30 23:41:18 +00006824 Expr::EvalResult IndexResult;
Stephen Hines648c3692016-09-16 01:07:04 +00006825 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
Fangrui Song407659a2018-11-30 23:41:18 +00006826 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6827 /*RHS is int*/ true);
Stephen Hines648c3692016-09-16 01:07:04 +00006828 E = ASE->getBase();
6829 goto tryAgain;
6830 }
6831 }
6832
6833 return SLCT_NotALiteral;
6834 }
Mike Stump11289f42009-09-09 15:08:12 +00006835
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006836 default:
Richard Smith55ce3522012-06-25 20:30:08 +00006837 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006838 }
6839}
6840
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006841Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00006842 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00006843 .Case("scanf", FST_Scanf)
6844 .Cases("printf", "printf0", FST_Printf)
6845 .Cases("NSString", "CFString", FST_NSString)
6846 .Case("strftime", FST_Strftime)
6847 .Case("strfmon", FST_Strfmon)
6848 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6849 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6850 .Case("os_trace", FST_OSLog)
6851 .Case("os_log", FST_OSLog)
6852 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006853}
6854
Jordan Rose3e0ec582012-07-19 18:10:23 +00006855/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00006856/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00006857/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006858bool Sema::CheckFormatArguments(const FormatAttr *Format,
6859 ArrayRef<const Expr *> Args,
6860 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006861 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006862 SourceLocation Loc, SourceRange Range,
6863 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00006864 FormatStringInfo FSI;
6865 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006866 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00006867 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00006868 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00006869 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006870}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00006871
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006872bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006873 bool HasVAListArg, unsigned format_idx,
6874 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006875 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006876 SourceLocation Loc, SourceRange Range,
6877 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00006878 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006879 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006880 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00006881 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006882 }
Mike Stump11289f42009-09-09 15:08:12 +00006883
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006884 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006885
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006886 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00006887 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006888 // Dynamically generated format strings are difficult to
6889 // automatically vet at compile time. Requiring that format strings
6890 // are string literals: (1) permits the checking of format strings by
6891 // the compiler and thereby (2) can practically remove the source of
6892 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00006893
Mike Stump11289f42009-09-09 15:08:12 +00006894 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00006895 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00006896 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00006897 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006898 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00006899 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00006900 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6901 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006902 /*IsFunctionCall*/ true, CheckedVarArgs,
6903 UncoveredArg,
6904 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006905
6906 // Generate a diagnostic where an uncovered argument is detected.
6907 if (UncoveredArg.hasUncoveredArg()) {
6908 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6909 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6910 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6911 }
6912
Richard Smith55ce3522012-06-25 20:30:08 +00006913 if (CT != SLCT_NotALiteral)
6914 // Literal format string found, check done!
6915 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00006916
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006917 // Strftime is particular as it always uses a single 'time' argument,
6918 // so it is safe to pass a non-literal string.
6919 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00006920 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006921
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006922 // Do not emit diag when the string param is a macro expansion and the
6923 // format is either NSString or CFString. This is a hack to prevent
6924 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6925 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006926 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006927 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00006928 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006929
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006930 // If there are no arguments specified, warn with -Wformat-security, otherwise
6931 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006932 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00006933 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6934 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006935 switch (Type) {
6936 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006937 break;
6938 case FST_Kprintf:
6939 case FST_FreeBSDKPrintf:
6940 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00006941 Diag(FormatLoc, diag::note_format_security_fixit)
6942 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006943 break;
6944 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00006945 Diag(FormatLoc, diag::note_format_security_fixit)
6946 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006947 break;
6948 }
6949 } else {
6950 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006951 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006952 }
Richard Smith55ce3522012-06-25 20:30:08 +00006953 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006954}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006955
Ted Kremenekab278de2010-01-28 23:39:18 +00006956namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006957
Ted Kremenek02087932010-07-16 02:11:22 +00006958class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6959protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00006960 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00006961 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00006962 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006963 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00006964 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00006965 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00006966 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00006967 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006968 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00006969 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00006970 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006971 bool usesPositionalArgs = false;
6972 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006973 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00006974 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00006975 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006976 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006977
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006978public:
Stephen Hines648c3692016-09-16 01:07:04 +00006979 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006980 const Expr *origFormatExpr,
6981 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006982 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006983 ArrayRef<const Expr *> Args, unsigned formatIdx,
6984 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006985 llvm::SmallBitVector &CheckedVarArgs,
6986 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006987 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6988 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6989 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006990 inFunctionCall(inFunctionCall), CallType(callType),
6991 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00006992 CoveredArgs.resize(numDataArgs);
6993 CoveredArgs.reset();
6994 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006995
Ted Kremenek019d2242010-01-29 01:50:07 +00006996 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006997
Ted Kremenek02087932010-07-16 02:11:22 +00006998 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006999 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007000
Jordan Rose92303592012-09-08 04:00:03 +00007001 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007002 const analyze_format_string::FormatSpecifier &FS,
7003 const analyze_format_string::ConversionSpecifier &CS,
7004 const char *startSpecifier, unsigned specifierLen,
7005 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00007006
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007007 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007008 const analyze_format_string::FormatSpecifier &FS,
7009 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007010
7011 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007012 const analyze_format_string::ConversionSpecifier &CS,
7013 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007014
Craig Toppere14c0f82014-03-12 04:55:44 +00007015 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007016
Craig Toppere14c0f82014-03-12 04:55:44 +00007017 void HandleInvalidPosition(const char *startSpecifier,
7018 unsigned specifierLen,
7019 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007020
Craig Toppere14c0f82014-03-12 04:55:44 +00007021 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007022
Craig Toppere14c0f82014-03-12 04:55:44 +00007023 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007024
Richard Trieu03cf7b72011-10-28 00:41:25 +00007025 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00007026 static void
7027 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7028 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7029 bool IsStringLocation, Range StringRange,
7030 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007031
Ted Kremenek02087932010-07-16 02:11:22 +00007032protected:
Ted Kremenekce815422010-07-19 21:25:57 +00007033 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7034 const char *startSpec,
7035 unsigned specifierLen,
7036 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007037
7038 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7039 const char *startSpec,
7040 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00007041
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007042 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00007043 CharSourceRange getSpecifierRange(const char *startSpecifier,
7044 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00007045 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007046
Ted Kremenek5739de72010-01-29 01:06:55 +00007047 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00007048
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007049 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7050 const analyze_format_string::ConversionSpecifier &CS,
7051 const char *startSpecifier, unsigned specifierLen,
7052 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007053
7054 template <typename Range>
7055 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7056 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007057 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00007058};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007059
7060} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007061
Ted Kremenek02087932010-07-16 02:11:22 +00007062SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00007063 return OrigFormatExpr->getSourceRange();
7064}
7065
Ted Kremenek02087932010-07-16 02:11:22 +00007066CharSourceRange CheckFormatHandler::
7067getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00007068 SourceLocation Start = getLocationOfByte(startSpecifier);
7069 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7070
7071 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007072 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00007073
7074 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007075}
7076
Ted Kremenek02087932010-07-16 02:11:22 +00007077SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00007078 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7079 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00007080}
7081
Ted Kremenek02087932010-07-16 02:11:22 +00007082void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7083 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00007084 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7085 getLocationOfByte(startSpecifier),
7086 /*IsStringLocation*/true,
7087 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00007088}
7089
Jordan Rose92303592012-09-08 04:00:03 +00007090void CheckFormatHandler::HandleInvalidLengthModifier(
7091 const analyze_format_string::FormatSpecifier &FS,
7092 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00007093 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00007094 using namespace analyze_format_string;
7095
7096 const LengthModifier &LM = FS.getLengthModifier();
7097 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7098
7099 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007100 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00007101 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007102 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007103 getLocationOfByte(LM.getStart()),
7104 /*IsStringLocation*/true,
7105 getSpecifierRange(startSpecifier, specifierLen));
7106
7107 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7108 << FixedLM->toString()
7109 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7110
7111 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007112 FixItHint Hint;
7113 if (DiagID == diag::warn_format_nonsensical_length)
7114 Hint = FixItHint::CreateRemoval(LMRange);
7115
7116 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007117 getLocationOfByte(LM.getStart()),
7118 /*IsStringLocation*/true,
7119 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00007120 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00007121 }
7122}
7123
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007124void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00007125 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007126 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007127 using namespace analyze_format_string;
7128
7129 const LengthModifier &LM = FS.getLengthModifier();
7130 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7131
7132 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007133 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00007134 if (FixedLM) {
7135 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7136 << LM.toString() << 0,
7137 getLocationOfByte(LM.getStart()),
7138 /*IsStringLocation*/true,
7139 getSpecifierRange(startSpecifier, specifierLen));
7140
7141 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7142 << FixedLM->toString()
7143 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7144
7145 } else {
7146 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7147 << LM.toString() << 0,
7148 getLocationOfByte(LM.getStart()),
7149 /*IsStringLocation*/true,
7150 getSpecifierRange(startSpecifier, specifierLen));
7151 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007152}
7153
7154void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7155 const analyze_format_string::ConversionSpecifier &CS,
7156 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00007157 using namespace analyze_format_string;
7158
7159 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00007160 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00007161 if (FixedCS) {
7162 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7163 << CS.toString() << /*conversion specifier*/1,
7164 getLocationOfByte(CS.getStart()),
7165 /*IsStringLocation*/true,
7166 getSpecifierRange(startSpecifier, specifierLen));
7167
7168 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7169 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7170 << FixedCS->toString()
7171 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7172 } else {
7173 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7174 << CS.toString() << /*conversion specifier*/1,
7175 getLocationOfByte(CS.getStart()),
7176 /*IsStringLocation*/true,
7177 getSpecifierRange(startSpecifier, specifierLen));
7178 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007179}
7180
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007181void CheckFormatHandler::HandlePosition(const char *startPos,
7182 unsigned posLen) {
7183 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7184 getLocationOfByte(startPos),
7185 /*IsStringLocation*/true,
7186 getSpecifierRange(startPos, posLen));
7187}
7188
Ted Kremenekd1668192010-02-27 01:41:03 +00007189void
Ted Kremenek02087932010-07-16 02:11:22 +00007190CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7191 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007192 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7193 << (unsigned) p,
7194 getLocationOfByte(startPos), /*IsStringLocation*/true,
7195 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007196}
7197
Ted Kremenek02087932010-07-16 02:11:22 +00007198void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00007199 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007200 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7201 getLocationOfByte(startPos),
7202 /*IsStringLocation*/true,
7203 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007204}
7205
Ted Kremenek02087932010-07-16 02:11:22 +00007206void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00007207 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007208 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007209 EmitFormatDiagnostic(
7210 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7211 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7212 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007213 }
Ted Kremenek02087932010-07-16 02:11:22 +00007214}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007215
Jordan Rose58bbe422012-07-19 18:10:08 +00007216// Note that this may return NULL if there was an error parsing or building
7217// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00007218const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007219 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00007220}
7221
7222void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007223 // Does the number of data arguments exceed the number of
7224 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00007225 if (!HasVAListArg) {
7226 // Find any arguments that weren't covered.
7227 CoveredArgs.flip();
7228 signed notCoveredArg = CoveredArgs.find_first();
7229 if (notCoveredArg >= 0) {
7230 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007231 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7232 } else {
7233 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00007234 }
7235 }
7236}
7237
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007238void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7239 const Expr *ArgExpr) {
7240 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7241 "Invalid state");
7242
7243 if (!ArgExpr)
7244 return;
7245
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007246 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007247
7248 if (S.getSourceManager().isInSystemMacro(Loc))
7249 return;
7250
7251 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7252 for (auto E : DiagnosticExprs)
7253 PDiag << E->getSourceRange();
7254
7255 CheckFormatHandler::EmitFormatDiagnostic(
7256 S, IsFunctionCall, DiagnosticExprs[0],
7257 PDiag, Loc, /*IsStringLocation*/false,
7258 DiagnosticExprs[0]->getSourceRange());
7259}
7260
Ted Kremenekce815422010-07-19 21:25:57 +00007261bool
7262CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7263 SourceLocation Loc,
7264 const char *startSpec,
7265 unsigned specifierLen,
7266 const char *csStart,
7267 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00007268 bool keepGoing = true;
7269 if (argIndex < NumDataArgs) {
7270 // Consider the argument coverered, even though the specifier doesn't
7271 // make sense.
7272 CoveredArgs.set(argIndex);
7273 }
7274 else {
7275 // If argIndex exceeds the number of data arguments we
7276 // don't issue a warning because that is just a cascade of warnings (and
7277 // they may have intended '%%' anyway). We don't want to continue processing
7278 // the format string after this point, however, as we will like just get
7279 // gibberish when trying to match arguments.
7280 keepGoing = false;
7281 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007282
7283 StringRef Specifier(csStart, csLen);
7284
7285 // If the specifier in non-printable, it could be the first byte of a UTF-8
7286 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7287 // hex value.
7288 std::string CodePointStr;
7289 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00007290 llvm::UTF32 CodePoint;
7291 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7292 const llvm::UTF8 *E =
7293 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7294 llvm::ConversionResult Result =
7295 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007296
Justin Lebar90910552016-09-30 00:38:45 +00007297 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007298 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00007299 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007300 }
7301
7302 llvm::raw_string_ostream OS(CodePointStr);
7303 if (CodePoint < 256)
7304 OS << "\\x" << llvm::format("%02x", CodePoint);
7305 else if (CodePoint <= 0xFFFF)
7306 OS << "\\u" << llvm::format("%04x", CodePoint);
7307 else
7308 OS << "\\U" << llvm::format("%08x", CodePoint);
7309 OS.flush();
7310 Specifier = CodePointStr;
7311 }
7312
7313 EmitFormatDiagnostic(
7314 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7315 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7316
Ted Kremenekce815422010-07-19 21:25:57 +00007317 return keepGoing;
7318}
7319
Richard Trieu03cf7b72011-10-28 00:41:25 +00007320void
7321CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7322 const char *startSpec,
7323 unsigned specifierLen) {
7324 EmitFormatDiagnostic(
7325 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7326 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7327}
7328
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007329bool
7330CheckFormatHandler::CheckNumArgs(
7331 const analyze_format_string::FormatSpecifier &FS,
7332 const analyze_format_string::ConversionSpecifier &CS,
7333 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7334
7335 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007336 PartialDiagnostic PDiag = FS.usesPositionalArg()
7337 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7338 << (argIndex+1) << NumDataArgs)
7339 : S.PDiag(diag::warn_printf_insufficient_data_args);
7340 EmitFormatDiagnostic(
7341 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7342 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007343
7344 // Since more arguments than conversion tokens are given, by extension
7345 // all arguments are covered, so mark this as so.
7346 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007347 return false;
7348 }
7349 return true;
7350}
7351
Richard Trieu03cf7b72011-10-28 00:41:25 +00007352template<typename Range>
7353void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7354 SourceLocation Loc,
7355 bool IsStringLocation,
7356 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007357 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007358 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007359 Loc, IsStringLocation, StringRange, FixIt);
7360}
7361
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007362/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007363/// so that the function call and string are in diagnostic messages.
7364///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007365/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007366/// call and only one diagnostic message will be produced. Otherwise, an
7367/// extra note will be emitted pointing to location of the format string.
7368///
7369/// \param ArgumentExpr the expression that is passed as the format string
7370/// argument in the function call. Used for getting locations when two
7371/// diagnostics are emitted.
7372///
7373/// \param PDiag the callee should already have provided any strings for the
7374/// diagnostic message. This function only adds locations and fixits
7375/// to diagnostics.
7376///
7377/// \param Loc primary location for diagnostic. If two diagnostics are
7378/// required, one will be at Loc and a new SourceLocation will be created for
7379/// the other one.
7380///
7381/// \param IsStringLocation if true, Loc points to the format string should be
7382/// used for the note. Otherwise, Loc points to the argument list and will
7383/// be used with PDiag.
7384///
7385/// \param StringRange some or all of the string to highlight. This is
7386/// templated so it can accept either a CharSourceRange or a SourceRange.
7387///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007388/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007389template <typename Range>
7390void CheckFormatHandler::EmitFormatDiagnostic(
7391 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7392 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7393 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007394 if (InFunctionCall) {
7395 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7396 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007397 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007398 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007399 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7400 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007401
7402 const Sema::SemaDiagnosticBuilder &Note =
7403 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7404 diag::note_format_string_defined);
7405
7406 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007407 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007408 }
7409}
7410
Ted Kremenek02087932010-07-16 02:11:22 +00007411//===--- CHECK: Printf format string checking ------------------------------===//
7412
7413namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007414
Ted Kremenek02087932010-07-16 02:11:22 +00007415class CheckPrintfHandler : public CheckFormatHandler {
7416public:
Stephen Hines648c3692016-09-16 01:07:04 +00007417 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007418 const Expr *origFormatExpr,
7419 const Sema::FormatStringType type, unsigned firstDataArg,
7420 unsigned numDataArgs, bool isObjC, const char *beg,
7421 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007422 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007423 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007424 llvm::SmallBitVector &CheckedVarArgs,
7425 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007426 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7427 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7428 inFunctionCall, CallType, CheckedVarArgs,
7429 UncoveredArg) {}
7430
7431 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7432
7433 /// Returns true if '%@' specifiers are allowed in the format string.
7434 bool allowsObjCArg() const {
7435 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7436 FSType == Sema::FST_OSTrace;
7437 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007438
Ted Kremenek02087932010-07-16 02:11:22 +00007439 bool HandleInvalidPrintfConversionSpecifier(
7440 const analyze_printf::PrintfSpecifier &FS,
7441 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007442 unsigned specifierLen) override;
7443
Akira Hatanakad572cf42018-11-06 07:05:14 +00007444 void handleInvalidMaskType(StringRef MaskType) override;
7445
Ted Kremenek02087932010-07-16 02:11:22 +00007446 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7447 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007448 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007449 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7450 const char *StartSpecifier,
7451 unsigned SpecifierLen,
7452 const Expr *E);
7453
Ted Kremenek02087932010-07-16 02:11:22 +00007454 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7455 const char *startSpecifier, unsigned specifierLen);
7456 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7457 const analyze_printf::OptionalAmount &Amt,
7458 unsigned type,
7459 const char *startSpecifier, unsigned specifierLen);
7460 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7461 const analyze_printf::OptionalFlag &flag,
7462 const char *startSpecifier, unsigned specifierLen);
7463 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7464 const analyze_printf::OptionalFlag &ignoredFlag,
7465 const analyze_printf::OptionalFlag &flag,
7466 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007467 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007468 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007469
Ted Kremenek2b417712015-07-02 05:39:16 +00007470 void HandleEmptyObjCModifierFlag(const char *startFlag,
7471 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007472
Ted Kremenek2b417712015-07-02 05:39:16 +00007473 void HandleInvalidObjCModifierFlag(const char *startFlag,
7474 unsigned flagLen) override;
7475
7476 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7477 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007478 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007479 override;
7480};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007481
7482} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007483
7484bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7485 const analyze_printf::PrintfSpecifier &FS,
7486 const char *startSpecifier,
7487 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007488 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007489 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007490
Ted Kremenekce815422010-07-19 21:25:57 +00007491 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7492 getLocationOfByte(CS.getStart()),
7493 startSpecifier, specifierLen,
7494 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007495}
7496
Akira Hatanakad572cf42018-11-06 07:05:14 +00007497void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7498 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7499}
7500
Ted Kremenek02087932010-07-16 02:11:22 +00007501bool CheckPrintfHandler::HandleAmount(
7502 const analyze_format_string::OptionalAmount &Amt,
7503 unsigned k, const char *startSpecifier,
7504 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007505 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007506 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007507 unsigned argIndex = Amt.getArgIndex();
7508 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007509 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7510 << k,
7511 getLocationOfByte(Amt.getStart()),
7512 /*IsStringLocation*/true,
7513 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007514 // Don't do any more checking. We will just emit
7515 // spurious errors.
7516 return false;
7517 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007518
Ted Kremenek5739de72010-01-29 01:06:55 +00007519 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007520 // Although not in conformance with C99, we also allow the argument to be
7521 // an 'unsigned int' as that is a reasonably safe case. GCC also
7522 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007523 CoveredArgs.set(argIndex);
7524 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007525 if (!Arg)
7526 return false;
7527
Ted Kremenek5739de72010-01-29 01:06:55 +00007528 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007529
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007530 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7531 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007532
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007533 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007534 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007535 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007536 << T << Arg->getSourceRange(),
7537 getLocationOfByte(Amt.getStart()),
7538 /*IsStringLocation*/true,
7539 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007540 // Don't do any more checking. We will just emit
7541 // spurious errors.
7542 return false;
7543 }
7544 }
7545 }
7546 return true;
7547}
Ted Kremenek5739de72010-01-29 01:06:55 +00007548
Tom Careb49ec692010-06-17 19:00:27 +00007549void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007550 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007551 const analyze_printf::OptionalAmount &Amt,
7552 unsigned type,
7553 const char *startSpecifier,
7554 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007555 const analyze_printf::PrintfConversionSpecifier &CS =
7556 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007557
Richard Trieu03cf7b72011-10-28 00:41:25 +00007558 FixItHint fixit =
7559 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7560 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7561 Amt.getConstantLength()))
7562 : FixItHint();
7563
7564 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7565 << type << CS.toString(),
7566 getLocationOfByte(Amt.getStart()),
7567 /*IsStringLocation*/true,
7568 getSpecifierRange(startSpecifier, specifierLen),
7569 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007570}
7571
Ted Kremenek02087932010-07-16 02:11:22 +00007572void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007573 const analyze_printf::OptionalFlag &flag,
7574 const char *startSpecifier,
7575 unsigned specifierLen) {
7576 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007577 const analyze_printf::PrintfConversionSpecifier &CS =
7578 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007579 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7580 << flag.toString() << CS.toString(),
7581 getLocationOfByte(flag.getPosition()),
7582 /*IsStringLocation*/true,
7583 getSpecifierRange(startSpecifier, specifierLen),
7584 FixItHint::CreateRemoval(
7585 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007586}
7587
7588void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007589 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007590 const analyze_printf::OptionalFlag &ignoredFlag,
7591 const analyze_printf::OptionalFlag &flag,
7592 const char *startSpecifier,
7593 unsigned specifierLen) {
7594 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007595 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7596 << ignoredFlag.toString() << flag.toString(),
7597 getLocationOfByte(ignoredFlag.getPosition()),
7598 /*IsStringLocation*/true,
7599 getSpecifierRange(startSpecifier, specifierLen),
7600 FixItHint::CreateRemoval(
7601 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007602}
7603
Ted Kremenek2b417712015-07-02 05:39:16 +00007604void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7605 unsigned flagLen) {
7606 // Warn about an empty flag.
7607 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7608 getLocationOfByte(startFlag),
7609 /*IsStringLocation*/true,
7610 getSpecifierRange(startFlag, flagLen));
7611}
7612
7613void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7614 unsigned flagLen) {
7615 // Warn about an invalid flag.
7616 auto Range = getSpecifierRange(startFlag, flagLen);
7617 StringRef flag(startFlag, flagLen);
7618 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7619 getLocationOfByte(startFlag),
7620 /*IsStringLocation*/true,
7621 Range, FixItHint::CreateRemoval(Range));
7622}
7623
7624void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7625 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7626 // Warn about using '[...]' without a '@' conversion.
7627 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7628 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7629 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7630 getLocationOfByte(conversionPosition),
7631 /*IsStringLocation*/true,
7632 Range, FixItHint::CreateRemoval(Range));
7633}
7634
Richard Smith55ce3522012-06-25 20:30:08 +00007635// Determines if the specified is a C++ class or struct containing
7636// a member with the specified name and kind (e.g. a CXXMethodDecl named
7637// "c_str()").
7638template<typename MemberKind>
7639static llvm::SmallPtrSet<MemberKind*, 1>
7640CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7641 const RecordType *RT = Ty->getAs<RecordType>();
7642 llvm::SmallPtrSet<MemberKind*, 1> Results;
7643
7644 if (!RT)
7645 return Results;
7646 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007647 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007648 return Results;
7649
Alp Tokerb6cc5922014-05-03 03:45:55 +00007650 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007651 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007652 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007653
7654 // We just need to include all members of the right kind turned up by the
7655 // filter, at this point.
7656 if (S.LookupQualifiedName(R, RT->getDecl()))
7657 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7658 NamedDecl *decl = (*I)->getUnderlyingDecl();
7659 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7660 Results.insert(FK);
7661 }
7662 return Results;
7663}
7664
Richard Smith2868a732014-02-28 01:36:39 +00007665/// Check if we could call '.c_str()' on an object.
7666///
7667/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7668/// allow the call, or if it would be ambiguous).
7669bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007670 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7671
Richard Smith2868a732014-02-28 01:36:39 +00007672 MethodSet Results =
7673 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7674 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7675 MI != ME; ++MI)
7676 if ((*MI)->getMinRequiredArguments() == 0)
7677 return true;
7678 return false;
7679}
7680
Richard Smith55ce3522012-06-25 20:30:08 +00007681// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007682// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007683// Returns true when a c_str() conversion method is found.
7684bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007685 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007686 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007687
7688 MethodSet Results =
7689 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7690
7691 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7692 MI != ME; ++MI) {
7693 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007694 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007695 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007696 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007697 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007698 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7699 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007700 return true;
7701 }
7702 }
7703
7704 return false;
7705}
7706
Ted Kremenekab278de2010-01-28 23:39:18 +00007707bool
Ted Kremenek02087932010-07-16 02:11:22 +00007708CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007709 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007710 const char *startSpecifier,
7711 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007712 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007713 using namespace analyze_printf;
7714
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007715 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007716
Ted Kremenek6cd69422010-07-19 22:01:06 +00007717 if (FS.consumesDataArgument()) {
7718 if (atFirstArg) {
7719 atFirstArg = false;
7720 usesPositionalArgs = FS.usesPositionalArg();
7721 }
7722 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007723 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7724 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007725 return false;
7726 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007727 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007728
Ted Kremenekd1668192010-02-27 01:41:03 +00007729 // First check if the field width, precision, and conversion specifier
7730 // have matching data arguments.
7731 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7732 startSpecifier, specifierLen)) {
7733 return false;
7734 }
7735
7736 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7737 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007738 return false;
7739 }
7740
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007741 if (!CS.consumesDataArgument()) {
7742 // FIXME: Technically specifying a precision or field width here
7743 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00007744 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007745 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007746
Ted Kremenek4a49d982010-02-26 19:18:41 +00007747 // Consume the argument.
7748 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00007749 if (argIndex < NumDataArgs) {
7750 // The check to see if the argIndex is valid will come later.
7751 // We set the bit here because we may exit early from this
7752 // function if we encounter some other error.
7753 CoveredArgs.set(argIndex);
7754 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00007755
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007756 // FreeBSD kernel extensions.
7757 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7758 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7759 // We need at least two arguments.
7760 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7761 return false;
7762
7763 // Claim the second argument.
7764 CoveredArgs.set(argIndex + 1);
7765
7766 // Type check the first argument (int for %b, pointer for %D)
7767 const Expr *Ex = getDataArg(argIndex);
7768 const analyze_printf::ArgType &AT =
7769 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7770 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7771 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7772 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007773 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7774 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7775 << false << Ex->getSourceRange(),
7776 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7777 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007778
7779 // Type check the second argument (char * for both %b and %D)
7780 Ex = getDataArg(argIndex + 1);
7781 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7782 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7783 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007784 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7785 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7786 << false << Ex->getSourceRange(),
7787 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7788 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007789
7790 return true;
7791 }
7792
Ted Kremenek4a49d982010-02-26 19:18:41 +00007793 // Check for using an Objective-C specific conversion specifier
7794 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007795 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00007796 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7797 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00007798 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007799
Mehdi Amini06d367c2016-10-24 20:39:34 +00007800 // %P can only be used with os_log.
7801 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7802 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7803 specifierLen);
7804 }
7805
7806 // %n is not allowed with os_log.
7807 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7808 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7809 getLocationOfByte(CS.getStart()),
7810 /*IsStringLocation*/ false,
7811 getSpecifierRange(startSpecifier, specifierLen));
7812
7813 return true;
7814 }
7815
7816 // Only scalars are allowed for os_trace.
7817 if (FSType == Sema::FST_OSTrace &&
7818 (CS.getKind() == ConversionSpecifier::PArg ||
7819 CS.getKind() == ConversionSpecifier::sArg ||
7820 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7821 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7822 specifierLen);
7823 }
7824
7825 // Check for use of public/private annotation outside of os_log().
7826 if (FSType != Sema::FST_OSLog) {
7827 if (FS.isPublic().isSet()) {
7828 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7829 << "public",
7830 getLocationOfByte(FS.isPublic().getPosition()),
7831 /*IsStringLocation*/ false,
7832 getSpecifierRange(startSpecifier, specifierLen));
7833 }
7834 if (FS.isPrivate().isSet()) {
7835 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7836 << "private",
7837 getLocationOfByte(FS.isPrivate().getPosition()),
7838 /*IsStringLocation*/ false,
7839 getSpecifierRange(startSpecifier, specifierLen));
7840 }
7841 }
7842
Tom Careb49ec692010-06-17 19:00:27 +00007843 // Check for invalid use of field width
7844 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00007845 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00007846 startSpecifier, specifierLen);
7847 }
7848
7849 // Check for invalid use of precision
7850 if (!FS.hasValidPrecision()) {
7851 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7852 startSpecifier, specifierLen);
7853 }
7854
Mehdi Amini06d367c2016-10-24 20:39:34 +00007855 // Precision is mandatory for %P specifier.
7856 if (CS.getKind() == ConversionSpecifier::PArg &&
7857 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7858 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7859 getLocationOfByte(startSpecifier),
7860 /*IsStringLocation*/ false,
7861 getSpecifierRange(startSpecifier, specifierLen));
7862 }
7863
Tom Careb49ec692010-06-17 19:00:27 +00007864 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00007865 if (!FS.hasValidThousandsGroupingPrefix())
7866 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007867 if (!FS.hasValidLeadingZeros())
7868 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7869 if (!FS.hasValidPlusPrefix())
7870 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00007871 if (!FS.hasValidSpacePrefix())
7872 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007873 if (!FS.hasValidAlternativeForm())
7874 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7875 if (!FS.hasValidLeftJustified())
7876 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7877
7878 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00007879 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7880 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7881 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007882 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7883 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7884 startSpecifier, specifierLen);
7885
7886 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00007887 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7888 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007889 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7890 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007891 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007892 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007893 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007894 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7895 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00007896
Jordan Rose92303592012-09-08 04:00:03 +00007897 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7898 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7899
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007900 // The remaining checks depend on the data arguments.
7901 if (HasVAListArg)
7902 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007903
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007904 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007905 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007906
Jordan Rose58bbe422012-07-19 18:10:08 +00007907 const Expr *Arg = getDataArg(argIndex);
7908 if (!Arg)
7909 return true;
7910
7911 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00007912}
7913
Jordan Roseaee34382012-09-05 22:56:26 +00007914static bool requiresParensToAddCast(const Expr *E) {
7915 // FIXME: We should have a general way to reason about operator
7916 // precedence and whether parens are actually needed here.
7917 // Take care of a few common cases where they aren't.
7918 const Expr *Inside = E->IgnoreImpCasts();
7919 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7920 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7921
7922 switch (Inside->getStmtClass()) {
7923 case Stmt::ArraySubscriptExprClass:
7924 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007925 case Stmt::CharacterLiteralClass:
7926 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007927 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007928 case Stmt::FloatingLiteralClass:
7929 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007930 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007931 case Stmt::ObjCArrayLiteralClass:
7932 case Stmt::ObjCBoolLiteralExprClass:
7933 case Stmt::ObjCBoxedExprClass:
7934 case Stmt::ObjCDictionaryLiteralClass:
7935 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007936 case Stmt::ObjCIvarRefExprClass:
7937 case Stmt::ObjCMessageExprClass:
7938 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007939 case Stmt::ObjCStringLiteralClass:
7940 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007941 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007942 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007943 case Stmt::UnaryOperatorClass:
7944 return false;
7945 default:
7946 return true;
7947 }
7948}
7949
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007950static std::pair<QualType, StringRef>
7951shouldNotPrintDirectly(const ASTContext &Context,
7952 QualType IntendedTy,
7953 const Expr *E) {
7954 // Use a 'while' to peel off layers of typedefs.
7955 QualType TyTy = IntendedTy;
7956 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7957 StringRef Name = UserTy->getDecl()->getName();
7958 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00007959 .Case("CFIndex", Context.getNSIntegerType())
7960 .Case("NSInteger", Context.getNSIntegerType())
7961 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007962 .Case("SInt32", Context.IntTy)
7963 .Case("UInt32", Context.UnsignedIntTy)
7964 .Default(QualType());
7965
7966 if (!CastTy.isNull())
7967 return std::make_pair(CastTy, Name);
7968
7969 TyTy = UserTy->desugar();
7970 }
7971
7972 // Strip parens if necessary.
7973 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7974 return shouldNotPrintDirectly(Context,
7975 PE->getSubExpr()->getType(),
7976 PE->getSubExpr());
7977
7978 // If this is a conditional expression, then its result type is constructed
7979 // via usual arithmetic conversions and thus there might be no necessary
7980 // typedef sugar there. Recurse to operands to check for NSInteger &
7981 // Co. usage condition.
7982 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7983 QualType TrueTy, FalseTy;
7984 StringRef TrueName, FalseName;
7985
7986 std::tie(TrueTy, TrueName) =
7987 shouldNotPrintDirectly(Context,
7988 CO->getTrueExpr()->getType(),
7989 CO->getTrueExpr());
7990 std::tie(FalseTy, FalseName) =
7991 shouldNotPrintDirectly(Context,
7992 CO->getFalseExpr()->getType(),
7993 CO->getFalseExpr());
7994
7995 if (TrueTy == FalseTy)
7996 return std::make_pair(TrueTy, TrueName);
7997 else if (TrueTy.isNull())
7998 return std::make_pair(FalseTy, FalseName);
7999 else if (FalseTy.isNull())
8000 return std::make_pair(TrueTy, TrueName);
8001 }
8002
8003 return std::make_pair(QualType(), StringRef());
8004}
8005
Aaron Ballman94d2d092018-12-18 15:54:38 +00008006/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8007/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8008/// type do not count.
8009static bool
8010isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8011 QualType From = ICE->getSubExpr()->getType();
8012 QualType To = ICE->getType();
8013 // It's an integer promotion if the destination type is the promoted
8014 // source type.
8015 if (ICE->getCastKind() == CK_IntegralCast &&
8016 From->isPromotableIntegerType() &&
8017 S.Context.getPromotedIntegerType(From) == To)
8018 return true;
8019 // Look through vector types, since we do default argument promotion for
8020 // those in OpenCL.
8021 if (const auto *VecTy = From->getAs<ExtVectorType>())
8022 From = VecTy->getElementType();
8023 if (const auto *VecTy = To->getAs<ExtVectorType>())
8024 To = VecTy->getElementType();
8025 // It's a floating promotion if the source type is a lower rank.
8026 return ICE->getCastKind() == CK_FloatingCast &&
8027 S.Context.getFloatingTypeOrder(From, To) < 0;
8028}
8029
Richard Smith55ce3522012-06-25 20:30:08 +00008030bool
8031CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8032 const char *StartSpecifier,
8033 unsigned SpecifierLen,
8034 const Expr *E) {
8035 using namespace analyze_format_string;
8036 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008037
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008038 // Now type check the data expression that matches the
8039 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00008040 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00008041 if (!AT.isValid())
8042 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00008043
Jordan Rose598ec092012-12-05 18:44:40 +00008044 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00008045 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8046 ExprTy = TET->getUnderlyingExpr()->getType();
8047 }
8048
JF Bastienec7d7f32018-06-22 21:54:40 +00008049 const analyze_printf::ArgType::MatchKind Match =
8050 AT.matchesType(S.Context, ExprTy);
8051 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
8052 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00008053 return true;
Jordan Rose98709982012-06-04 22:48:57 +00008054
Jordan Rose22b74712012-09-05 22:56:19 +00008055 // Look through argument promotions for our error message's reported type.
8056 // This includes the integral and floating promotions, but excludes array
Aaron Ballman94d2d092018-12-18 15:54:38 +00008057 // and function pointer decay (seeing that an argument intended to be a
8058 // string has type 'char [6]' is probably more confusing than 'char *') and
8059 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
Jordan Rose22b74712012-09-05 22:56:19 +00008060 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Aaron Ballman94d2d092018-12-18 15:54:38 +00008061 if (isArithmeticArgumentPromotion(S, ICE)) {
Jordan Rose22b74712012-09-05 22:56:19 +00008062 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00008063 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00008064
8065 // Check if we didn't match because of an implicit cast from a 'char'
8066 // or 'short' to an 'int'. This is done because printf is a varargs
8067 // function.
8068 if (ICE->getType() == S.Context.IntTy ||
8069 ICE->getType() == S.Context.UnsignedIntTy) {
8070 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00008071 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00008072 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00008073 }
Jordan Rose98709982012-06-04 22:48:57 +00008074 }
Jordan Rose598ec092012-12-05 18:44:40 +00008075 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8076 // Special case for 'a', which has type 'int' in C.
8077 // Note, however, that we do /not/ want to treat multibyte constants like
8078 // 'MooV' as characters! This form is deprecated but still exists.
8079 if (ExprTy == S.Context.IntTy)
8080 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8081 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00008082 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008083
Jordan Rosebc53ed12014-05-31 04:12:14 +00008084 // Look through enums to their underlying type.
8085 bool IsEnum = false;
8086 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8087 ExprTy = EnumTy->getDecl()->getIntegerType();
8088 IsEnum = true;
8089 }
8090
Jordan Rose0e5badd2012-12-05 18:44:49 +00008091 // %C in an Objective-C context prints a unichar, not a wchar_t.
8092 // If the argument is an integer of some kind, believe the %C and suggest
8093 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00008094 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00008095 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00008096 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8097 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8098 !ExprTy->isCharType()) {
8099 // 'unichar' is defined as a typedef of unsigned short, but we should
8100 // prefer using the typedef if it is visible.
8101 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00008102
8103 // While we are here, check if the value is an IntegerLiteral that happens
8104 // to be within the valid range.
8105 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8106 const llvm::APInt &V = IL->getValue();
8107 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8108 return true;
8109 }
8110
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008111 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00008112 Sema::LookupOrdinaryName);
8113 if (S.LookupName(Result, S.getCurScope())) {
8114 NamedDecl *ND = Result.getFoundDecl();
8115 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8116 if (TD->getUnderlyingType() == IntendedTy)
8117 IntendedTy = S.Context.getTypedefType(TD);
8118 }
8119 }
8120 }
8121
8122 // Special-case some of Darwin's platform-independence types by suggesting
8123 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008124 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00008125 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008126 QualType CastTy;
8127 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8128 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008129 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00008130 // (long in ASTContext). Only complain to pedants.
8131 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008132 (AT.isSizeT() || AT.isPtrdiffT()) &&
8133 AT.matchesType(S.Context, CastTy))
JF Bastienec7d7f32018-06-22 21:54:40 +00008134 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008135 IntendedTy = CastTy;
8136 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00008137 }
8138 }
8139
Jordan Rose22b74712012-09-05 22:56:19 +00008140 // We may be able to offer a FixItHint if it is a supported type.
8141 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008142 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00008143 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008144
JF Bastienec7d7f32018-06-22 21:54:40 +00008145 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00008146 // Get the fix string from the fixed format specifier
8147 SmallString<16> buf;
8148 llvm::raw_svector_ostream os(buf);
8149 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008150
Jordan Roseaee34382012-09-05 22:56:26 +00008151 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8152
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008153 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00008154 unsigned Diag =
8155 Pedantic
8156 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8157 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00008158 // In this case, the specifier is wrong and should be changed to match
8159 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00008160 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00008161 << AT.getRepresentativeTypeName(S.Context)
8162 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008163 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00008164 /*IsStringLocation*/ false, SpecRange,
8165 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00008166 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00008167 // The canonical type for formatting this value is different from the
8168 // actual type of the expression. (This occurs, for example, with Darwin's
8169 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8170 // should be printed as 'long' for 64-bit compatibility.)
8171 // Rather than emitting a normal format/argument mismatch, we want to
8172 // add a cast to the recommended type (and correct the format string
8173 // if necessary).
8174 SmallString<16> CastBuf;
8175 llvm::raw_svector_ostream CastFix(CastBuf);
8176 CastFix << "(";
8177 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8178 CastFix << ")";
8179
8180 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00008181 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00008182 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8183
8184 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8185 // If there's already a cast present, just replace it.
8186 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8187 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8188
8189 } else if (!requiresParensToAddCast(E)) {
8190 // If the expression has high enough precedence,
8191 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008192 Hints.push_back(
8193 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008194 } else {
8195 // Otherwise, add parens around the expression as well as the cast.
8196 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008197 Hints.push_back(
8198 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008199
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008200 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00008201 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8202 }
8203
Jordan Rose0e5badd2012-12-05 18:44:49 +00008204 if (ShouldNotPrintDirectly) {
8205 // The expression has a type that should not be printed directly.
8206 // We extract the name from the typedef because we don't want to show
8207 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008208 StringRef Name;
8209 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8210 Name = TypedefTy->getDecl()->getName();
8211 else
8212 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00008213 unsigned Diag = Pedantic
8214 ? diag::warn_format_argument_needs_cast_pedantic
8215 : diag::warn_format_argument_needs_cast;
8216 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8217 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008218 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00008219 SpecRange, Hints);
8220 } else {
8221 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00008222 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00008223 // and we should cast instead. Just use the normal warning message.
8224 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008225 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8226 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8227 << E->getSourceRange(),
8228 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00008229 }
Jordan Roseaee34382012-09-05 22:56:26 +00008230 }
Jordan Rose22b74712012-09-05 22:56:19 +00008231 } else {
8232 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8233 SpecifierLen);
8234 // Since the warning for passing non-POD types to variadic functions
8235 // was deferred until now, we emit a warning for non-POD
8236 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00008237 switch (S.isValidVarArgType(ExprTy)) {
8238 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00008239 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00008240 unsigned Diag =
8241 Pedantic
8242 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8243 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00008244
Seth Cantrellb4802962015-03-04 03:12:10 +00008245 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008246 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00008247 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008248 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00008249 break;
8250 }
Richard Smithd7293d72013-08-05 18:49:43 +00008251 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00008252 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008253 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8254 << S.getLangOpts().CPlusPlus11 << ExprTy
8255 << CallType
8256 << AT.getRepresentativeTypeName(S.Context) << CSR
8257 << E->getSourceRange(),
8258 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00008259 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00008260 break;
8261
8262 case Sema::VAK_Invalid:
8263 if (ExprTy->isObjCObjectType())
8264 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008265 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8266 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8267 << AT.getRepresentativeTypeName(S.Context) << CSR
8268 << E->getSourceRange(),
8269 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00008270 else
8271 // FIXME: If this is an initializer list, suggest removing the braces
8272 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008273 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8274 << isa<InitListExpr>(E) << ExprTy << CallType
8275 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00008276 break;
8277 }
8278
8279 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8280 "format string specifier index out of range");
8281 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008282 }
8283
Ted Kremenekab278de2010-01-28 23:39:18 +00008284 return true;
8285}
8286
Ted Kremenek02087932010-07-16 02:11:22 +00008287//===--- CHECK: Scanf format string checking ------------------------------===//
8288
Fangrui Song6907ce22018-07-30 19:24:48 +00008289namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008290
Ted Kremenek02087932010-07-16 02:11:22 +00008291class CheckScanfHandler : public CheckFormatHandler {
8292public:
Stephen Hines648c3692016-09-16 01:07:04 +00008293 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00008294 const Expr *origFormatExpr, Sema::FormatStringType type,
8295 unsigned firstDataArg, unsigned numDataArgs,
8296 const char *beg, bool hasVAListArg,
8297 ArrayRef<const Expr *> Args, unsigned formatIdx,
8298 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008299 llvm::SmallBitVector &CheckedVarArgs,
8300 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00008301 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8302 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8303 inFunctionCall, CallType, CheckedVarArgs,
8304 UncoveredArg) {}
8305
Ted Kremenek02087932010-07-16 02:11:22 +00008306 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8307 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008308 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00008309
Ted Kremenekce815422010-07-19 21:25:57 +00008310 bool HandleInvalidScanfConversionSpecifier(
8311 const analyze_scanf::ScanfSpecifier &FS,
8312 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008313 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008314
Craig Toppere14c0f82014-03-12 04:55:44 +00008315 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00008316};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008317
8318} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00008319
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008320void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8321 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008322 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8323 getLocationOfByte(end), /*IsStringLocation*/true,
8324 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008325}
8326
Ted Kremenekce815422010-07-19 21:25:57 +00008327bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8328 const analyze_scanf::ScanfSpecifier &FS,
8329 const char *startSpecifier,
8330 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008331 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00008332 FS.getConversionSpecifier();
8333
8334 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8335 getLocationOfByte(CS.getStart()),
8336 startSpecifier, specifierLen,
8337 CS.getStart(), CS.getLength());
8338}
8339
Ted Kremenek02087932010-07-16 02:11:22 +00008340bool CheckScanfHandler::HandleScanfSpecifier(
8341 const analyze_scanf::ScanfSpecifier &FS,
8342 const char *startSpecifier,
8343 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008344 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008345 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008346
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008347 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008348
Ted Kremenek6cd69422010-07-19 22:01:06 +00008349 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8350 // be used to decide if we are using positional arguments consistently.
8351 if (FS.consumesDataArgument()) {
8352 if (atFirstArg) {
8353 atFirstArg = false;
8354 usesPositionalArgs = FS.usesPositionalArg();
8355 }
8356 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008357 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8358 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008359 return false;
8360 }
Ted Kremenek02087932010-07-16 02:11:22 +00008361 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008362
Ted Kremenek02087932010-07-16 02:11:22 +00008363 // Check if the field with is non-zero.
8364 const OptionalAmount &Amt = FS.getFieldWidth();
8365 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8366 if (Amt.getConstantAmount() == 0) {
8367 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8368 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008369 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8370 getLocationOfByte(Amt.getStart()),
8371 /*IsStringLocation*/true, R,
8372 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008373 }
8374 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008375
Ted Kremenek02087932010-07-16 02:11:22 +00008376 if (!FS.consumesDataArgument()) {
8377 // FIXME: Technically specifying a precision or field width here
8378 // makes no sense. Worth issuing a warning at some point.
8379 return true;
8380 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008381
Ted Kremenek02087932010-07-16 02:11:22 +00008382 // Consume the argument.
8383 unsigned argIndex = FS.getArgIndex();
8384 if (argIndex < NumDataArgs) {
8385 // The check to see if the argIndex is valid will come later.
8386 // We set the bit here because we may exit early from this
8387 // function if we encounter some other error.
8388 CoveredArgs.set(argIndex);
8389 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008390
Ted Kremenek4407ea42010-07-20 20:04:47 +00008391 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00008392 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8393 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008394 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8395 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008396 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008397 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008398 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008399 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8400 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008401
Jordan Rose92303592012-09-08 04:00:03 +00008402 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8403 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8404
Ted Kremenek02087932010-07-16 02:11:22 +00008405 // The remaining checks depend on the data arguments.
8406 if (HasVAListArg)
8407 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008408
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008409 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008410 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008411
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008412 // Check that the argument type matches the format specifier.
8413 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008414 if (!Ex)
8415 return true;
8416
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008417 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008418
8419 if (!AT.isValid()) {
8420 return true;
8421 }
8422
JF Bastienec7d7f32018-06-22 21:54:40 +00008423 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008424 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008425 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8426 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008427 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008428
Seth Cantrell79340072015-03-04 05:58:08 +00008429 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008430 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008431 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008432
JF Bastienec7d7f32018-06-22 21:54:40 +00008433 unsigned Diag =
8434 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8435 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008436
JF Bastienec7d7f32018-06-22 21:54:40 +00008437 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008438 // Get the fix string from the fixed format specifier.
8439 SmallString<128> buf;
8440 llvm::raw_svector_ostream os(buf);
8441 fixedFS.toString(os);
8442
8443 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008444 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008445 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008446 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008447 /*IsStringLocation*/ false,
8448 getSpecifierRange(startSpecifier, specifierLen),
8449 FixItHint::CreateReplacement(
8450 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8451 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008452 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008453 << AT.getRepresentativeTypeName(S.Context)
8454 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008455 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008456 /*IsStringLocation*/ false,
8457 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008458 }
8459
Ted Kremenek02087932010-07-16 02:11:22 +00008460 return true;
8461}
8462
Stephen Hines648c3692016-09-16 01:07:04 +00008463static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008464 const Expr *OrigFormatExpr,
8465 ArrayRef<const Expr *> Args,
8466 bool HasVAListArg, unsigned format_idx,
8467 unsigned firstDataArg,
8468 Sema::FormatStringType Type,
8469 bool inFunctionCall,
8470 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008471 llvm::SmallBitVector &CheckedVarArgs,
8472 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008473 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008474 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008475 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008476 S, inFunctionCall, Args[format_idx],
8477 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8478 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008479 return;
8480 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008481
Ted Kremenekab278de2010-01-28 23:39:18 +00008482 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008483 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008484 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008485 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008486 const ConstantArrayType *T =
8487 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008488 assert(T && "String literal not of constant array type!");
8489 size_t TypeSize = T->getSize().getZExtValue();
8490 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008491 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008492
8493 // Emit a warning if the string literal is truncated and does not contain an
8494 // embedded null character.
8495 if (TypeSize <= StrRef.size() &&
8496 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8497 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008498 S, inFunctionCall, Args[format_idx],
8499 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008500 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008501 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8502 return;
8503 }
8504
Ted Kremenekab278de2010-01-28 23:39:18 +00008505 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008506 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008507 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008508 S, inFunctionCall, Args[format_idx],
8509 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8510 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008511 return;
8512 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008513
8514 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008515 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8516 Type == Sema::FST_OSTrace) {
8517 CheckPrintfHandler H(
8518 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8519 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8520 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8521 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008522
Hans Wennborg23926bd2011-12-15 10:25:47 +00008523 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008524 S.getLangOpts(),
8525 S.Context.getTargetInfo(),
8526 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008527 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008528 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008529 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8530 numDataArgs, Str, HasVAListArg, Args, format_idx,
8531 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008532
Hans Wennborg23926bd2011-12-15 10:25:47 +00008533 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008534 S.getLangOpts(),
8535 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008536 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008537 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008538}
8539
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008540bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8541 // Str - The format string. NOTE: this is NOT null-terminated!
8542 StringRef StrRef = FExpr->getString();
8543 const char *Str = StrRef.data();
8544 // Account for cases where the string literal is truncated in a declaration.
8545 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8546 assert(T && "String literal not of constant array type!");
8547 size_t TypeSize = T->getSize().getZExtValue();
8548 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8549 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8550 getLangOpts(),
8551 Context.getTargetInfo());
8552}
8553
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008554//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8555
8556// Returns the related absolute value function that is larger, of 0 if one
8557// does not exist.
8558static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8559 switch (AbsFunction) {
8560 default:
8561 return 0;
8562
8563 case Builtin::BI__builtin_abs:
8564 return Builtin::BI__builtin_labs;
8565 case Builtin::BI__builtin_labs:
8566 return Builtin::BI__builtin_llabs;
8567 case Builtin::BI__builtin_llabs:
8568 return 0;
8569
8570 case Builtin::BI__builtin_fabsf:
8571 return Builtin::BI__builtin_fabs;
8572 case Builtin::BI__builtin_fabs:
8573 return Builtin::BI__builtin_fabsl;
8574 case Builtin::BI__builtin_fabsl:
8575 return 0;
8576
8577 case Builtin::BI__builtin_cabsf:
8578 return Builtin::BI__builtin_cabs;
8579 case Builtin::BI__builtin_cabs:
8580 return Builtin::BI__builtin_cabsl;
8581 case Builtin::BI__builtin_cabsl:
8582 return 0;
8583
8584 case Builtin::BIabs:
8585 return Builtin::BIlabs;
8586 case Builtin::BIlabs:
8587 return Builtin::BIllabs;
8588 case Builtin::BIllabs:
8589 return 0;
8590
8591 case Builtin::BIfabsf:
8592 return Builtin::BIfabs;
8593 case Builtin::BIfabs:
8594 return Builtin::BIfabsl;
8595 case Builtin::BIfabsl:
8596 return 0;
8597
8598 case Builtin::BIcabsf:
8599 return Builtin::BIcabs;
8600 case Builtin::BIcabs:
8601 return Builtin::BIcabsl;
8602 case Builtin::BIcabsl:
8603 return 0;
8604 }
8605}
8606
8607// Returns the argument type of the absolute value function.
8608static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8609 unsigned AbsType) {
8610 if (AbsType == 0)
8611 return QualType();
8612
8613 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8614 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8615 if (Error != ASTContext::GE_None)
8616 return QualType();
8617
8618 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8619 if (!FT)
8620 return QualType();
8621
8622 if (FT->getNumParams() != 1)
8623 return QualType();
8624
8625 return FT->getParamType(0);
8626}
8627
8628// Returns the best absolute value function, or zero, based on type and
8629// current absolute value function.
8630static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8631 unsigned AbsFunctionKind) {
8632 unsigned BestKind = 0;
8633 uint64_t ArgSize = Context.getTypeSize(ArgType);
8634 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8635 Kind = getLargerAbsoluteValueFunction(Kind)) {
8636 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8637 if (Context.getTypeSize(ParamType) >= ArgSize) {
8638 if (BestKind == 0)
8639 BestKind = Kind;
8640 else if (Context.hasSameType(ParamType, ArgType)) {
8641 BestKind = Kind;
8642 break;
8643 }
8644 }
8645 }
8646 return BestKind;
8647}
8648
8649enum AbsoluteValueKind {
8650 AVK_Integer,
8651 AVK_Floating,
8652 AVK_Complex
8653};
8654
8655static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8656 if (T->isIntegralOrEnumerationType())
8657 return AVK_Integer;
8658 if (T->isRealFloatingType())
8659 return AVK_Floating;
8660 if (T->isAnyComplexType())
8661 return AVK_Complex;
8662
8663 llvm_unreachable("Type not integer, floating, or complex");
8664}
8665
8666// Changes the absolute value function to a different type. Preserves whether
8667// the function is a builtin.
8668static unsigned changeAbsFunction(unsigned AbsKind,
8669 AbsoluteValueKind ValueKind) {
8670 switch (ValueKind) {
8671 case AVK_Integer:
8672 switch (AbsKind) {
8673 default:
8674 return 0;
8675 case Builtin::BI__builtin_fabsf:
8676 case Builtin::BI__builtin_fabs:
8677 case Builtin::BI__builtin_fabsl:
8678 case Builtin::BI__builtin_cabsf:
8679 case Builtin::BI__builtin_cabs:
8680 case Builtin::BI__builtin_cabsl:
8681 return Builtin::BI__builtin_abs;
8682 case Builtin::BIfabsf:
8683 case Builtin::BIfabs:
8684 case Builtin::BIfabsl:
8685 case Builtin::BIcabsf:
8686 case Builtin::BIcabs:
8687 case Builtin::BIcabsl:
8688 return Builtin::BIabs;
8689 }
8690 case AVK_Floating:
8691 switch (AbsKind) {
8692 default:
8693 return 0;
8694 case Builtin::BI__builtin_abs:
8695 case Builtin::BI__builtin_labs:
8696 case Builtin::BI__builtin_llabs:
8697 case Builtin::BI__builtin_cabsf:
8698 case Builtin::BI__builtin_cabs:
8699 case Builtin::BI__builtin_cabsl:
8700 return Builtin::BI__builtin_fabsf;
8701 case Builtin::BIabs:
8702 case Builtin::BIlabs:
8703 case Builtin::BIllabs:
8704 case Builtin::BIcabsf:
8705 case Builtin::BIcabs:
8706 case Builtin::BIcabsl:
8707 return Builtin::BIfabsf;
8708 }
8709 case AVK_Complex:
8710 switch (AbsKind) {
8711 default:
8712 return 0;
8713 case Builtin::BI__builtin_abs:
8714 case Builtin::BI__builtin_labs:
8715 case Builtin::BI__builtin_llabs:
8716 case Builtin::BI__builtin_fabsf:
8717 case Builtin::BI__builtin_fabs:
8718 case Builtin::BI__builtin_fabsl:
8719 return Builtin::BI__builtin_cabsf;
8720 case Builtin::BIabs:
8721 case Builtin::BIlabs:
8722 case Builtin::BIllabs:
8723 case Builtin::BIfabsf:
8724 case Builtin::BIfabs:
8725 case Builtin::BIfabsl:
8726 return Builtin::BIcabsf;
8727 }
8728 }
8729 llvm_unreachable("Unable to convert function");
8730}
8731
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00008732static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008733 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8734 if (!FnInfo)
8735 return 0;
8736
8737 switch (FDecl->getBuiltinID()) {
8738 default:
8739 return 0;
8740 case Builtin::BI__builtin_abs:
8741 case Builtin::BI__builtin_fabs:
8742 case Builtin::BI__builtin_fabsf:
8743 case Builtin::BI__builtin_fabsl:
8744 case Builtin::BI__builtin_labs:
8745 case Builtin::BI__builtin_llabs:
8746 case Builtin::BI__builtin_cabs:
8747 case Builtin::BI__builtin_cabsf:
8748 case Builtin::BI__builtin_cabsl:
8749 case Builtin::BIabs:
8750 case Builtin::BIlabs:
8751 case Builtin::BIllabs:
8752 case Builtin::BIfabs:
8753 case Builtin::BIfabsf:
8754 case Builtin::BIfabsl:
8755 case Builtin::BIcabs:
8756 case Builtin::BIcabsf:
8757 case Builtin::BIcabsl:
8758 return FDecl->getBuiltinID();
8759 }
8760 llvm_unreachable("Unknown Builtin type");
8761}
8762
8763// If the replacement is valid, emit a note with replacement function.
8764// Additionally, suggest including the proper header if not already included.
8765static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00008766 unsigned AbsKind, QualType ArgType) {
8767 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00008768 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00008769 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008770 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8771 FunctionName = "std::abs";
8772 if (ArgType->isIntegralOrEnumerationType()) {
8773 HeaderName = "cstdlib";
8774 } else if (ArgType->isRealFloatingType()) {
8775 HeaderName = "cmath";
8776 } else {
8777 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008778 }
Richard Trieubeffb832014-04-15 23:47:53 +00008779
8780 // Lookup all std::abs
8781 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00008782 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00008783 R.suppressDiagnostics();
8784 S.LookupQualifiedName(R, Std);
8785
8786 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008787 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008788 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8789 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8790 } else {
8791 FDecl = dyn_cast<FunctionDecl>(I);
8792 }
8793 if (!FDecl)
8794 continue;
8795
8796 // Found std::abs(), check that they are the right ones.
8797 if (FDecl->getNumParams() != 1)
8798 continue;
8799
8800 // Check that the parameter type can handle the argument.
8801 QualType ParamType = FDecl->getParamDecl(0)->getType();
8802 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8803 S.Context.getTypeSize(ArgType) <=
8804 S.Context.getTypeSize(ParamType)) {
8805 // Found a function, don't need the header hint.
8806 EmitHeaderHint = false;
8807 break;
8808 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008809 }
Richard Trieubeffb832014-04-15 23:47:53 +00008810 }
8811 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00008812 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00008813 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8814
8815 if (HeaderName) {
8816 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8817 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8818 R.suppressDiagnostics();
8819 S.LookupName(R, S.getCurScope());
8820
8821 if (R.isSingleResult()) {
8822 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8823 if (FD && FD->getBuiltinID() == AbsKind) {
8824 EmitHeaderHint = false;
8825 } else {
8826 return;
8827 }
8828 } else if (!R.empty()) {
8829 return;
8830 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008831 }
8832 }
8833
8834 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00008835 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008836
Richard Trieubeffb832014-04-15 23:47:53 +00008837 if (!HeaderName)
8838 return;
8839
8840 if (!EmitHeaderHint)
8841 return;
8842
Alp Toker5d96e0a2014-07-11 20:53:51 +00008843 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8844 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00008845}
8846
Richard Trieua7f30b12016-12-06 01:42:28 +00008847template <std::size_t StrLen>
8848static bool IsStdFunction(const FunctionDecl *FDecl,
8849 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00008850 if (!FDecl)
8851 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008852 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00008853 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008854 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00008855 return false;
8856
8857 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008858}
8859
8860// Warn when using the wrong abs() function.
8861void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00008862 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008863 if (Call->getNumArgs() != 1)
8864 return;
8865
8866 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00008867 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00008868 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008869 return;
8870
8871 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8872 QualType ParamType = Call->getArg(0)->getType();
8873
Alp Toker5d96e0a2014-07-11 20:53:51 +00008874 // Unsigned types cannot be negative. Suggest removing the absolute value
8875 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008876 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00008877 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00008878 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008879 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8880 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00008881 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008882 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8883 return;
8884 }
8885
David Majnemer7f77eb92015-11-15 03:04:34 +00008886 // Taking the absolute value of a pointer is very suspicious, they probably
8887 // wanted to index into an array, dereference a pointer, call a function, etc.
8888 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8889 unsigned DiagType = 0;
8890 if (ArgType->isFunctionType())
8891 DiagType = 1;
8892 else if (ArgType->isArrayType())
8893 DiagType = 2;
8894
8895 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8896 return;
8897 }
8898
Richard Trieubeffb832014-04-15 23:47:53 +00008899 // std::abs has overloads which prevent most of the absolute value problems
8900 // from occurring.
8901 if (IsStdAbs)
8902 return;
8903
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008904 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8905 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8906
8907 // The argument and parameter are the same kind. Check if they are the right
8908 // size.
8909 if (ArgValueKind == ParamValueKind) {
8910 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8911 return;
8912
8913 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8914 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8915 << FDecl << ArgType << ParamType;
8916
8917 if (NewAbsKind == 0)
8918 return;
8919
8920 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008921 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008922 return;
8923 }
8924
8925 // ArgValueKind != ParamValueKind
8926 // The wrong type of absolute value function was used. Attempt to find the
8927 // proper one.
8928 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8929 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8930 if (NewAbsKind == 0)
8931 return;
8932
8933 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8934 << FDecl << ParamValueKind << ArgValueKind;
8935
8936 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008937 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008938}
8939
Richard Trieu67c00712016-12-05 23:41:46 +00008940//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00008941void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8942 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00008943 if (!Call || !FDecl) return;
8944
8945 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008946 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008947 if (Call->getExprLoc().isMacroID()) return;
8948
8949 // Only care about the one template argument, two function parameter std::max
8950 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00008951 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008952 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8953 if (!ArgList) return;
8954 if (ArgList->size() != 1) return;
8955
8956 // Check that template type argument is unsigned integer.
8957 const auto& TA = ArgList->get(0);
8958 if (TA.getKind() != TemplateArgument::Type) return;
8959 QualType ArgType = TA.getAsType();
8960 if (!ArgType->isUnsignedIntegerType()) return;
8961
8962 // See if either argument is a literal zero.
8963 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8964 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8965 if (!MTE) return false;
8966 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8967 if (!Num) return false;
8968 if (Num->getValue() != 0) return false;
8969 return true;
8970 };
8971
8972 const Expr *FirstArg = Call->getArg(0);
8973 const Expr *SecondArg = Call->getArg(1);
8974 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8975 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8976
8977 // Only warn when exactly one argument is zero.
8978 if (IsFirstArgZero == IsSecondArgZero) return;
8979
8980 SourceRange FirstRange = FirstArg->getSourceRange();
8981 SourceRange SecondRange = SecondArg->getSourceRange();
8982
8983 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8984
8985 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8986 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8987
8988 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8989 SourceRange RemovalRange;
8990 if (IsFirstArgZero) {
8991 RemovalRange = SourceRange(FirstRange.getBegin(),
8992 SecondRange.getBegin().getLocWithOffset(-1));
8993 } else {
8994 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8995 SecondRange.getEnd());
8996 }
8997
8998 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8999 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9000 << FixItHint::CreateRemoval(RemovalRange);
9001}
9002
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009003//===--- CHECK: Standard memory functions ---------------------------------===//
9004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009005/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00009006/// such as memcmp, strncat, etc and warns if it's a comparison.
9007///
9008/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9009static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9010 IdentifierInfo *FnName,
9011 SourceLocation FnLoc,
9012 SourceLocation RParenLoc) {
9013 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9014 if (!Size)
9015 return false;
9016
Richard Smithc70f1d62017-12-14 15:16:18 +00009017 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9018 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00009019 return false;
9020
Nico Weber0e6daef2013-12-26 23:38:39 +00009021 SourceRange SizeRange = Size->getSourceRange();
9022 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9023 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00009024 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009025 << FnName
9026 << FixItHint::CreateInsertion(
9027 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00009028 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00009029 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00009030 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00009031 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9032 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00009033
9034 return true;
9035}
9036
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009037/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009038/// (e.g., whether it has a vtable).
9039static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9040 bool &IsContained) {
9041 // Look through array types while ignoring qualifiers.
9042 const Type *Ty = T->getBaseElementTypeUnsafe();
9043 IsContained = false;
9044
9045 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9046 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00009047 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009048 return nullptr;
9049
9050 if (RD->isDynamicClass())
9051 return RD;
9052
9053 // Check all the fields. If any bases were dynamic, the class is dynamic.
9054 // It's impossible for a class to transitively contain itself by value, so
9055 // infinite recursion is impossible.
9056 for (auto *FD : RD->fields()) {
9057 bool SubContained;
9058 if (const CXXRecordDecl *ContainedRD =
9059 getContainedDynamicClass(FD->getType(), SubContained)) {
9060 IsContained = true;
9061 return ContainedRD;
9062 }
9063 }
9064
9065 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00009066}
9067
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009068static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9069 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9070 if (Unary->getKind() == UETT_SizeOf)
9071 return Unary;
9072 return nullptr;
9073}
9074
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009075/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009076/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00009077static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009078 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9079 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009080 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00009081 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009082}
9083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009084/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00009085static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009086 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9087 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009088 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00009089}
9090
Akira Hatanaka2be04412018-04-17 19:13:41 +00009091namespace {
9092
9093struct SearchNonTrivialToInitializeField
9094 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9095 using Super =
9096 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9097
9098 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9099
9100 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9101 SourceLocation SL) {
9102 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9103 asDerived().visitArray(PDIK, AT, SL);
9104 return;
9105 }
9106
9107 Super::visitWithKind(PDIK, FT, SL);
9108 }
9109
9110 void visitARCStrong(QualType FT, SourceLocation SL) {
9111 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9112 }
9113 void visitARCWeak(QualType FT, SourceLocation SL) {
9114 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9115 }
9116 void visitStruct(QualType FT, SourceLocation SL) {
9117 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9118 visit(FD->getType(), FD->getLocation());
9119 }
9120 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9121 const ArrayType *AT, SourceLocation SL) {
9122 visit(getContext().getBaseElementType(AT), SL);
9123 }
9124 void visitTrivial(QualType FT, SourceLocation SL) {}
9125
9126 static void diag(QualType RT, const Expr *E, Sema &S) {
9127 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9128 }
9129
9130 ASTContext &getContext() { return S.getASTContext(); }
9131
9132 const Expr *E;
9133 Sema &S;
9134};
9135
9136struct SearchNonTrivialToCopyField
9137 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9138 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9139
9140 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9141
9142 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9143 SourceLocation SL) {
9144 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9145 asDerived().visitArray(PCK, AT, SL);
9146 return;
9147 }
9148
9149 Super::visitWithKind(PCK, FT, SL);
9150 }
9151
9152 void visitARCStrong(QualType FT, SourceLocation SL) {
9153 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9154 }
9155 void visitARCWeak(QualType FT, SourceLocation SL) {
9156 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9157 }
9158 void visitStruct(QualType FT, SourceLocation SL) {
9159 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9160 visit(FD->getType(), FD->getLocation());
9161 }
9162 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9163 SourceLocation SL) {
9164 visit(getContext().getBaseElementType(AT), SL);
9165 }
9166 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9167 SourceLocation SL) {}
9168 void visitTrivial(QualType FT, SourceLocation SL) {}
9169 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9170
9171 static void diag(QualType RT, const Expr *E, Sema &S) {
9172 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9173 }
9174
9175 ASTContext &getContext() { return S.getASTContext(); }
9176
9177 const Expr *E;
9178 Sema &S;
9179};
9180
9181}
9182
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009183/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9184static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9185 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9186
9187 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9188 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9189 return false;
9190
9191 return doesExprLikelyComputeSize(BO->getLHS()) ||
9192 doesExprLikelyComputeSize(BO->getRHS());
9193 }
9194
9195 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9196}
9197
9198/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9199///
9200/// \code
9201/// #define MACRO 0
9202/// foo(MACRO);
9203/// foo(0);
9204/// \endcode
9205///
9206/// This should return true for the first call to foo, but not for the second
9207/// (regardless of whether foo is a macro or function).
9208static bool isArgumentExpandedFromMacro(SourceManager &SM,
9209 SourceLocation CallLoc,
9210 SourceLocation ArgLoc) {
9211 if (!CallLoc.isMacroID())
9212 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9213
9214 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9215 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9216}
9217
9218/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9219/// last two arguments transposed.
9220static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9221 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9222 return;
9223
9224 const Expr *SizeArg =
9225 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9226
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009227 auto isLiteralZero = [](const Expr *E) {
9228 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9229 };
9230
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009231 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9232 SourceLocation CallLoc = Call->getRParenLoc();
9233 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009234 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009235 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9236
9237 SourceLocation DiagLoc = SizeArg->getExprLoc();
9238
9239 // Some platforms #define bzero to __builtin_memset. See if this is the
9240 // case, and if so, emit a better diagnostic.
9241 if (BId == Builtin::BIbzero ||
9242 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9243 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9244 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9245 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009246 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009247 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9248 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9249 }
9250 return;
9251 }
9252
9253 // If the second argument to a memset is a sizeof expression and the third
9254 // isn't, this is also likely an error. This should catch
9255 // 'memset(buf, sizeof(buf), 0xff)'.
9256 if (BId == Builtin::BImemset &&
9257 doesExprLikelyComputeSize(Call->getArg(1)) &&
9258 !doesExprLikelyComputeSize(Call->getArg(2))) {
9259 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9260 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9261 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9262 return;
9263 }
9264}
9265
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009266/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009267///
Chandler Carruthac687262011-06-03 06:23:57 +00009268/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009269/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9270/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009271///
9272/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009273void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00009274 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009275 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00009276 assert(BId != 0);
9277
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009278 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00009279 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009280 unsigned ExpectedNumArgs =
9281 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00009282 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009283 return;
9284
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009285 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00009286 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009287 unsigned LenArg =
9288 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00009289 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009290
Nico Weber0e6daef2013-12-26 23:38:39 +00009291 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009292 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009293 return;
9294
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009295 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9296 CheckMemaccessSize(*this, BId, Call);
9297
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009298 // We have special checking when the length is a sizeof expression.
9299 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9300 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9301 llvm::FoldingSetNodeID SizeOfArgID;
9302
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00009303 // Although widely used, 'bzero' is not a standard function. Be more strict
9304 // with the argument types before allowing diagnostics and only allow the
9305 // form bzero(ptr, sizeof(...)).
9306 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9307 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9308 return;
9309
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009310 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9311 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00009312 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009313
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009314 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00009315 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009316 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009317 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00009318
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009319 // Never warn about void type pointers. This can be used to suppress
9320 // false positives.
9321 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009322 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009323
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009324 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9325 // actually comparing the expressions for equality. Because computing the
9326 // expression IDs can be expensive, we only do this if the diagnostic is
9327 // enabled.
9328 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009329 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9330 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009331 // We only compute IDs for expressions if the warning is enabled, and
9332 // cache the sizeof arg's ID.
9333 if (SizeOfArgID == llvm::FoldingSetNodeID())
9334 SizeOfArg->Profile(SizeOfArgID, Context, true);
9335 llvm::FoldingSetNodeID DestID;
9336 Dest->Profile(DestID, Context, true);
9337 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009338 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9339 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009340 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009341 StringRef ReadableName = FnName->getName();
9342
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009343 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009344 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009345 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009346 if (!PointeeTy->isIncompleteType() &&
9347 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009348 ActionIdx = 2; // If the pointee's size is sizeof(char),
9349 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009350
9351 // If the function is defined as a builtin macro, do not show macro
9352 // expansion.
9353 SourceLocation SL = SizeOfArg->getExprLoc();
9354 SourceRange DSR = Dest->getSourceRange();
9355 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009356 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009357
9358 if (SM.isMacroArgExpansion(SL)) {
9359 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9360 SL = SM.getSpellingLoc(SL);
9361 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9362 SM.getSpellingLoc(DSR.getEnd()));
9363 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9364 SM.getSpellingLoc(SSR.getEnd()));
9365 }
9366
Anna Zaksd08d9152012-05-30 23:14:52 +00009367 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009368 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009369 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009370 << PointeeTy
9371 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009372 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009373 << SSR);
9374 DiagRuntimeBehavior(SL, SizeOfArg,
9375 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9376 << ActionIdx
9377 << SSR);
9378
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009379 break;
9380 }
9381 }
9382
9383 // Also check for cases where the sizeof argument is the exact same
9384 // type as the memory argument, and where it points to a user-defined
9385 // record type.
9386 if (SizeOfArgTy != QualType()) {
9387 if (PointeeTy->isRecordType() &&
9388 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9389 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9390 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9391 << FnName << SizeOfArgTy << ArgIdx
9392 << PointeeTy << Dest->getSourceRange()
9393 << LenExpr->getSourceRange());
9394 break;
9395 }
Nico Weberc5e73862011-06-14 16:14:58 +00009396 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009397 } else if (DestTy->isArrayType()) {
9398 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009399 }
Nico Weberc5e73862011-06-14 16:14:58 +00009400
Nico Weberc44b35e2015-03-21 17:37:46 +00009401 if (PointeeTy == QualType())
9402 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009403
Nico Weberc44b35e2015-03-21 17:37:46 +00009404 // Always complain about dynamic classes.
9405 bool IsContained;
9406 if (const CXXRecordDecl *ContainedRD =
9407 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009408
Nico Weberc44b35e2015-03-21 17:37:46 +00009409 unsigned OperationType = 0;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009410 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
Nico Weberc44b35e2015-03-21 17:37:46 +00009411 // "overwritten" if we're warning about the destination for any call
9412 // but memcmp; otherwise a verb appropriate to the call.
Clement Courbet8c3343d2019-02-14 12:00:34 +00009413 if (ArgIdx != 0 || IsCmp) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009414 if (BId == Builtin::BImemcpy)
9415 OperationType = 1;
9416 else if(BId == Builtin::BImemmove)
9417 OperationType = 2;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009418 else if (IsCmp)
Nico Weberc44b35e2015-03-21 17:37:46 +00009419 OperationType = 3;
9420 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009421
Clement Courbet8c3343d2019-02-14 12:00:34 +00009422 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9423 PDiag(diag::warn_dyn_class_memaccess)
9424 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9425 << IsContained << ContainedRD << OperationType
9426 << Call->getCallee()->getSourceRange());
Nico Weberc44b35e2015-03-21 17:37:46 +00009427 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9428 BId != Builtin::BImemset)
9429 DiagRuntimeBehavior(
9430 Dest->getExprLoc(), Dest,
9431 PDiag(diag::warn_arc_object_memaccess)
9432 << ArgIdx << FnName << PointeeTy
9433 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009434 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9435 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9436 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9437 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9438 PDiag(diag::warn_cstruct_memaccess)
9439 << ArgIdx << FnName << PointeeTy << 0);
9440 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9441 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9442 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9443 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9444 PDiag(diag::warn_cstruct_memaccess)
9445 << ArgIdx << FnName << PointeeTy << 1);
9446 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9447 } else {
9448 continue;
9449 }
9450 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009451 continue;
9452
9453 DiagRuntimeBehavior(
9454 Dest->getExprLoc(), Dest,
9455 PDiag(diag::note_bad_memaccess_silence)
9456 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9457 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009458 }
9459}
9460
Ted Kremenek6865f772011-08-18 20:55:45 +00009461// A little helper routine: ignore addition and subtraction of integer literals.
9462// This intentionally does not ignore all integer constant expressions because
9463// we don't want to remove sizeof().
9464static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9465 Ex = Ex->IgnoreParenCasts();
9466
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009467 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009468 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9469 if (!BO || !BO->isAdditiveOp())
9470 break;
9471
9472 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9473 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009474
Ted Kremenek6865f772011-08-18 20:55:45 +00009475 if (isa<IntegerLiteral>(RHS))
9476 Ex = LHS;
9477 else if (isa<IntegerLiteral>(LHS))
9478 Ex = RHS;
9479 else
9480 break;
9481 }
9482
9483 return Ex;
9484}
9485
Anna Zaks13b08572012-08-08 21:42:23 +00009486static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9487 ASTContext &Context) {
9488 // Only handle constant-sized or VLAs, but not flexible members.
9489 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9490 // Only issue the FIXIT for arrays of size > 1.
9491 if (CAT->getSize().getSExtValue() <= 1)
9492 return false;
9493 } else if (!Ty->isVariableArrayType()) {
9494 return false;
9495 }
9496 return true;
9497}
9498
Ted Kremenek6865f772011-08-18 20:55:45 +00009499// Warn if the user has made the 'size' argument to strlcpy or strlcat
9500// be the size of the source, instead of the destination.
9501void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9502 IdentifierInfo *FnName) {
9503
9504 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009505 unsigned NumArgs = Call->getNumArgs();
9506 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009507 return;
9508
9509 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9510 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009511 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009512
9513 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009514 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009515 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009516
Ted Kremenek6865f772011-08-18 20:55:45 +00009517 // Look for 'strlcpy(dst, x, sizeof(x))'
9518 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9519 CompareWithSrc = Ex;
9520 else {
9521 // Look for 'strlcpy(dst, x, strlen(x))'
9522 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009523 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9524 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009525 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9526 }
9527 }
9528
9529 if (!CompareWithSrc)
9530 return;
9531
9532 // Determine if the argument to sizeof/strlen is equal to the source
9533 // argument. In principle there's all kinds of things you could do
9534 // here, for instance creating an == expression and evaluating it with
9535 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9536 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9537 if (!SrcArgDRE)
9538 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009539
Ted Kremenek6865f772011-08-18 20:55:45 +00009540 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009541 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009542 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9543 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009544
Ted Kremenek6865f772011-08-18 20:55:45 +00009545 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009546 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9547 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009548
Ted Kremenek6865f772011-08-18 20:55:45 +00009549 // Output a FIXIT hint if the destination is an array (rather than a
9550 // pointer to an array). This could be enhanced to handle some
9551 // pointers if we know the actual size, like if DstArg is 'array+2'
9552 // we could say 'sizeof(array)-2'.
9553 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009554 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009555 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009556
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009557 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009558 llvm::raw_svector_ostream OS(sizeString);
9559 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009560 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009561 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009562
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009563 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9564 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9565 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009566}
9567
Anna Zaks314cd092012-02-01 19:08:57 +00009568/// Check if two expressions refer to the same declaration.
9569static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9570 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9571 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9572 return D1->getDecl() == D2->getDecl();
9573 return false;
9574}
9575
9576static const Expr *getStrlenExprArg(const Expr *E) {
9577 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9578 const FunctionDecl *FD = CE->getDirectCallee();
9579 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009580 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009581 return CE->getArg(0)->IgnoreParenCasts();
9582 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009583 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009584}
9585
9586// Warn on anti-patterns as the 'size' argument to strncat.
9587// The correct size argument should look like following:
9588// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9589void Sema::CheckStrncatArguments(const CallExpr *CE,
9590 IdentifierInfo *FnName) {
9591 // Don't crash if the user has the wrong number of arguments.
9592 if (CE->getNumArgs() < 3)
9593 return;
9594 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9595 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9596 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9597
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009598 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009599 CE->getRParenLoc()))
9600 return;
9601
Anna Zaks314cd092012-02-01 19:08:57 +00009602 // Identify common expressions, which are wrongly used as the size argument
9603 // to strncat and may lead to buffer overflows.
9604 unsigned PatternType = 0;
9605 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9606 // - sizeof(dst)
9607 if (referToTheSameDecl(SizeOfArg, DstArg))
9608 PatternType = 1;
9609 // - sizeof(src)
9610 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9611 PatternType = 2;
9612 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9613 if (BE->getOpcode() == BO_Sub) {
9614 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9615 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9616 // - sizeof(dst) - strlen(dst)
9617 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9618 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9619 PatternType = 1;
9620 // - sizeof(src) - (anything)
9621 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9622 PatternType = 2;
9623 }
9624 }
9625
9626 if (PatternType == 0)
9627 return;
9628
Anna Zaks5069aa32012-02-03 01:27:37 +00009629 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009630 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009631 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009632 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009633
9634 // If the function is defined as a builtin macro, do not show macro expansion.
9635 if (SM.isMacroArgExpansion(SL)) {
9636 SL = SM.getSpellingLoc(SL);
9637 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9638 SM.getSpellingLoc(SR.getEnd()));
9639 }
9640
Anna Zaks13b08572012-08-08 21:42:23 +00009641 // Check if the destination is an array (rather than a pointer to an array).
9642 QualType DstTy = DstArg->getType();
9643 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9644 Context);
9645 if (!isKnownSizeArray) {
9646 if (PatternType == 1)
9647 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9648 else
9649 Diag(SL, diag::warn_strncat_src_size) << SR;
9650 return;
9651 }
9652
Anna Zaks314cd092012-02-01 19:08:57 +00009653 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009654 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009655 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009656 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009657
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009658 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009659 llvm::raw_svector_ostream OS(sizeString);
9660 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009661 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009662 OS << ") - ";
9663 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009664 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009665 OS << ") - 1";
9666
Anna Zaks5069aa32012-02-03 01:27:37 +00009667 Diag(SL, diag::note_strncat_wrong_size)
9668 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009669}
9670
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009671void
9672Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9673 SourceLocation ReturnLoc,
9674 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009675 const AttrVec *Attrs,
9676 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009677 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009678 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9679 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009680 CheckNonNullExpr(*this, RetValExp))
9681 Diag(ReturnLoc, diag::warn_null_ret)
9682 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009683
9684 // C++11 [basic.stc.dynamic.allocation]p4:
9685 // If an allocation function declared with a non-throwing
9686 // exception-specification fails to allocate storage, it shall return
9687 // a null pointer. Any other allocation function that fails to allocate
9688 // storage shall indicate failure only by throwing an exception [...]
9689 if (FD) {
9690 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9691 if (Op == OO_New || Op == OO_Array_New) {
9692 const FunctionProtoType *Proto
9693 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00009694 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00009695 CheckNonNullExpr(*this, RetValExp))
9696 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9697 << FD << getLangOpts().CPlusPlus11;
9698 }
9699 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009700}
9701
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009702//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9703
9704/// Check for comparisons of floating point operands using != and ==.
9705/// Issue a warning if these are no self-comparisons, as they are not likely
9706/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00009707void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00009708 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9709 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009710
9711 // Special case: check for x == x (which is OK).
9712 // Do not emit warnings for such cases.
9713 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9714 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9715 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00009716 return;
Mike Stump11289f42009-09-09 15:08:12 +00009717
Ted Kremenekeda40e22007-11-29 00:59:04 +00009718 // Special case: check for comparisons against literals that can be exactly
9719 // represented by APFloat. In such cases, do not emit a warning. This
9720 // is a heuristic: often comparison against such literals are used to
9721 // detect if a value in a variable has not changed. This clearly can
9722 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00009723 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9724 if (FLL->isExact())
9725 return;
9726 } else
9727 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9728 if (FLR->isExact())
9729 return;
Mike Stump11289f42009-09-09 15:08:12 +00009730
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009731 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00009732 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009733 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009734 return;
Mike Stump11289f42009-09-09 15:08:12 +00009735
David Blaikie1f4ff152012-07-16 20:47:22 +00009736 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009737 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009738 return;
Mike Stump11289f42009-09-09 15:08:12 +00009739
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009740 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00009741 Diag(Loc, diag::warn_floatingpoint_eq)
9742 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009743}
John McCallca01b222010-01-04 23:21:16 +00009744
John McCall70aa5392010-01-06 05:24:50 +00009745//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9746//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00009747
John McCall70aa5392010-01-06 05:24:50 +00009748namespace {
John McCallca01b222010-01-04 23:21:16 +00009749
John McCall70aa5392010-01-06 05:24:50 +00009750/// Structure recording the 'active' range of an integer-valued
9751/// expression.
9752struct IntRange {
9753 /// The number of bits active in the int.
9754 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00009755
John McCall70aa5392010-01-06 05:24:50 +00009756 /// True if the int is known not to have negative values.
9757 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00009758
John McCall70aa5392010-01-06 05:24:50 +00009759 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009760 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00009761
John McCall817d4af2010-11-10 23:38:19 +00009762 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00009763 static IntRange forBoolType() {
9764 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00009765 }
9766
John McCall817d4af2010-11-10 23:38:19 +00009767 /// Returns the range of an opaque value of the given integral type.
9768 static IntRange forValueOfType(ASTContext &C, QualType T) {
9769 return forValueOfCanonicalType(C,
9770 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00009771 }
9772
John McCall817d4af2010-11-10 23:38:19 +00009773 /// Returns the range of an opaque value of a canonical integral type.
9774 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00009775 assert(T->isCanonicalUnqualified());
9776
9777 if (const VectorType *VT = dyn_cast<VectorType>(T))
9778 T = VT->getElementType().getTypePtr();
9779 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9780 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009781 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9782 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00009783
Roman Lebedevca1aaac2017-10-21 16:44:03 +00009784 if (!C.getLangOpts().CPlusPlus) {
9785 // For enum types in C code, use the underlying datatype.
9786 if (const EnumType *ET = dyn_cast<EnumType>(T))
9787 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9788 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9789 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00009790 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00009791 // In C++11, enums can have a fixed underlying type. Use this type to
9792 // compute the range.
9793 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00009794 return IntRange(C.getIntWidth(QualType(T, 0)),
9795 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00009796 }
John McCall18a2c2c2010-11-09 22:22:12 +00009797
David Majnemer6a426652013-06-07 22:07:20 +00009798 unsigned NumPositive = Enum->getNumPositiveBits();
9799 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00009800
David Majnemer6a426652013-06-07 22:07:20 +00009801 if (NumNegative == 0)
9802 return IntRange(NumPositive, true/*NonNegative*/);
9803 else
9804 return IntRange(std::max(NumPositive + 1, NumNegative),
9805 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00009806 }
John McCall70aa5392010-01-06 05:24:50 +00009807
9808 const BuiltinType *BT = cast<BuiltinType>(T);
9809 assert(BT->isInteger());
9810
9811 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9812 }
9813
John McCall817d4af2010-11-10 23:38:19 +00009814 /// Returns the "target" range of a canonical integral type, i.e.
9815 /// the range of values expressible in the type.
9816 ///
9817 /// This matches forValueOfCanonicalType except that enums have the
9818 /// full range of their type, not the range of their enumerators.
9819 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9820 assert(T->isCanonicalUnqualified());
9821
9822 if (const VectorType *VT = dyn_cast<VectorType>(T))
9823 T = VT->getElementType().getTypePtr();
9824 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9825 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009826 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9827 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009828 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00009829 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009830
9831 const BuiltinType *BT = cast<BuiltinType>(T);
9832 assert(BT->isInteger());
9833
9834 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9835 }
9836
9837 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00009838 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00009839 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00009840 L.NonNegative && R.NonNegative);
9841 }
9842
John McCall817d4af2010-11-10 23:38:19 +00009843 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00009844 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00009845 return IntRange(std::min(L.Width, R.Width),
9846 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00009847 }
9848};
9849
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009850} // namespace
9851
9852static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9853 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009854 if (value.isSigned() && value.isNegative())
9855 return IntRange(value.getMinSignedBits(), false);
9856
9857 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00009858 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009859
9860 // isNonNegative() just checks the sign bit without considering
9861 // signedness.
9862 return IntRange(value.getActiveBits(), true);
9863}
9864
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009865static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9866 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009867 if (result.isInt())
9868 return GetValueRange(C, result.getInt(), MaxWidth);
9869
9870 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00009871 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9872 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9873 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9874 R = IntRange::join(R, El);
9875 }
John McCall70aa5392010-01-06 05:24:50 +00009876 return R;
9877 }
9878
9879 if (result.isComplexInt()) {
9880 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9881 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9882 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00009883 }
9884
9885 // This can happen with lossless casts to intptr_t of "based" lvalues.
9886 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00009887 // FIXME: The only reason we need to pass the type in here is to get
9888 // the sign right on this one case. It would be nice if APValue
9889 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009890 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00009891 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00009892}
John McCall70aa5392010-01-06 05:24:50 +00009893
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009894static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009895 QualType Ty = E->getType();
9896 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9897 Ty = AtomicRHS->getValueType();
9898 return Ty;
9899}
9900
John McCall70aa5392010-01-06 05:24:50 +00009901/// Pseudo-evaluate the given integer expression, estimating the
9902/// range of values it might take.
9903///
9904/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009905static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009906 E = E->IgnoreParens();
9907
9908 // Try a full evaluation first.
9909 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009910 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00009911 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009912
9913 // I think we only want to look through implicit casts here; if the
9914 // user has an explicit widening cast, we should treat the value as
9915 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009916 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009917 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00009918 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9919
Eli Friedmane6d33952013-07-08 20:20:06 +00009920 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009921
George Burgess IVdf1ed002016-01-13 01:52:39 +00009922 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9923 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009924
John McCall70aa5392010-01-06 05:24:50 +00009925 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00009926 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00009927 return OutputTypeRange;
9928
9929 IntRange SubRange
9930 = GetExprRange(C, CE->getSubExpr(),
9931 std::min(MaxWidth, OutputTypeRange.Width));
9932
9933 // Bail out if the subexpr's range is as wide as the cast type.
9934 if (SubRange.Width >= OutputTypeRange.Width)
9935 return OutputTypeRange;
9936
9937 // Otherwise, we take the smaller width, and we're non-negative if
9938 // either the output type or the subexpr is.
9939 return IntRange(SubRange.Width,
9940 SubRange.NonNegative || OutputTypeRange.NonNegative);
9941 }
9942
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009943 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009944 // If we can fold the condition, just take that operand.
9945 bool CondResult;
9946 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9947 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9948 : CO->getFalseExpr(),
9949 MaxWidth);
9950
9951 // Otherwise, conservatively merge.
9952 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9953 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9954 return IntRange::join(L, R);
9955 }
9956
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009957 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009958 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009959 case BO_Cmp:
9960 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009961
9962 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009963 case BO_LAnd:
9964 case BO_LOr:
9965 case BO_LT:
9966 case BO_GT:
9967 case BO_LE:
9968 case BO_GE:
9969 case BO_EQ:
9970 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009971 return IntRange::forBoolType();
9972
John McCallc3688382011-07-13 06:35:24 +00009973 // The type of the assignments is the type of the LHS, so the RHS
9974 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009975 case BO_MulAssign:
9976 case BO_DivAssign:
9977 case BO_RemAssign:
9978 case BO_AddAssign:
9979 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009980 case BO_XorAssign:
9981 case BO_OrAssign:
9982 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009983 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009984
John McCallc3688382011-07-13 06:35:24 +00009985 // Simple assignments just pass through the RHS, which will have
9986 // been coerced to the LHS type.
9987 case BO_Assign:
9988 // TODO: bitfields?
9989 return GetExprRange(C, BO->getRHS(), MaxWidth);
9990
John McCall70aa5392010-01-06 05:24:50 +00009991 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009992 case BO_PtrMemD:
9993 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009994 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009995
John McCall2ce81ad2010-01-06 22:07:33 +00009996 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009997 case BO_And:
9998 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009999 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
10000 GetExprRange(C, BO->getRHS(), MaxWidth));
10001
John McCall70aa5392010-01-06 05:24:50 +000010002 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +000010003 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +000010004 // ...except that we want to treat '1 << (blah)' as logically
10005 // positive. It's an important idiom.
10006 if (IntegerLiteral *I
10007 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10008 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +000010009 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +000010010 return IntRange(R.Width, /*NonNegative*/ true);
10011 }
10012 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010013 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +000010014
John McCalle3027922010-08-25 11:45:40 +000010015 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +000010016 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010017
John McCall2ce81ad2010-01-06 22:07:33 +000010018 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +000010019 case BO_Shr:
10020 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +000010021 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
10022
10023 // If the shift amount is a positive constant, drop the width by
10024 // that much.
10025 llvm::APSInt shift;
10026 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10027 shift.isNonNegative()) {
10028 unsigned zext = shift.getZExtValue();
10029 if (zext >= L.Width)
10030 L.Width = (L.NonNegative ? 0 : 1);
10031 else
10032 L.Width -= zext;
10033 }
10034
10035 return L;
10036 }
10037
10038 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +000010039 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +000010040 return GetExprRange(C, BO->getRHS(), MaxWidth);
10041
John McCall2ce81ad2010-01-06 22:07:33 +000010042 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +000010043 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +000010044 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +000010045 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +000010046 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +000010047
John McCall51431812011-07-14 22:39:48 +000010048 // The width of a division result is mostly determined by the size
10049 // of the LHS.
10050 case BO_Div: {
10051 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010052 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +000010053 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
10054
10055 // If the divisor is constant, use that.
10056 llvm::APSInt divisor;
10057 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10058 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10059 if (log2 >= L.Width)
10060 L.Width = (L.NonNegative ? 0 : 1);
10061 else
10062 L.Width = std::min(L.Width - log2, MaxWidth);
10063 return L;
10064 }
10065
10066 // Otherwise, just use the LHS's width.
10067 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
10068 return IntRange(L.Width, L.NonNegative && R.NonNegative);
10069 }
10070
10071 // The result of a remainder can't be larger than the result of
10072 // either side.
10073 case BO_Rem: {
10074 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010075 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +000010076 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
10077 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
10078
10079 IntRange meet = IntRange::meet(L, R);
10080 meet.Width = std::min(meet.Width, MaxWidth);
10081 return meet;
10082 }
10083
10084 // The default behavior is okay for these.
10085 case BO_Mul:
10086 case BO_Add:
10087 case BO_Xor:
10088 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +000010089 break;
10090 }
10091
John McCall51431812011-07-14 22:39:48 +000010092 // The default case is to treat the operation as if it were closed
10093 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +000010094 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
10095 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
10096 return IntRange::join(L, R);
10097 }
10098
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010099 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010100 switch (UO->getOpcode()) {
10101 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +000010102 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +000010103 return IntRange::forBoolType();
10104
10105 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +000010106 case UO_Deref:
10107 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +000010108 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010109
10110 default:
10111 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
10112 }
10113 }
10114
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010115 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +000010116 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
10117
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010118 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +000010119 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +000010120 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +000010121
Eli Friedmane6d33952013-07-08 20:20:06 +000010122 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010123}
John McCall263a48b2010-01-04 23:31:57 +000010124
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010125static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +000010126 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +000010127}
10128
John McCall263a48b2010-01-04 23:31:57 +000010129/// Checks whether the given value, which currently has the given
10130/// source semantics, has the same value when coerced through the
10131/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010132static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10133 const llvm::fltSemantics &Src,
10134 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010135 llvm::APFloat truncated = value;
10136
10137 bool ignored;
10138 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10139 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10140
10141 return truncated.bitwiseIsEqual(value);
10142}
10143
10144/// Checks whether the given value, which currently has the given
10145/// source semantics, has the same value when coerced through the
10146/// target semantics.
10147///
10148/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010149static bool IsSameFloatAfterCast(const APValue &value,
10150 const llvm::fltSemantics &Src,
10151 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010152 if (value.isFloat())
10153 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10154
10155 if (value.isVector()) {
10156 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10157 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10158 return false;
10159 return true;
10160 }
10161
10162 assert(value.isComplexFloat());
10163 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10164 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10165}
10166
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010167static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010168
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010169static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +000010170 // Suppress cases where we are comparing against an enum constant.
10171 if (const DeclRefExpr *DR =
10172 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10173 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +000010174 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +000010175
10176 // Suppress cases where the '0' value is expanded from a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010177 if (E->getBeginLoc().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +000010178 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +000010179
Roman Lebedev6de129e2017-10-15 20:13:17 +000010180 return false;
10181}
10182
Richard Smith692f66ab2017-12-06 19:23:19 +000010183static bool isKnownToHaveUnsignedValue(Expr *E) {
10184 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +000010185 (!E->getType()->isSignedIntegerType() ||
10186 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10187}
10188
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010189namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +000010190/// The promoted range of values of a type. In general this has the
10191/// following structure:
10192///
10193/// |-----------| . . . |-----------|
10194/// ^ ^ ^ ^
10195/// Min HoleMin HoleMax Max
10196///
10197/// ... where there is only a hole if a signed type is promoted to unsigned
10198/// (in which case Min and Max are the smallest and largest representable
10199/// values).
10200struct PromotedRange {
10201 // Min, or HoleMax if there is a hole.
10202 llvm::APSInt PromotedMin;
10203 // Max, or HoleMin if there is a hole.
10204 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010205
Richard Smitha5370fb2017-12-08 22:57:11 +000010206 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10207 if (R.Width == 0)
10208 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10209 else if (R.Width >= BitWidth && !Unsigned) {
10210 // Promotion made the type *narrower*. This happens when promoting
10211 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10212 // Treat all values of 'signed int' as being in range for now.
10213 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10214 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10215 } else {
10216 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10217 .extOrTrunc(BitWidth);
10218 PromotedMin.setIsUnsigned(Unsigned);
10219
10220 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10221 .extOrTrunc(BitWidth);
10222 PromotedMax.setIsUnsigned(Unsigned);
10223 }
10224 }
10225
10226 // Determine whether this range is contiguous (has no hole).
10227 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10228
10229 // Where a constant value is within the range.
10230 enum ComparisonResult {
10231 LT = 0x1,
10232 LE = 0x2,
10233 GT = 0x4,
10234 GE = 0x8,
10235 EQ = 0x10,
10236 NE = 0x20,
10237 InRangeFlag = 0x40,
10238
10239 Less = LE | LT | NE,
10240 Min = LE | InRangeFlag,
10241 InRange = InRangeFlag,
10242 Max = GE | InRangeFlag,
10243 Greater = GE | GT | NE,
10244
10245 OnlyValue = LE | GE | EQ | InRangeFlag,
10246 InHole = NE
10247 };
10248
10249 ComparisonResult compare(const llvm::APSInt &Value) const {
10250 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10251 Value.isUnsigned() == PromotedMin.isUnsigned());
10252 if (!isContiguous()) {
10253 assert(Value.isUnsigned() && "discontiguous range for signed compare");
10254 if (Value.isMinValue()) return Min;
10255 if (Value.isMaxValue()) return Max;
10256 if (Value >= PromotedMin) return InRange;
10257 if (Value <= PromotedMax) return InRange;
10258 return InHole;
10259 }
10260
10261 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10262 case -1: return Less;
10263 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10264 case 1:
10265 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10266 case -1: return InRange;
10267 case 0: return Max;
10268 case 1: return Greater;
10269 }
10270 }
10271
10272 llvm_unreachable("impossible compare result");
10273 }
10274
Richard Smithc70f1d62017-12-14 15:16:18 +000010275 static llvm::Optional<StringRef>
10276 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10277 if (Op == BO_Cmp) {
10278 ComparisonResult LTFlag = LT, GTFlag = GT;
10279 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10280
10281 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10282 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10283 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10284 return llvm::None;
10285 }
10286
Richard Smitha5370fb2017-12-08 22:57:11 +000010287 ComparisonResult TrueFlag, FalseFlag;
10288 if (Op == BO_EQ) {
10289 TrueFlag = EQ;
10290 FalseFlag = NE;
10291 } else if (Op == BO_NE) {
10292 TrueFlag = NE;
10293 FalseFlag = EQ;
10294 } else {
10295 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10296 TrueFlag = LT;
10297 FalseFlag = GE;
10298 } else {
10299 TrueFlag = GT;
10300 FalseFlag = LE;
10301 }
10302 if (Op == BO_GE || Op == BO_LE)
10303 std::swap(TrueFlag, FalseFlag);
10304 }
10305 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010306 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +000010307 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010308 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +000010309 return llvm::None;
10310 }
Roman Lebedev6de129e2017-10-15 20:13:17 +000010311};
John McCallcc7e5bf2010-05-06 08:58:33 +000010312}
10313
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010314static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +000010315 // Strip off implicit integral promotions.
10316 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010317 if (ICE->getCastKind() != CK_IntegralCast &&
10318 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +000010319 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010320 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +000010321 }
10322
10323 return E->getType()->isEnumeralType();
10324}
10325
Richard Smith692f66ab2017-12-06 19:23:19 +000010326static int classifyConstantValue(Expr *Constant) {
10327 // The values of this enumeration are used in the diagnostics
10328 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10329 enum ConstantValueKind {
10330 Miscellaneous = 0,
10331 LiteralTrue,
10332 LiteralFalse
10333 };
10334 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10335 return BL->getValue() ? ConstantValueKind::LiteralTrue
10336 : ConstantValueKind::LiteralFalse;
10337 return ConstantValueKind::Miscellaneous;
10338}
10339
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010340static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10341 Expr *Constant, Expr *Other,
10342 const llvm::APSInt &Value,
10343 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010344 if (S.inTemplateInstantiation())
10345 return false;
10346
Richard Smitha5370fb2017-12-08 22:57:11 +000010347 Expr *OriginalOther = Other;
10348
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010349 Constant = Constant->IgnoreParenImpCasts();
10350 Other = Other->IgnoreParenImpCasts();
10351
Richard Smitha5370fb2017-12-08 22:57:11 +000010352 // Suppress warnings on tautological comparisons between values of the same
10353 // enumeration type. There are only two ways we could warn on this:
10354 // - If the constant is outside the range of representable values of
10355 // the enumeration. In such a case, we should warn about the cast
10356 // to enumeration type, not about the comparison.
10357 // - If the constant is the maximum / minimum in-range value. For an
10358 // enumeratin type, such comparisons can be meaningful and useful.
10359 if (Constant->getType()->isEnumeralType() &&
10360 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10361 return false;
10362
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010363 // TODO: Investigate using GetExprRange() to get tighter bounds
10364 // on the bit ranges.
10365 QualType OtherT = Other->getType();
10366 if (const auto *AT = OtherT->getAs<AtomicType>())
10367 OtherT = AT->getValueType();
10368 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10369
10370 // Whether we're treating Other as being a bool because of the form of
10371 // expression despite it having another type (typically 'int' in C).
10372 bool OtherIsBooleanDespiteType =
10373 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10374 if (OtherIsBooleanDespiteType)
10375 OtherRange = IntRange::forBoolType();
10376
Richard Smitha5370fb2017-12-08 22:57:11 +000010377 // Determine the promoted range of the other type and see if a comparison of
10378 // the constant against that range is tautological.
10379 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10380 Value.isUnsigned());
10381 auto Cmp = OtherPromotedRange.compare(Value);
10382 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10383 if (!Result)
10384 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010385
Richard Smitha5370fb2017-12-08 22:57:11 +000010386 // Suppress the diagnostic for an in-range comparison if the constant comes
10387 // from a macro or enumerator. We don't want to diagnose
10388 //
10389 // some_long_value <= INT_MAX
10390 //
10391 // when sizeof(int) == sizeof(long).
10392 bool InRange = Cmp & PromotedRange::InRangeFlag;
10393 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10394 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010395
10396 // If this is a comparison to an enum constant, include that
10397 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010398 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010399 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10400 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10401
Richard Smitha5370fb2017-12-08 22:57:11 +000010402 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010403 SmallString<64> PrettySourceValue;
10404 llvm::raw_svector_ostream OS(PrettySourceValue);
10405 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +000010406 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010407 else
10408 OS << Value;
10409
Richard Smitha5370fb2017-12-08 22:57:11 +000010410 // FIXME: We use a somewhat different formatting for the in-range cases and
10411 // cases involving boolean values for historical reasons. We should pick a
10412 // consistent way of presenting these diagnostics.
10413 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10414 S.DiagRuntimeBehavior(
10415 E->getOperatorLoc(), E,
10416 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10417 : diag::warn_tautological_bool_compare)
10418 << OS.str() << classifyConstantValue(Constant)
10419 << OtherT << OtherIsBooleanDespiteType << *Result
10420 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10421 } else {
10422 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10423 ? (HasEnumType(OriginalOther)
10424 ? diag::warn_unsigned_enum_always_true_comparison
10425 : diag::warn_unsigned_always_true_comparison)
10426 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010427
Richard Smitha5370fb2017-12-08 22:57:11 +000010428 S.Diag(E->getOperatorLoc(), Diag)
10429 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10431 }
10432
10433 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010434}
10435
John McCallcc7e5bf2010-05-06 08:58:33 +000010436/// Analyze the operands of the given comparison. Implements the
10437/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010438static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010439 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10440 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010441}
John McCall263a48b2010-01-04 23:31:57 +000010442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010443/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010444///
Richard Trieu82402a02011-09-15 21:56:47 +000010445/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010446static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010447 // The type the comparison is being performed in.
10448 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010449
10450 // Only analyze comparison operators where both sides have been converted to
10451 // the same type.
10452 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10453 return AnalyzeImpConvsInComparison(S, E);
10454
10455 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010456 if (E->isValueDependent())
10457 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010458
Roman Lebedev6de129e2017-10-15 20:13:17 +000010459 Expr *LHS = E->getLHS();
10460 Expr *RHS = E->getRHS();
10461
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010462 if (T->isIntegralType(S.Context)) {
10463 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010464 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010465
Roman Lebedev6de129e2017-10-15 20:13:17 +000010466 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10467 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010468
Roman Lebedev6de129e2017-10-15 20:13:17 +000010469 // We don't care about expressions whose result is a constant.
10470 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10471 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010472
Roman Lebedev6de129e2017-10-15 20:13:17 +000010473 // We only care about expressions where just one side is literal
10474 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10475 // Is the constant on the RHS or LHS?
10476 const bool RhsConstant = IsRHSIntegralLiteral;
10477 Expr *Const = RhsConstant ? RHS : LHS;
10478 Expr *Other = RhsConstant ? LHS : RHS;
10479 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10480
10481 // Check whether an integer constant comparison results in a value
10482 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010483 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10484 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010485 }
10486 }
10487
10488 if (!T->hasUnsignedIntegerRepresentation()) {
10489 // We don't do anything special if this isn't an unsigned integral
10490 // comparison: we're only interested in integral comparisons, and
10491 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010492 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010493 }
10494
10495 LHS = LHS->IgnoreParenImpCasts();
10496 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010497
Alex Lorenzb57409f2018-02-07 20:45:39 +000010498 if (!S.getLangOpts().CPlusPlus) {
10499 // Avoid warning about comparison of integers with different signs when
10500 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10501 // the type of `E`.
10502 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10503 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10504 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10505 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10506 }
10507
John McCallcc7e5bf2010-05-06 08:58:33 +000010508 // Check to see if one of the (unmodified) operands is of different
10509 // signedness.
10510 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010511 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10512 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010513 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010514 signedOperand = LHS;
10515 unsignedOperand = RHS;
10516 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10517 signedOperand = RHS;
10518 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010519 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010520 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010521 }
10522
John McCallcc7e5bf2010-05-06 08:58:33 +000010523 // Otherwise, calculate the effective range of the signed operand.
10524 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +000010525
John McCallcc7e5bf2010-05-06 08:58:33 +000010526 // Go ahead and analyze implicit conversions in the operands. Note
10527 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010528 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10529 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010530
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010531 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010532 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010533 return;
John McCallca01b222010-01-04 23:21:16 +000010534
10535 // For (in)equality comparisons, if the unsigned operand is a
10536 // constant which cannot collide with a overflowed signed operand,
10537 // then reinterpreting the signed operand as unsigned will not
10538 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010539 if (E->isEqualityOp()) {
10540 unsigned comparisonWidth = S.Context.getIntWidth(T);
10541 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +000010542
John McCallcc7e5bf2010-05-06 08:58:33 +000010543 // We should never be unable to prove that the unsigned operand is
10544 // non-negative.
10545 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10546
10547 if (unsignedRange.Width < comparisonWidth)
10548 return;
10549 }
10550
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010551 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10552 S.PDiag(diag::warn_mixed_sign_comparison)
10553 << LHS->getType() << RHS->getType()
10554 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010555}
10556
John McCall1f425642010-11-11 03:21:53 +000010557/// Analyzes an attempt to assign the given value to a bitfield.
10558///
10559/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010560static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10561 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010562 assert(Bitfield->isBitField());
10563 if (Bitfield->isInvalidDecl())
10564 return false;
10565
John McCalldeebbcf2010-11-11 05:33:51 +000010566 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010567 QualType BitfieldType = Bitfield->getType();
10568 if (BitfieldType->isBooleanType())
10569 return false;
10570
10571 if (BitfieldType->isEnumeralType()) {
10572 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10573 // If the underlying enum type was not explicitly specified as an unsigned
10574 // type and the enum contain only positive values, MSVC++ will cause an
10575 // inconsistency by storing this as a signed type.
10576 if (S.getLangOpts().CPlusPlus11 &&
10577 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10578 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10579 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10580 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10581 << BitfieldEnumDecl->getNameAsString();
10582 }
10583 }
10584
John McCalldeebbcf2010-11-11 05:33:51 +000010585 if (Bitfield->getType()->isBooleanType())
10586 return false;
10587
Douglas Gregor789adec2011-02-04 13:09:01 +000010588 // Ignore value- or type-dependent expressions.
10589 if (Bitfield->getBitWidth()->isValueDependent() ||
10590 Bitfield->getBitWidth()->isTypeDependent() ||
10591 Init->isValueDependent() ||
10592 Init->isTypeDependent())
10593 return false;
10594
John McCall1f425642010-11-11 03:21:53 +000010595 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010596 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010597
Fangrui Song407659a2018-11-30 23:41:18 +000010598 Expr::EvalResult Result;
10599 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Reid Kleckner329f24d2017-03-14 18:01:02 +000010600 Expr::SE_AllowSideEffects)) {
10601 // The RHS is not constant. If the RHS has an enum type, make sure the
10602 // bitfield is wide enough to hold all the values of the enum without
10603 // truncation.
10604 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10605 EnumDecl *ED = EnumTy->getDecl();
10606 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10607
10608 // Enum types are implicitly signed on Windows, so check if there are any
10609 // negative enumerators to see if the enum was intended to be signed or
10610 // not.
10611 bool SignedEnum = ED->getNumNegativeBits() > 0;
10612
10613 // Check for surprising sign changes when assigning enum values to a
10614 // bitfield of different signedness. If the bitfield is signed and we
10615 // have exactly the right number of bits to store this unsigned enum,
10616 // suggest changing the enum to an unsigned type. This typically happens
10617 // on Windows where unfixed enums always use an underlying type of 'int'.
10618 unsigned DiagID = 0;
10619 if (SignedEnum && !SignedBitfield) {
10620 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10621 } else if (SignedBitfield && !SignedEnum &&
10622 ED->getNumPositiveBits() == FieldWidth) {
10623 DiagID = diag::warn_signed_bitfield_enum_conversion;
10624 }
10625
10626 if (DiagID) {
10627 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10628 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10629 SourceRange TypeRange =
10630 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10631 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10632 << SignedEnum << TypeRange;
10633 }
10634
10635 // Compute the required bitwidth. If the enum has negative values, we need
10636 // one more bit than the normal number of positive bits to represent the
10637 // sign bit.
10638 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10639 ED->getNumNegativeBits())
10640 : ED->getNumPositiveBits();
10641
10642 // Check the bitwidth.
10643 if (BitsNeeded > FieldWidth) {
10644 Expr *WidthExpr = Bitfield->getBitWidth();
10645 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10646 << Bitfield << ED;
10647 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10648 << BitsNeeded << ED << WidthExpr->getSourceRange();
10649 }
10650 }
10651
John McCall1f425642010-11-11 03:21:53 +000010652 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010653 }
John McCall1f425642010-11-11 03:21:53 +000010654
Fangrui Song407659a2018-11-30 23:41:18 +000010655 llvm::APSInt Value = Result.Val.getInt();
10656
John McCall1f425642010-11-11 03:21:53 +000010657 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010658
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010659 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000010660 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010661 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10662 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000010663
John McCall1f425642010-11-11 03:21:53 +000010664 if (OriginalWidth <= FieldWidth)
10665 return false;
10666
Eli Friedmanc267a322012-01-26 23:11:39 +000010667 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010668 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000010669 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000010670
Eli Friedmanc267a322012-01-26 23:11:39 +000010671 // Check whether the stored value is equal to the original value.
10672 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000010673 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000010674 return false;
10675
Eli Friedmanc267a322012-01-26 23:11:39 +000010676 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000010677 // therefore don't strictly fit into a signed bitfield of width 1.
10678 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000010679 return false;
10680
John McCall1f425642010-11-11 03:21:53 +000010681 std::string PrettyValue = Value.toString(10);
10682 std::string PrettyTrunc = TruncatedValue.toString(10);
10683
10684 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10685 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10686 << Init->getSourceRange();
10687
10688 return true;
10689}
10690
John McCalld2a53122010-11-09 23:24:47 +000010691/// Analyze the given simple or compound assignment for warning-worthy
10692/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010693static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000010694 // Just recurse on the LHS.
10695 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10696
10697 // We want to recurse on the RHS as normal unless we're assigning to
10698 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000010699 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010700 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000010701 E->getOperatorLoc())) {
10702 // Recurse, ignoring any implicit conversions on the RHS.
10703 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10704 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000010705 }
10706 }
10707
10708 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000010709
JF Bastiene77b48b2018-09-10 20:42:56 +000010710 // Diagnose implicitly sequentially-consistent atomic assignment.
10711 if (E->getLHS()->getType()->isAtomicType())
10712 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000010713}
10714
John McCall263a48b2010-01-04 23:31:57 +000010715/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000010716static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010717 SourceLocation CContext, unsigned diag,
10718 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010719 if (pruneControlFlow) {
10720 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10721 S.PDiag(diag)
10722 << SourceType << T << E->getSourceRange()
10723 << SourceRange(CContext));
10724 return;
10725 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000010726 S.Diag(E->getExprLoc(), diag)
10727 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10728}
10729
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010730/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010731static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10732 SourceLocation CContext,
10733 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010734 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010735}
10736
Richard Trieube234c32016-04-21 21:04:55 +000010737/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010738static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10739 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000010740 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000010741 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000010742
10743 Expr *InnerE = E->IgnoreParenImpCasts();
10744 // We also want to warn on, e.g., "int i = -1.234"
10745 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10746 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10747 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10748
10749 const bool IsLiteral =
10750 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10751
10752 llvm::APFloat Value(0.0);
10753 bool IsConstant =
10754 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10755 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +000010756 return DiagnoseImpCast(S, E, T, CContext,
10757 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000010758 }
10759
Chandler Carruth016ef402011-04-10 08:36:24 +000010760 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000010761
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000010762 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10763 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000010764 llvm::APFloat::opStatus Result = Value.convertToInteger(
10765 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10766
10767 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000010768 if (IsLiteral) return;
10769 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10770 PruneWarnings);
10771 }
10772
Erich Keanea4c48c62018-05-08 21:26:21 +000010773 // Conversion of a floating-point value to a non-bool integer where the
10774 // integral part cannot be represented by the integer type is undefined.
10775 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10776 return DiagnoseImpCast(
10777 S, E, T, CContext,
10778 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000010779 : diag::warn_impcast_float_to_integer_out_of_range,
10780 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000010781
Richard Trieube234c32016-04-21 21:04:55 +000010782 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000010783 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000010784 // Warn on floating point literal to integer.
10785 DiagID = diag::warn_impcast_literal_float_to_integer;
10786 } else if (IntegerValue == 0) {
10787 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10788 return DiagnoseImpCast(S, E, T, CContext,
10789 diag::warn_impcast_float_integer, PruneWarnings);
10790 }
10791 // Warn on non-zero to zero conversion.
10792 DiagID = diag::warn_impcast_float_to_integer_zero;
10793 } else {
10794 if (IntegerValue.isUnsigned()) {
10795 if (!IntegerValue.isMaxValue()) {
10796 return DiagnoseImpCast(S, E, T, CContext,
10797 diag::warn_impcast_float_integer, PruneWarnings);
10798 }
10799 } else { // IntegerValue.isSigned()
10800 if (!IntegerValue.isMaxSignedValue() &&
10801 !IntegerValue.isMinSignedValue()) {
10802 return DiagnoseImpCast(S, E, T, CContext,
10803 diag::warn_impcast_float_integer, PruneWarnings);
10804 }
10805 }
10806 // Warn on evaluatable floating point expression to integer conversion.
10807 DiagID = diag::warn_impcast_float_to_integer;
10808 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010809
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010810 // FIXME: Force the precision of the source value down so we don't print
10811 // digits which are usually useless (we don't really care here if we
10812 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10813 // would automatically print the shortest representation, but it's a bit
10814 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +000010815 SmallString<16> PrettySourceValue;
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010816 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10817 precision = (precision * 59 + 195) / 196;
10818 Value.toString(PrettySourceValue, precision);
Eli Friedman07185912013-08-29 23:44:43 +000010819
David Blaikie9b88cc02012-05-15 17:18:27 +000010820 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000010821 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000010822 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000010823 else
David Blaikie9b88cc02012-05-15 17:18:27 +000010824 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000010825
Richard Trieube234c32016-04-21 21:04:55 +000010826 if (PruneWarnings) {
10827 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10828 S.PDiag(DiagID)
10829 << E->getType() << T.getUnqualifiedType()
10830 << PrettySourceValue << PrettyTargetValue
10831 << E->getSourceRange() << SourceRange(CContext));
10832 } else {
10833 S.Diag(E->getExprLoc(), DiagID)
10834 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10835 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10836 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010837}
10838
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010839/// Analyze the given compound assignment for the possible losing of
10840/// floating-point precision.
10841static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10842 assert(isa<CompoundAssignOperator>(E) &&
10843 "Must be compound assignment operation");
10844 // Recurse on the LHS and RHS in here
10845 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10846 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10847
JF Bastiene77b48b2018-09-10 20:42:56 +000010848 if (E->getLHS()->getType()->isAtomicType())
10849 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10850
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010851 // Now check the outermost expression
10852 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10853 const auto *RBT = cast<CompoundAssignOperator>(E)
10854 ->getComputationResultType()
10855 ->getAs<BuiltinType>();
10856
10857 // The below checks assume source is floating point.
10858 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10859
Erik Pilkingtond5b017d2019-02-14 22:48:01 +000010860 // If source is floating point but target is an integer.
10861 if (ResultBT->isInteger())
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000010862 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10863 E->getExprLoc(), diag::warn_impcast_float_integer);
10864
10865 if (!ResultBT->isFloatingPoint())
10866 return;
10867
10868 // If both source and target are floating points, warn about losing precision.
10869 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10870 QualType(ResultBT, 0), QualType(RBT, 0));
10871 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010872 // warn about dropping FP rank.
10873 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10874 diag::warn_impcast_float_result_precision);
10875}
10876
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010877static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10878 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000010879 if (!Range.Width) return "0";
10880
10881 llvm::APSInt ValueInRange = Value;
10882 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000010883 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000010884 return ValueInRange.toString(10);
10885}
10886
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010887static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010888 if (!isa<ImplicitCastExpr>(Ex))
10889 return false;
10890
10891 Expr *InnerE = Ex->IgnoreParenImpCasts();
10892 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10893 const Type *Source =
10894 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10895 if (Target->isDependentType())
10896 return false;
10897
10898 const BuiltinType *FloatCandidateBT =
10899 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10900 const Type *BoolCandidateType = ToBool ? Target : Source;
10901
10902 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10903 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10904}
10905
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010906static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10907 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010908 unsigned NumArgs = TheCall->getNumArgs();
10909 for (unsigned i = 0; i < NumArgs; ++i) {
10910 Expr *CurrA = TheCall->getArg(i);
10911 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10912 continue;
10913
10914 bool IsSwapped = ((i > 0) &&
10915 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10916 IsSwapped |= ((i < (NumArgs - 1)) &&
10917 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10918 if (IsSwapped) {
10919 // Warn on this floating-point to bool conversion.
10920 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10921 CurrA->getType(), CC,
10922 diag::warn_impcast_floating_point_to_bool);
10923 }
10924 }
10925}
10926
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010927static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10928 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000010929 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10930 E->getExprLoc()))
10931 return;
10932
Richard Trieu09d6b802016-01-08 23:35:06 +000010933 // Don't warn on functions which have return type nullptr_t.
10934 if (isa<CallExpr>(E))
10935 return;
10936
Richard Trieu5b993502014-10-15 03:42:06 +000010937 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10938 const Expr::NullPointerConstantKind NullKind =
10939 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10940 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10941 return;
10942
10943 // Return if target type is a safe conversion.
10944 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10945 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10946 return;
10947
10948 SourceLocation Loc = E->getSourceRange().getBegin();
10949
Richard Trieu0a5e1662016-02-13 00:58:53 +000010950 // Venture through the macro stacks to get to the source of macro arguments.
10951 // The new location is a better location than the complete location that was
10952 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000010953 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10954 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010955
Richard Trieu5b993502014-10-15 03:42:06 +000010956 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010957 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10958 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10959 Loc, S.SourceMgr, S.getLangOpts());
10960 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010961 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010962 }
10963
10964 // Only warn if the null and context location are in the same macro expansion.
10965 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10966 return;
10967
10968 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010969 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010970 << FixItHint::CreateReplacement(Loc,
10971 S.getFixItZeroLiteralForType(T, Loc));
10972}
10973
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010974static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10975 ObjCArrayLiteral *ArrayLiteral);
10976
10977static void
10978checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10979 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010980
10981/// Check a single element within a collection literal against the
10982/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010983static void checkObjCCollectionLiteralElement(Sema &S,
10984 QualType TargetElementType,
10985 Expr *Element,
10986 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010987 // Skip a bitcast to 'id' or qualified 'id'.
10988 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10989 if (ICE->getCastKind() == CK_BitCast &&
10990 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10991 Element = ICE->getSubExpr();
10992 }
10993
10994 QualType ElementType = Element->getType();
10995 ExprResult ElementResult(Element);
10996 if (ElementType->getAs<ObjCObjectPointerType>() &&
10997 S.CheckSingleAssignmentConstraints(TargetElementType,
10998 ElementResult,
10999 false, false)
11000 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011001 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11002 << ElementType << ElementKind << TargetElementType
11003 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000011004 }
11005
11006 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11007 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11008 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11009 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11010}
11011
11012/// Check an Objective-C array literal being converted to the given
11013/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011014static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11015 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011016 if (!S.NSArrayDecl)
11017 return;
11018
11019 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11020 if (!TargetObjCPtr)
11021 return;
11022
11023 if (TargetObjCPtr->isUnspecialized() ||
11024 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11025 != S.NSArrayDecl->getCanonicalDecl())
11026 return;
11027
11028 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11029 if (TypeArgs.size() != 1)
11030 return;
11031
11032 QualType TargetElementType = TypeArgs[0];
11033 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11034 checkObjCCollectionLiteralElement(S, TargetElementType,
11035 ArrayLiteral->getElement(I),
11036 0);
11037 }
11038}
11039
11040/// Check an Objective-C dictionary literal being converted to the given
11041/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011042static void
11043checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11044 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011045 if (!S.NSDictionaryDecl)
11046 return;
11047
11048 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11049 if (!TargetObjCPtr)
11050 return;
11051
11052 if (TargetObjCPtr->isUnspecialized() ||
11053 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11054 != S.NSDictionaryDecl->getCanonicalDecl())
11055 return;
11056
11057 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11058 if (TypeArgs.size() != 2)
11059 return;
11060
11061 QualType TargetKeyType = TypeArgs[0];
11062 QualType TargetObjectType = TypeArgs[1];
11063 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11064 auto Element = DictionaryLiteral->getKeyValueElement(I);
11065 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11066 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11067 }
11068}
11069
Richard Trieufc404c72016-02-05 23:02:38 +000011070// Helper function to filter out cases for constant width constant conversion.
11071// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011072static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11073 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000011074 // If initializing from a constant, and the constant starts with '0',
11075 // then it is a binary, octal, or hexadecimal. Allow these constants
11076 // to fill all the bits, even if there is a sign change.
11077 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11078 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011079 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000011080 if (FirstLiteralCharacter == '0')
11081 return false;
11082 }
11083
11084 // If the CC location points to a '{', and the type is char, then assume
11085 // assume it is an array initialization.
11086 if (CC.isValid() && T->isCharType()) {
11087 const char FirstContextCharacter =
11088 S.getSourceManager().getCharacterData(CC)[0];
11089 if (FirstContextCharacter == '{')
11090 return false;
11091 }
11092
11093 return true;
11094}
11095
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011096static void
11097CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
11098 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011099 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000011100
John McCallcc7e5bf2010-05-06 08:58:33 +000011101 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11102 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11103 if (Source == Target) return;
11104 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000011105
Chandler Carruthc22845a2011-07-26 05:40:03 +000011106 // If the conversion context location is invalid don't complain. We also
11107 // don't want to emit a warning if the issue occurs from the expansion of
11108 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11109 // delay this check as long as possible. Once we detect we are in that
11110 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011111 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000011112 return;
11113
JF Bastiene77b48b2018-09-10 20:42:56 +000011114 if (Source->isAtomicType())
11115 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11116
Richard Trieu021baa32011-09-23 20:10:00 +000011117 // Diagnose implicit casts to bool.
11118 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11119 if (isa<StringLiteral>(E))
11120 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000011121 // and expressions, for instance, assert(0 && "error here"), are
11122 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000011123 return DiagnoseImpCast(S, E, T, CC,
11124 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000011125 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11126 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11127 // This covers the literal expressions that evaluate to Objective-C
11128 // objects.
11129 return DiagnoseImpCast(S, E, T, CC,
11130 diag::warn_impcast_objective_c_literal_to_bool);
11131 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011132 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11133 // Warn on pointer to bool conversion that is always true.
11134 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11135 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000011136 }
Richard Trieu021baa32011-09-23 20:10:00 +000011137 }
John McCall263a48b2010-01-04 23:31:57 +000011138
Douglas Gregor5054cb02015-07-07 03:58:22 +000011139 // Check implicit casts from Objective-C collection literals to specialized
11140 // collection types, e.g., NSArray<NSString *> *.
11141 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11142 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11143 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11144 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11145
John McCall263a48b2010-01-04 23:31:57 +000011146 // Strip vector types.
11147 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011148 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011149 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011150 return;
John McCallacf0ee52010-10-08 02:01:28 +000011151 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011152 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011153
Chris Lattneree7286f2011-06-14 04:51:15 +000011154 // If the vector cast is cast between two vectors of the same size, it is
11155 // a bitcast, not a conversion.
11156 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11157 return;
John McCall263a48b2010-01-04 23:31:57 +000011158
11159 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11160 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11161 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000011162 if (auto VecTy = dyn_cast<VectorType>(Target))
11163 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000011164
11165 // Strip complex types.
11166 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011167 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000011168 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011169 return;
11170
Tim Northover02416372017-08-08 23:18:05 +000011171 return DiagnoseImpCast(S, E, T, CC,
11172 S.getLangOpts().CPlusPlus
11173 ? diag::err_impcast_complex_scalar
11174 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011175 }
John McCall263a48b2010-01-04 23:31:57 +000011176
11177 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11178 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11179 }
11180
11181 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11182 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11183
11184 // If the source is floating point...
11185 if (SourceBT && SourceBT->isFloatingPoint()) {
11186 // ...and the target is floating point...
11187 if (TargetBT && TargetBT->isFloatingPoint()) {
11188 // ...then warn if we're dropping FP rank.
11189
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011190 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11191 QualType(SourceBT, 0), QualType(TargetBT, 0));
11192 if (Order > 0) {
John McCall263a48b2010-01-04 23:31:57 +000011193 // Don't warn about float constants that are precisely
11194 // representable in the target type.
11195 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000011196 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000011197 // Value might be a float, a float vector, or a float complex.
11198 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000011199 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11200 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000011201 return;
11202 }
11203
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011204 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011205 return;
11206
John McCallacf0ee52010-10-08 02:01:28 +000011207 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000011208 }
11209 // ... or possibly if we're increasing rank, too
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011210 else if (Order < 0) {
George Burgess IV148e0d32015-10-29 00:28:52 +000011211 if (S.SourceMgr.isInSystemMacro(CC))
11212 return;
11213
11214 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000011215 }
11216 return;
11217 }
11218
Richard Trieube234c32016-04-21 21:04:55 +000011219 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000011220 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011221 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011222 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000011223
Richard Trieube234c32016-04-21 21:04:55 +000011224 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000011225 }
John McCall263a48b2010-01-04 23:31:57 +000011226
Richard Smith54894fd2015-12-30 01:06:52 +000011227 // Detect the case where a call result is converted from floating-point to
11228 // to bool, and the final argument to the call is converted from bool, to
11229 // discover this typo:
11230 //
11231 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11232 //
11233 // FIXME: This is an incredibly special case; is there some more general
11234 // way to detect this class of misplaced-parentheses bug?
11235 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011236 // Check last argument of function call to see if it is an
11237 // implicit cast from a type matching the type the result
11238 // is being cast to.
11239 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000011240 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011241 Expr *LastA = CEx->getArg(NumArgs - 1);
11242 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000011243 if (isa<ImplicitCastExpr>(LastA) &&
11244 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011245 // Warn on this floating-point to bool conversion
11246 DiagnoseImpCast(S, E, T, CC,
11247 diag::warn_impcast_floating_point_to_bool);
11248 }
11249 }
11250 }
John McCall263a48b2010-01-04 23:31:57 +000011251 return;
11252 }
11253
Leonard Chan8f7caae2019-03-06 00:28:43 +000011254 // Valid casts involving fixed point types should be accounted for here.
Leonard Chand3f3e162019-01-18 21:04:25 +000011255 if (Source->isFixedPointType()) {
Leonard Chan8f7caae2019-03-06 00:28:43 +000011256 if (Target->isUnsaturatedFixedPointType()) {
Leonard Chand3f3e162019-01-18 21:04:25 +000011257 Expr::EvalResult Result;
11258 if (E->EvaluateAsFixedPoint(Result, S.Context,
11259 Expr::SE_AllowSideEffects)) {
11260 APFixedPoint Value = Result.Val.getFixedPoint();
11261 APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11262 APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11263 if (Value > MaxVal || Value < MinVal) {
11264 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11265 S.PDiag(diag::warn_impcast_fixed_point_range)
11266 << Value.toString() << T
11267 << E->getSourceRange()
11268 << clang::SourceRange(CC));
11269 return;
11270 }
11271 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011272 } else if (Target->isIntegerType()) {
11273 Expr::EvalResult Result;
11274 if (E->EvaluateAsFixedPoint(Result, S.Context,
11275 Expr::SE_AllowSideEffects)) {
11276 APFixedPoint FXResult = Result.Val.getFixedPoint();
11277
11278 bool Overflowed;
11279 llvm::APSInt IntResult = FXResult.convertToInt(
11280 S.Context.getIntWidth(T),
11281 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11282
11283 if (Overflowed) {
11284 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11285 S.PDiag(diag::warn_impcast_fixed_point_range)
11286 << FXResult.toString() << T
11287 << E->getSourceRange()
11288 << clang::SourceRange(CC));
11289 return;
11290 }
11291 }
11292 }
11293 } else if (Target->isUnsaturatedFixedPointType()) {
11294 if (Source->isIntegerType()) {
11295 Expr::EvalResult Result;
11296 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11297 llvm::APSInt Value = Result.Val.getInt();
11298
11299 bool Overflowed;
11300 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11301 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11302
11303 if (Overflowed) {
11304 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11305 S.PDiag(diag::warn_impcast_fixed_point_range)
11306 << Value.toString(/*radix=*/10) << T
11307 << E->getSourceRange()
11308 << clang::SourceRange(CC));
11309 return;
11310 }
11311 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011312 }
11313 }
11314
Richard Trieu5b993502014-10-15 03:42:06 +000011315 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000011316
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011317 S.DiscardMisalignedMemberAddress(Target, E);
11318
David Blaikie9366d2b2012-06-19 21:19:06 +000011319 if (!Source->isIntegerType() || !Target->isIntegerType())
11320 return;
11321
David Blaikie7555b6a2012-05-15 16:56:36 +000011322 // TODO: remove this early return once the false positives for constant->bool
11323 // in templates, macros, etc, are reduced or removed.
11324 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11325 return;
11326
John McCallcc7e5bf2010-05-06 08:58:33 +000011327 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000011328 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000011329
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011330 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000011331 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011332 // TODO: this should happen for bitfield stores, too.
Fangrui Song407659a2018-11-30 23:41:18 +000011333 Expr::EvalResult Result;
11334 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11335 llvm::APSInt Value(32);
11336 Value = Result.Val.getInt();
11337
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011338 if (S.SourceMgr.isInSystemMacro(CC))
11339 return;
11340
John McCall18a2c2c2010-11-09 22:22:12 +000011341 std::string PrettySourceValue = Value.toString(10);
11342 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011343
Ted Kremenek33ba9952011-10-22 02:37:33 +000011344 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11345 S.PDiag(diag::warn_impcast_integer_precision_constant)
11346 << PrettySourceValue << PrettyTargetValue
11347 << E->getType() << T << E->getSourceRange()
11348 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000011349 return;
11350 }
11351
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011352 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11353 if (S.SourceMgr.isInSystemMacro(CC))
11354 return;
11355
David Blaikie9455da02012-04-12 22:40:54 +000011356 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000011357 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11358 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000011359 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000011360 }
11361
David Bolvanskycf7d2252018-10-02 06:02:30 +000011362 if (TargetRange.Width > SourceRange.Width) {
11363 if (auto *UO = dyn_cast<UnaryOperator>(E))
11364 if (UO->getOpcode() == UO_Minus)
11365 if (Source->isUnsignedIntegerType()) {
11366 if (Target->isUnsignedIntegerType())
11367 return DiagnoseImpCast(S, E, T, CC,
11368 diag::warn_impcast_high_order_zero_bits);
11369 if (Target->isSignedIntegerType())
11370 return DiagnoseImpCast(S, E, T, CC,
11371 diag::warn_impcast_nonnegative_result);
11372 }
11373 }
11374
Richard Trieudcb55572016-01-29 23:51:16 +000011375 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11376 SourceRange.NonNegative && Source->isSignedIntegerType()) {
11377 // Warn when doing a signed to signed conversion, warn if the positive
11378 // source value is exactly the width of the target type, which will
11379 // cause a negative value to be stored.
11380
Fangrui Song407659a2018-11-30 23:41:18 +000011381 Expr::EvalResult Result;
11382 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
Richard Trieufc404c72016-02-05 23:02:38 +000011383 !S.SourceMgr.isInSystemMacro(CC)) {
Fangrui Song407659a2018-11-30 23:41:18 +000011384 llvm::APSInt Value = Result.Val.getInt();
Richard Trieufc404c72016-02-05 23:02:38 +000011385 if (isSameWidthConstantConversion(S, E, T, CC)) {
11386 std::string PrettySourceValue = Value.toString(10);
11387 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000011388
Richard Trieufc404c72016-02-05 23:02:38 +000011389 S.DiagRuntimeBehavior(
11390 E->getExprLoc(), E,
11391 S.PDiag(diag::warn_impcast_integer_precision_constant)
11392 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11393 << E->getSourceRange() << clang::SourceRange(CC));
11394 return;
Richard Trieudcb55572016-01-29 23:51:16 +000011395 }
11396 }
Richard Trieufc404c72016-02-05 23:02:38 +000011397
Richard Trieudcb55572016-01-29 23:51:16 +000011398 // Fall through for non-constants to give a sign conversion warning.
11399 }
11400
John McCallcc7e5bf2010-05-06 08:58:33 +000011401 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11402 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11403 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011404 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011405 return;
11406
John McCallcc7e5bf2010-05-06 08:58:33 +000011407 unsigned DiagID = diag::warn_impcast_integer_sign;
11408
11409 // Traditionally, gcc has warned about this under -Wsign-compare.
11410 // We also want to warn about it in -Wconversion.
11411 // So if -Wconversion is off, use a completely identical diagnostic
11412 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011413 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011414 if (ICContext) {
11415 DiagID = diag::warn_impcast_integer_sign_conditional;
11416 *ICContext = true;
11417 }
11418
John McCallacf0ee52010-10-08 02:01:28 +000011419 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011420 }
11421
Douglas Gregora78f1932011-02-22 02:45:07 +000011422 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011423 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11424 // type, to give us better diagnostics.
11425 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011426 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011427 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11428 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11429 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11430 SourceType = S.Context.getTypeDeclType(Enum);
11431 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11432 }
11433 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011434
Douglas Gregora78f1932011-02-22 02:45:07 +000011435 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11436 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011437 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11438 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011439 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011440 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011441 return;
11442
Fangrui Song6907ce22018-07-30 19:24:48 +000011443 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011444 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011445 }
John McCall263a48b2010-01-04 23:31:57 +000011446}
11447
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011448static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11449 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011450
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011451static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11452 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011453 E = E->IgnoreParenImpCasts();
11454
11455 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011456 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011457
John McCallacf0ee52010-10-08 02:01:28 +000011458 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011459 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011460 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011461}
11462
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011463static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11464 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011465 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011466
11467 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011468 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11469 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011470
11471 // If -Wconversion would have warned about either of the candidates
11472 // for a signedness conversion to the context type...
11473 if (!Suspicious) return;
11474
11475 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011476 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000011477 return;
11478
John McCallcc7e5bf2010-05-06 08:58:33 +000011479 // ...then check whether it would have warned about either of the
11480 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000011481 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000011482
Richard Trieubb43dec2011-07-21 02:46:28 +000011483 Suspicious = false;
11484 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11485 E->getType(), CC, &Suspicious);
11486 if (!Suspicious)
11487 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000011488 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011489}
11490
JF Bastiene77b48b2018-09-10 20:42:56 +000011491/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000011492/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011493static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000011494 if (S.getLangOpts().Bool)
11495 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000011496 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11497 return;
Richard Trieu65724892014-11-15 06:37:39 +000011498 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11499}
11500
John McCallcc7e5bf2010-05-06 08:58:33 +000011501/// AnalyzeImplicitConversions - Find and report any interesting
11502/// implicit conversions in the given expression. There are a couple
11503/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011504static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11505 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000011506 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000011507 Expr *E = OrigE->IgnoreParenImpCasts();
11508
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000011509 if (E->isTypeDependent() || E->isValueDependent())
11510 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011511
John McCallcc7e5bf2010-05-06 08:58:33 +000011512 // For conditional operators, we analyze the arguments as if they
11513 // were being fed directly into the output.
11514 if (isa<ConditionalOperator>(E)) {
11515 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000011516 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011517 return;
11518 }
11519
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011520 // Check implicit argument conversions for function calls.
11521 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11522 CheckImplicitArgumentConversions(S, Call, CC);
11523
John McCallcc7e5bf2010-05-06 08:58:33 +000011524 // Go ahead and check any implicit conversions we might have skipped.
11525 // The non-canonical typecheck is just an optimization;
11526 // CheckImplicitConversion will filter out dead implicit conversions.
11527 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011528 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011529
11530 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000011531
11532 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11533 // The bound subexpressions in a PseudoObjectExpr are not reachable
11534 // as transitive children.
11535 // FIXME: Use a more uniform representation for this.
11536 for (auto *SE : POE->semantics())
11537 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11538 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000011539 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000011540
John McCallcc7e5bf2010-05-06 08:58:33 +000011541 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000011542 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11543 E = CE->getSubExpr()->IgnoreParenImpCasts();
11544 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11545 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCallacf0ee52010-10-08 02:01:28 +000011546 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011547 }
11548
John McCalld2a53122010-11-09 23:24:47 +000011549 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11550 // Do a somewhat different check with comparison operators.
11551 if (BO->isComparisonOp())
11552 return AnalyzeComparison(S, BO);
11553
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011554 // And with simple assignments.
11555 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000011556 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011557 // And with compound assignments.
11558 if (BO->isAssignmentOp())
11559 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000011560 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011561
11562 // These break the otherwise-useful invariant below. Fortunately,
11563 // we don't really need to recurse into them, because any internal
11564 // expressions should have been analyzed already when they were
11565 // built into statements.
11566 if (isa<StmtExpr>(E)) return;
11567
11568 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000011569 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000011570
11571 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000011572 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000011573 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000011574 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000011575 for (Stmt *SubStmt : E->children()) {
11576 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000011577 if (!ChildExpr)
11578 continue;
11579
Richard Trieu955231d2014-01-25 01:10:35 +000011580 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000011581 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000011582 // Ignore checking string literals that are in logical and operators.
11583 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000011584 continue;
11585 AnalyzeImplicitConversions(S, ChildExpr, CC);
11586 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011587
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011588 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000011589 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11590 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011591 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000011592
11593 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11594 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011595 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011596 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011597
JF Bastiene77b48b2018-09-10 20:42:56 +000011598 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11599 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000011600 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000011601 } else if (U->getOpcode() != UO_AddrOf) {
11602 if (U->getSubExpr()->getType()->isAtomicType())
11603 S.Diag(U->getSubExpr()->getBeginLoc(),
11604 diag::warn_atomic_implicit_seq_cst);
11605 }
11606 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011607}
11608
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011609/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011610static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11611 // Taking into account implicit conversions,
11612 // allow any integer.
11613 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011614 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011615 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11616 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011617 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011618 // Potentially emit standard warnings for implicit conversions if enabled
11619 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011620 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011621 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011622}
11623
Richard Trieuc1888e02014-06-28 23:25:37 +000011624// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11625// Returns true when emitting a warning about taking the address of a reference.
11626static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000011627 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000011628 E = E->IgnoreParenImpCasts();
11629
11630 const FunctionDecl *FD = nullptr;
11631
11632 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11633 if (!DRE->getDecl()->getType()->isReferenceType())
11634 return false;
11635 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11636 if (!M->getMemberDecl()->getType()->isReferenceType())
11637 return false;
11638 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000011639 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000011640 return false;
11641 FD = Call->getDirectCallee();
11642 } else {
11643 return false;
11644 }
11645
11646 SemaRef.Diag(E->getExprLoc(), PD);
11647
11648 // If possible, point to location of function.
11649 if (FD) {
11650 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11651 }
11652
11653 return true;
11654}
11655
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011656// Returns true if the SourceLocation is expanded from any macro body.
11657// Returns false if the SourceLocation is invalid, is from not in a macro
11658// expansion, or is from expanded from a top-level macro argument.
11659static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11660 if (Loc.isInvalid())
11661 return false;
11662
11663 while (Loc.isMacroID()) {
11664 if (SM.isMacroBodyExpansion(Loc))
11665 return true;
11666 Loc = SM.getImmediateMacroCallerLoc(Loc);
11667 }
11668
11669 return false;
11670}
11671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011672/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000011673/// \param E the expression containing the pointer
11674/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11675/// compared to a null pointer
11676/// \param IsEqual True when the comparison is equal to a null pointer
11677/// \param Range Extra SourceRange to highlight in the diagnostic
11678void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11679 Expr::NullPointerConstantKind NullKind,
11680 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011681 if (!E)
11682 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011683
11684 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011685 if (E->getExprLoc().isMacroID()) {
11686 const SourceManager &SM = getSourceManager();
11687 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11688 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000011689 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011690 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011691 E = E->IgnoreImpCasts();
11692
11693 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11694
Richard Trieuf7432752014-06-06 21:39:26 +000011695 if (isa<CXXThisExpr>(E)) {
11696 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11697 : diag::warn_this_bool_conversion;
11698 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11699 return;
11700 }
11701
Richard Trieu3bb8b562014-02-26 02:36:06 +000011702 bool IsAddressOf = false;
11703
11704 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11705 if (UO->getOpcode() != UO_AddrOf)
11706 return;
11707 IsAddressOf = true;
11708 E = UO->getSubExpr();
11709 }
11710
Richard Trieuc1888e02014-06-28 23:25:37 +000011711 if (IsAddressOf) {
11712 unsigned DiagID = IsCompare
11713 ? diag::warn_address_of_reference_null_compare
11714 : diag::warn_address_of_reference_bool_conversion;
11715 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11716 << IsEqual;
11717 if (CheckForReference(*this, E, PD)) {
11718 return;
11719 }
11720 }
11721
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011722 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11723 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000011724 std::string Str;
11725 llvm::raw_string_ostream S(Str);
11726 E->printPretty(S, nullptr, getPrintingPolicy());
11727 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11728 : diag::warn_cast_nonnull_to_bool;
11729 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11730 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011731 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000011732 };
11733
11734 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11735 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11736 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011737 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11738 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011739 return;
11740 }
11741 }
11742 }
11743
Richard Trieu3bb8b562014-02-26 02:36:06 +000011744 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000011745 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011746 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11747 D = R->getDecl();
11748 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11749 D = M->getMemberDecl();
11750 }
11751
11752 // Weak Decls can be null.
11753 if (!D || D->isWeak())
11754 return;
George Burgess IV850269a2015-12-08 22:02:00 +000011755
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011756 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000011757 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11758 if (getCurFunction() &&
11759 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011760 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11761 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011762 return;
11763 }
11764
11765 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
Michael Liaoce389922019-03-29 03:55:52 +000011766 // Skip function template not specialized yet.
11767 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11768 return;
David Majnemera3debed2016-06-24 05:33:44 +000011769 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000011770 assert(ParamIter != FD->param_end());
11771 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11772
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011773 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11774 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011775 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000011776 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011777 }
George Burgess IV850269a2015-12-08 22:02:00 +000011778
Joel E. Denny81508102018-03-13 14:51:22 +000011779 for (const ParamIdx &ArgNo : NonNull->args()) {
11780 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011781 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011782 return;
11783 }
George Burgess IV850269a2015-12-08 22:02:00 +000011784 }
11785 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011786 }
11787 }
George Burgess IV850269a2015-12-08 22:02:00 +000011788 }
11789
Richard Trieu3bb8b562014-02-26 02:36:06 +000011790 QualType T = D->getType();
11791 const bool IsArray = T->isArrayType();
11792 const bool IsFunction = T->isFunctionType();
11793
Richard Trieuc1888e02014-06-28 23:25:37 +000011794 // Address of function is used to silence the function warning.
11795 if (IsAddressOf && IsFunction) {
11796 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011797 }
11798
11799 // Found nothing.
11800 if (!IsAddressOf && !IsFunction && !IsArray)
11801 return;
11802
11803 // Pretty print the expression for the diagnostic.
11804 std::string Str;
11805 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000011806 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000011807
11808 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11809 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000011810 enum {
11811 AddressOf,
11812 FunctionPointer,
11813 ArrayPointer
11814 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011815 if (IsAddressOf)
11816 DiagType = AddressOf;
11817 else if (IsFunction)
11818 DiagType = FunctionPointer;
11819 else if (IsArray)
11820 DiagType = ArrayPointer;
11821 else
11822 llvm_unreachable("Could not determine diagnostic.");
11823 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11824 << Range << IsEqual;
11825
11826 if (!IsFunction)
11827 return;
11828
11829 // Suggest '&' to silence the function warning.
11830 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011831 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011832
11833 // Check to see if '()' fixit should be emitted.
11834 QualType ReturnType;
11835 UnresolvedSet<4> NonTemplateOverloads;
11836 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11837 if (ReturnType.isNull())
11838 return;
11839
11840 if (IsCompare) {
11841 // There are two cases here. If there is null constant, the only suggest
11842 // for a pointer return type. If the null is 0, then suggest if the return
11843 // type is a pointer or an integer type.
11844 if (!ReturnType->isPointerType()) {
11845 if (NullKind == Expr::NPCK_ZeroExpression ||
11846 NullKind == Expr::NPCK_ZeroLiteral) {
11847 if (!ReturnType->isIntegerType())
11848 return;
11849 } else {
11850 return;
11851 }
11852 }
11853 } else { // !IsCompare
11854 // For function to bool, only suggest if the function pointer has bool
11855 // return type.
11856 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11857 return;
11858 }
11859 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000011860 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011861}
11862
John McCallcc7e5bf2010-05-06 08:58:33 +000011863/// Diagnoses "dangerous" implicit conversions within the given
11864/// expression (which is a full expression). Implements -Wconversion
11865/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000011866///
11867/// \param CC the "context" location of the implicit conversion, i.e.
11868/// the most location of the syntactic entity requiring the implicit
11869/// conversion
11870void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011871 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000011872 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000011873 return;
11874
11875 // Don't diagnose for value- or type-dependent expressions.
11876 if (E->isTypeDependent() || E->isValueDependent())
11877 return;
11878
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011879 // Check for array bounds violations in cases where the check isn't triggered
11880 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11881 // ArraySubscriptExpr is on the RHS of a variable initialization.
11882 CheckArrayAccess(E);
11883
John McCallacf0ee52010-10-08 02:01:28 +000011884 // This is not the right CC for (e.g.) a variable initialization.
11885 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011886}
11887
Richard Trieu65724892014-11-15 06:37:39 +000011888/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11889/// Input argument E is a logical expression.
11890void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11891 ::CheckBoolLikeConversion(*this, E, CC);
11892}
11893
Richard Smith9f7df0c2017-06-26 23:19:32 +000011894/// Diagnose when expression is an integer constant expression and its evaluation
11895/// results in integer overflow
11896void Sema::CheckForIntOverflow (Expr *E) {
11897 // Use a work list to deal with nested struct initializers.
11898 SmallVector<Expr *, 2> Exprs(1, E);
11899
11900 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011901 Expr *OriginalE = Exprs.pop_back_val();
11902 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000011903
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011904 if (isa<BinaryOperator>(E)) {
11905 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000011906 continue;
11907 }
11908
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011909 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000011910 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011911 else if (isa<ObjCBoxedExpr>(OriginalE))
11912 E->EvaluateForOverflow(Context);
11913 else if (auto Call = dyn_cast<CallExpr>(E))
11914 Exprs.append(Call->arg_begin(), Call->arg_end());
11915 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11916 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000011917 } while (!Exprs.empty());
11918}
11919
Richard Smithc406cb72013-01-17 01:17:56 +000011920namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011922/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000011923/// same object.
11924class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011925 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000011926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011927 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000011928 /// unsequenced if one is an ancestor or a descendent of the other. When we
11929 /// finish processing an expression with sequencing, such as a comma
11930 /// expression, we fold its tree nodes into its parent, since they are
11931 /// unsequenced with respect to nodes we will visit later.
11932 class SequenceTree {
11933 struct Value {
11934 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11935 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000011936 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000011937 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011938 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000011939
11940 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011941 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000011942 /// to some other region.
11943 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000011944 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011945
Serge Gueltonbe885392019-01-20 21:19:56 +000011946 unsigned Index;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011947
11948 explicit Seq(unsigned N) : Index(N) {}
11949
Richard Smithc406cb72013-01-17 01:17:56 +000011950 public:
Serge Gueltonbe885392019-01-20 21:19:56 +000011951 Seq() : Index(0) {}
Richard Smithc406cb72013-01-17 01:17:56 +000011952 };
11953
11954 SequenceTree() { Values.push_back(Value(0)); }
11955 Seq root() const { return Seq(0); }
11956
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011957 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000011958 /// subset of \p Parent. This sequence of operations is sequenced with
11959 /// respect to other children of \p Parent.
11960 Seq allocate(Seq Parent) {
11961 Values.push_back(Value(Parent.Index));
11962 return Seq(Values.size() - 1);
11963 }
11964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011965 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000011966 void merge(Seq S) {
11967 Values[S.Index].Merged = true;
11968 }
11969
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011970 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000011971 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11972 /// should have been merged into its parent as appropriate.
11973 bool isUnsequenced(Seq Cur, Seq Old) {
11974 unsigned C = representative(Cur.Index);
11975 unsigned Target = representative(Old.Index);
11976 while (C >= Target) {
11977 if (C == Target)
11978 return true;
11979 C = Values[C].Parent;
11980 }
11981 return false;
11982 }
11983
11984 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011985 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000011986 unsigned representative(unsigned K) {
11987 if (Values[K].Merged)
11988 // Perform path compression as we go.
11989 return Values[K].Parent = representative(Values[K].Parent);
11990 return K;
11991 }
11992 };
11993
11994 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011995 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000011996
11997 /// Different flavors of object usage which we track. We only track the
11998 /// least-sequenced usage of each kind.
11999 enum UsageKind {
12000 /// A read of an object. Multiple unsequenced reads are OK.
12001 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012002
Richard Smithc406cb72013-01-17 01:17:56 +000012003 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000012004 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000012005 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012006
Richard Smithc406cb72013-01-17 01:17:56 +000012007 /// A modification of an object which is not sequenced before the value
12008 /// computation of the expression, such as n++.
12009 UK_ModAsSideEffect,
12010
12011 UK_Count = UK_ModAsSideEffect + 1
12012 };
12013
12014 struct Usage {
Serge Gueltonc1904042019-01-20 23:43:37 +000012015 Expr *Use;
Richard Smithc406cb72013-01-17 01:17:56 +000012016 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012017
Serge Gueltonc1904042019-01-20 23:43:37 +000012018 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000012019 };
12020
12021 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000012022 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012023
Richard Smithc406cb72013-01-17 01:17:56 +000012024 /// Have we issued a diagnostic for this variable already?
Serge Gueltonc1904042019-01-20 23:43:37 +000012025 bool Diagnosed;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012026
Serge Gueltonc1904042019-01-20 23:43:37 +000012027 UsageInfo() : Uses(), Diagnosed(false) {}
Richard Smithc406cb72013-01-17 01:17:56 +000012028 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012029 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000012030
12031 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012032
Richard Smithc406cb72013-01-17 01:17:56 +000012033 /// Sequenced regions within the expression.
12034 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012035
Richard Smithc406cb72013-01-17 01:17:56 +000012036 /// Declaration modifications and references which we have seen.
12037 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012038
Richard Smithc406cb72013-01-17 01:17:56 +000012039 /// The region we are currently within.
12040 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012041
Richard Smithc406cb72013-01-17 01:17:56 +000012042 /// Filled in with declarations which were modified as a side-effect
12043 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012044 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12045
Richard Smithd33f5202013-01-17 23:18:09 +000012046 /// Expressions to check later. We defer checking these to reduce
12047 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012048 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000012049
12050 /// RAII object wrapping the visitation of a sequenced subexpression of an
12051 /// expression. At the end of this process, the side-effects of the evaluation
12052 /// become sequenced with respect to the value computation of the result, so
12053 /// we downgrade any UK_ModAsSideEffect within the evaluation to
12054 /// UK_ModAsValue.
12055 struct SequencedSubexpression {
12056 SequencedSubexpression(SequenceChecker &Self)
12057 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12058 Self.ModAsSideEffect = &ModAsSideEffect;
12059 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012060
Richard Smithc406cb72013-01-17 01:17:56 +000012061 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000012062 for (auto &M : llvm::reverse(ModAsSideEffect)) {
12063 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000012064 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000012065 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12066 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000012067 }
12068 Self.ModAsSideEffect = OldModAsSideEffect;
12069 }
12070
12071 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012072 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012073 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000012074 };
12075
Richard Smith40238f02013-06-20 22:21:56 +000012076 /// RAII object wrapping the visitation of a subexpression which we might
12077 /// choose to evaluate as a constant. If any subexpression is evaluated and
12078 /// found to be non-constant, this allows us to suppress the evaluation of
12079 /// the outer expression.
12080 class EvaluationTracker {
12081 public:
12082 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012083 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000012084 Self.EvalTracker = this;
12085 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012086
Richard Smith40238f02013-06-20 22:21:56 +000012087 ~EvaluationTracker() {
12088 Self.EvalTracker = Prev;
12089 if (Prev)
12090 Prev->EvalOK &= EvalOK;
12091 }
12092
12093 bool evaluate(const Expr *E, bool &Result) {
12094 if (!EvalOK || E->isValueDependent())
12095 return false;
12096 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
12097 return EvalOK;
12098 }
12099
12100 private:
12101 SequenceChecker &Self;
12102 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012103 bool EvalOK = true;
12104 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000012105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012106 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000012107 /// if any.
12108 Object getObject(Expr *E, bool Mod) const {
12109 E = E->IgnoreParenCasts();
12110 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12111 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12112 return getObject(UO->getSubExpr(), Mod);
12113 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12114 if (BO->getOpcode() == BO_Comma)
12115 return getObject(BO->getRHS(), Mod);
12116 if (Mod && BO->isAssignmentOp())
12117 return getObject(BO->getLHS(), Mod);
12118 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12119 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12120 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12121 return ME->getMemberDecl();
12122 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12123 // FIXME: If this is a reference, map through to its value.
12124 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000012125 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000012126 }
12127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012128 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000012129 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12130 Usage &U = UI.Uses[UK];
12131 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12132 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12133 ModAsSideEffect->push_back(std::make_pair(O, U));
12134 U.Use = Ref;
12135 U.Seq = Region;
12136 }
12137 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012138
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012139 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000012140 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12141 bool IsModMod) {
12142 if (UI.Diagnosed)
12143 return;
12144
12145 const Usage &U = UI.Uses[OtherKind];
12146 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12147 return;
12148
12149 Expr *Mod = U.Use;
12150 Expr *ModOrUse = Ref;
12151 if (OtherKind == UK_Use)
12152 std::swap(Mod, ModOrUse);
12153
12154 SemaRef.Diag(Mod->getExprLoc(),
12155 IsModMod ? diag::warn_unsequenced_mod_mod
12156 : diag::warn_unsequenced_mod_use)
12157 << O << SourceRange(ModOrUse->getExprLoc());
12158 UI.Diagnosed = true;
12159 }
12160
12161 void notePreUse(Object O, Expr *Use) {
12162 UsageInfo &U = UsageMap[O];
12163 // Uses conflict with other modifications.
12164 checkUsage(O, U, Use, UK_ModAsValue, false);
12165 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012166
Richard Smithc406cb72013-01-17 01:17:56 +000012167 void notePostUse(Object O, Expr *Use) {
12168 UsageInfo &U = UsageMap[O];
12169 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12170 addUsage(U, O, Use, UK_Use);
12171 }
12172
12173 void notePreMod(Object O, Expr *Mod) {
12174 UsageInfo &U = UsageMap[O];
12175 // Modifications conflict with other modifications and with uses.
12176 checkUsage(O, U, Mod, UK_ModAsValue, true);
12177 checkUsage(O, U, Mod, UK_Use, false);
12178 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012179
Richard Smithc406cb72013-01-17 01:17:56 +000012180 void notePostMod(Object O, Expr *Use, UsageKind UK) {
12181 UsageInfo &U = UsageMap[O];
12182 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12183 addUsage(U, O, Use, UK);
12184 }
12185
12186public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012187 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012188 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000012189 Visit(E);
12190 }
12191
12192 void VisitStmt(Stmt *S) {
12193 // Skip all statements which aren't expressions for now.
12194 }
12195
12196 void VisitExpr(Expr *E) {
12197 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000012198 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000012199 }
12200
12201 void VisitCastExpr(CastExpr *E) {
12202 Object O = Object();
12203 if (E->getCastKind() == CK_LValueToRValue)
12204 O = getObject(E->getSubExpr(), false);
12205
12206 if (O)
12207 notePreUse(O, E);
12208 VisitExpr(E);
12209 if (O)
12210 notePostUse(O, E);
12211 }
12212
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012213 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12214 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12215 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12216 SequenceTree::Seq OldRegion = Region;
12217
12218 {
12219 SequencedSubexpression SeqBefore(*this);
12220 Region = BeforeRegion;
12221 Visit(SequencedBefore);
12222 }
12223
12224 Region = AfterRegion;
12225 Visit(SequencedAfter);
12226
12227 Region = OldRegion;
12228
12229 Tree.merge(BeforeRegion);
12230 Tree.merge(AfterRegion);
12231 }
12232
12233 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12234 // C++17 [expr.sub]p1:
12235 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12236 // expression E1 is sequenced before the expression E2.
12237 if (SemaRef.getLangOpts().CPlusPlus17)
12238 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12239 else
12240 Base::VisitStmt(ASE);
12241 }
12242
Richard Smithc406cb72013-01-17 01:17:56 +000012243 void VisitBinComma(BinaryOperator *BO) {
12244 // C++11 [expr.comma]p1:
12245 // Every value computation and side effect associated with the left
12246 // expression is sequenced before every value computation and side
12247 // effect associated with the right expression.
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012248 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
Richard Smithc406cb72013-01-17 01:17:56 +000012249 }
12250
12251 void VisitBinAssign(BinaryOperator *BO) {
12252 // The modification is sequenced after the value computation of the LHS
12253 // and RHS, so check it before inspecting the operands and update the
12254 // map afterwards.
12255 Object O = getObject(BO->getLHS(), true);
12256 if (!O)
12257 return VisitExpr(BO);
12258
12259 notePreMod(O, BO);
12260
12261 // C++11 [expr.ass]p7:
12262 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12263 // only once.
12264 //
12265 // Therefore, for a compound assignment operator, O is considered used
12266 // everywhere except within the evaluation of E1 itself.
12267 if (isa<CompoundAssignOperator>(BO))
12268 notePreUse(O, BO);
12269
12270 Visit(BO->getLHS());
12271
12272 if (isa<CompoundAssignOperator>(BO))
12273 notePostUse(O, BO);
12274
12275 Visit(BO->getRHS());
12276
Richard Smith83e37bee2013-06-26 23:16:51 +000012277 // C++11 [expr.ass]p1:
12278 // the assignment is sequenced [...] before the value computation of the
12279 // assignment expression.
12280 // C11 6.5.16/3 has no such rule.
12281 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12282 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012283 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012284
Richard Smithc406cb72013-01-17 01:17:56 +000012285 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12286 VisitBinAssign(CAO);
12287 }
12288
12289 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12290 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12291 void VisitUnaryPreIncDec(UnaryOperator *UO) {
12292 Object O = getObject(UO->getSubExpr(), true);
12293 if (!O)
12294 return VisitExpr(UO);
12295
12296 notePreMod(O, UO);
12297 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000012298 // C++11 [expr.pre.incr]p1:
12299 // the expression ++x is equivalent to x+=1
12300 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12301 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012302 }
12303
12304 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12305 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12306 void VisitUnaryPostIncDec(UnaryOperator *UO) {
12307 Object O = getObject(UO->getSubExpr(), true);
12308 if (!O)
12309 return VisitExpr(UO);
12310
12311 notePreMod(O, UO);
12312 Visit(UO->getSubExpr());
12313 notePostMod(O, UO, UK_ModAsSideEffect);
12314 }
12315
12316 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12317 void VisitBinLOr(BinaryOperator *BO) {
12318 // The side-effects of the LHS of an '&&' are sequenced before the
12319 // value computation of the RHS, and hence before the value computation
12320 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12321 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000012322 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012323 {
12324 SequencedSubexpression Sequenced(*this);
12325 Visit(BO->getLHS());
12326 }
12327
12328 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012329 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012330 if (!Result)
12331 Visit(BO->getRHS());
12332 } else {
12333 // Check for unsequenced operations in the RHS, treating it as an
12334 // entirely separate evaluation.
12335 //
12336 // FIXME: If there are operations in the RHS which are unsequenced
12337 // with respect to operations outside the RHS, and those operations
12338 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000012339 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012340 }
Richard Smithc406cb72013-01-17 01:17:56 +000012341 }
12342 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000012343 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012344 {
12345 SequencedSubexpression Sequenced(*this);
12346 Visit(BO->getLHS());
12347 }
12348
12349 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012350 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012351 if (Result)
12352 Visit(BO->getRHS());
12353 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000012354 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012355 }
Richard Smithc406cb72013-01-17 01:17:56 +000012356 }
12357
12358 // Only visit the condition, unless we can be sure which subexpression will
12359 // be chosen.
12360 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000012361 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000012362 {
12363 SequencedSubexpression Sequenced(*this);
12364 Visit(CO->getCond());
12365 }
Richard Smithc406cb72013-01-17 01:17:56 +000012366
12367 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012368 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000012369 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012370 else {
Richard Smithd33f5202013-01-17 23:18:09 +000012371 WorkList.push_back(CO->getTrueExpr());
12372 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012373 }
Richard Smithc406cb72013-01-17 01:17:56 +000012374 }
12375
Richard Smithe3dbfe02013-06-30 10:40:20 +000012376 void VisitCallExpr(CallExpr *CE) {
12377 // C++11 [intro.execution]p15:
12378 // When calling a function [...], every value computation and side effect
12379 // associated with any argument expression, or with the postfix expression
12380 // designating the called function, is sequenced before execution of every
12381 // expression or statement in the body of the function [and thus before
12382 // the value computation of its result].
12383 SequencedSubexpression Sequenced(*this);
12384 Base::VisitCallExpr(CE);
12385
12386 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12387 }
12388
Richard Smithc406cb72013-01-17 01:17:56 +000012389 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000012390 // This is a call, so all subexpressions are sequenced before the result.
12391 SequencedSubexpression Sequenced(*this);
12392
Richard Smithc406cb72013-01-17 01:17:56 +000012393 if (!CCE->isListInitialization())
12394 return VisitExpr(CCE);
12395
12396 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012397 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012398 SequenceTree::Seq Parent = Region;
12399 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12400 E = CCE->arg_end();
12401 I != E; ++I) {
12402 Region = Tree.allocate(Parent);
12403 Elts.push_back(Region);
12404 Visit(*I);
12405 }
12406
12407 // Forget that the initializers are sequenced.
12408 Region = Parent;
12409 for (unsigned I = 0; I < Elts.size(); ++I)
12410 Tree.merge(Elts[I]);
12411 }
12412
12413 void VisitInitListExpr(InitListExpr *ILE) {
12414 if (!SemaRef.getLangOpts().CPlusPlus11)
12415 return VisitExpr(ILE);
12416
12417 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012418 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012419 SequenceTree::Seq Parent = Region;
12420 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12421 Expr *E = ILE->getInit(I);
12422 if (!E) continue;
12423 Region = Tree.allocate(Parent);
12424 Elts.push_back(Region);
12425 Visit(E);
12426 }
12427
12428 // Forget that the initializers are sequenced.
12429 Region = Parent;
12430 for (unsigned I = 0; I < Elts.size(); ++I)
12431 Tree.merge(Elts[I]);
12432 }
12433};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012434
12435} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012436
12437void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012438 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012439 WorkList.push_back(E);
12440 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012441 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012442 SequenceChecker(*this, Item, WorkList);
12443 }
Richard Smithc406cb72013-01-17 01:17:56 +000012444}
12445
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012446void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12447 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000012448 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000012449 if (!E->isInstantiationDependent())
12450 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012451 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000012452 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012453 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000012454}
12455
John McCall1f425642010-11-11 03:21:53 +000012456void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12457 FieldDecl *BitField,
12458 Expr *Init) {
12459 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12460}
12461
David Majnemer61a5bbf2015-04-07 22:08:51 +000012462static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12463 SourceLocation Loc) {
12464 if (!PType->isVariablyModifiedType())
12465 return;
12466 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12467 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12468 return;
12469 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000012470 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12471 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12472 return;
12473 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000012474 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12475 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12476 return;
12477 }
12478
12479 const ArrayType *AT = S.Context.getAsArrayType(PType);
12480 if (!AT)
12481 return;
12482
12483 if (AT->getSizeModifier() != ArrayType::Star) {
12484 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12485 return;
12486 }
12487
12488 S.Diag(Loc, diag::err_array_star_in_function_definition);
12489}
12490
Mike Stump0c2ec772010-01-21 03:59:47 +000012491/// CheckParmsForFunctionDef - Check that the parameters of the given
12492/// function are appropriate for the definition of a function. This
12493/// takes care of any checks that cannot be performed on the
12494/// declaration itself, e.g., that the types of each of the function
12495/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000012496bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000012497 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012498 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000012499 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012500 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12501 // function declarator that is part of a function definition of
12502 // that function shall not have incomplete type.
12503 //
12504 // This is also C++ [dcl.fct]p6.
12505 if (!Param->isInvalidDecl() &&
12506 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012507 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012508 Param->setInvalidDecl();
12509 HasInvalidParm = true;
12510 }
12511
12512 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12513 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000012514 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012515 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000012516 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012517 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000012518 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000012519
12520 // C99 6.7.5.3p12:
12521 // If the function declarator is not part of a definition of that
12522 // function, parameters may have incomplete type and may use the [*]
12523 // notation in their sequences of declarator specifiers to specify
12524 // variable length array types.
12525 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000012526 // FIXME: This diagnostic should point the '[*]' if source-location
12527 // information is added for it.
12528 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012529
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012530 // If the parameter is a c++ class type and it has to be destructed in the
12531 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012532 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012533 if (!Param->isInvalidDecl()) {
12534 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12535 if (!ClassDecl->isInvalidDecl() &&
12536 !ClassDecl->hasIrrelevantDestructor() &&
12537 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000012538 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012539 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12540 MarkFunctionReferenced(Param->getLocation(), Destructor);
12541 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000012542 }
12543 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012544 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012545
12546 // Parameters with the pass_object_size attribute only need to be marked
12547 // constant at function definitions. Because we lack information about
12548 // whether we're on a declaration or definition when we're instantiating the
12549 // attribute, we need to check for constness here.
12550 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12551 if (!Param->getType().isConstQualified())
12552 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12553 << Attr->getSpelling() << 1;
Aaron Ballmanc3463f62018-12-05 18:56:57 +000012554
12555 // Check for parameter names shadowing fields from the class.
12556 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12557 // The owning context for the parameter should be the function, but we
12558 // want to see if this function's declaration context is a record.
12559 DeclContext *DC = Param->getDeclContext();
12560 if (DC && DC->isFunctionOrMethod()) {
12561 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12562 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12563 RD, /*DeclIsField*/ false);
12564 }
12565 }
Mike Stump0c2ec772010-01-21 03:59:47 +000012566 }
12567
12568 return HasInvalidParm;
12569}
John McCall2b5c1b22010-08-12 21:44:57 +000012570
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012571/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12572/// or MemberExpr.
12573static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12574 ASTContext &Context) {
12575 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12576 return Context.getDeclAlign(DRE->getDecl());
12577
12578 if (const auto *ME = dyn_cast<MemberExpr>(E))
12579 return Context.getDeclAlign(ME->getMemberDecl());
12580
12581 return TypeAlign;
12582}
12583
John McCall2b5c1b22010-08-12 21:44:57 +000012584/// CheckCastAlign - Implements -Wcast-align, which warns when a
12585/// pointer cast increases the alignment requirements.
12586void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12587 // This is actually a lot of work to potentially be doing on every
12588 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012589 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000012590 return;
12591
12592 // Ignore dependent types.
12593 if (T->isDependentType() || Op->getType()->isDependentType())
12594 return;
12595
12596 // Require that the destination be a pointer type.
12597 const PointerType *DestPtr = T->getAs<PointerType>();
12598 if (!DestPtr) return;
12599
12600 // If the destination has alignment 1, we're done.
12601 QualType DestPointee = DestPtr->getPointeeType();
12602 if (DestPointee->isIncompleteType()) return;
12603 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12604 if (DestAlign.isOne()) return;
12605
12606 // Require that the source be a pointer type.
12607 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12608 if (!SrcPtr) return;
12609 QualType SrcPointee = SrcPtr->getPointeeType();
12610
12611 // Whitelist casts from cv void*. We already implicitly
12612 // whitelisted casts to cv void*, since they have alignment 1.
12613 // Also whitelist casts involving incomplete types, which implicitly
12614 // includes 'void'.
12615 if (SrcPointee->isIncompleteType()) return;
12616
12617 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012618
12619 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12620 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12621 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12622 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12623 if (UO->getOpcode() == UO_AddrOf)
12624 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12625 }
12626
John McCall2b5c1b22010-08-12 21:44:57 +000012627 if (SrcAlign >= DestAlign) return;
12628
12629 Diag(TRange.getBegin(), diag::warn_cast_align)
12630 << Op->getType() << T
12631 << static_cast<unsigned>(SrcAlign.getQuantity())
12632 << static_cast<unsigned>(DestAlign.getQuantity())
12633 << TRange << Op->getSourceRange();
12634}
12635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012636/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000012637/// array member of a struct.
12638///
12639/// We avoid emitting out-of-bounds access warnings for such arrays as they are
12640/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000012641static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000012642 const NamedDecl *ND) {
12643 if (Size != 1 || !ND) return false;
12644
12645 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12646 if (!FD) return false;
12647
12648 // Don't consider sizes resulting from macro expansions or template argument
12649 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000012650
12651 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012652 while (TInfo) {
12653 TypeLoc TL = TInfo->getTypeLoc();
12654 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000012655 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12656 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012657 TInfo = TDL->getTypeSourceInfo();
12658 continue;
12659 }
David Blaikie6adc78e2013-02-18 22:06:02 +000012660 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12661 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000012662 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12663 return false;
12664 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012665 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000012666 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012667
12668 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000012669 if (!RD) return false;
12670 if (RD->isUnion()) return false;
12671 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12672 if (!CRD->isStandardLayout()) return false;
12673 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012674
Benjamin Kramer8c543672011-08-06 03:04:42 +000012675 // See if this is the last field decl in the record.
12676 const Decl *D = FD;
12677 while ((D = D->getNextDeclInContext()))
12678 if (isa<FieldDecl>(D))
12679 return false;
12680 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000012681}
12682
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012683void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012684 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000012685 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012686 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012687 if (IndexExpr->isValueDependent())
12688 return;
12689
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012690 const Type *EffectiveType =
12691 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012692 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012693 const ConstantArrayType *ArrayTy =
Bruno Riccied414842018-12-20 20:05:11 +000012694 Context.getAsConstantArrayType(BaseExpr->getType());
12695
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012696 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000012697 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000012698
Bruno Riccied414842018-12-20 20:05:11 +000012699 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
Bruno Ricci95550e42019-03-25 21:37:10 +000012700 if (EffectiveType->isDependentType() || BaseType->isDependentType())
12701 return;
Bruno Riccied414842018-12-20 20:05:11 +000012702
Fangrui Song407659a2018-11-30 23:41:18 +000012703 Expr::EvalResult Result;
12704 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000012705 return;
Fangrui Song407659a2018-11-30 23:41:18 +000012706
12707 llvm::APSInt index = Result.Val.getInt();
Richard Smith13f67182011-12-16 19:31:14 +000012708 if (IndexNegated)
12709 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000012710
Craig Topperc3ec1492014-05-26 06:22:03 +000012711 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000012712 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012713 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000012714 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012715 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000012716
Ted Kremeneke4b316c2011-02-23 23:06:04 +000012717 if (index.isUnsigned() || !index.isNegative()) {
Bruno Riccif605e822019-01-08 13:52:54 +000012718 // It is possible that the type of the base expression after
12719 // IgnoreParenCasts is incomplete, even though the type of the base
12720 // expression before IgnoreParenCasts is complete (see PR39746 for an
12721 // example). In this case we have no information about whether the array
12722 // access exceeds the array bounds. However we can still diagnose an array
12723 // access which precedes the array bounds.
12724 if (BaseType->isIncompleteType())
12725 return;
12726
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012727 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000012728 if (!size.isStrictlyPositive())
12729 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012730
Nico Weber7c299802011-09-17 22:59:41 +000012731 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012732 // Make sure we're comparing apples to apples when comparing index to size
12733 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12734 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000012735 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000012736 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012737 if (ptrarith_typesize != array_typesize) {
12738 // There's a cast to a different size type involved
12739 uint64_t ratio = array_typesize / ptrarith_typesize;
12740 // TODO: Be smarter about handling cases where array_typesize is not a
12741 // multiple of ptrarith_typesize
12742 if (ptrarith_typesize * ratio == array_typesize)
12743 size *= llvm::APInt(size.getBitWidth(), ratio);
12744 }
12745 }
12746
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012747 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012748 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012749 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012750 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012751
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012752 // For array subscripting the index must be less than size, but for pointer
12753 // arithmetic also allow the index (offset) to be equal to size since
12754 // computing the next address after the end of the array is legal and
12755 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012756 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000012757 return;
12758
12759 // Also don't warn for arrays of size 1 which are members of some
12760 // structure. These are often used to approximate flexible arrays in C89
12761 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012762 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000012763 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012764
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012765 // Suppress the warning if the subscript expression (as identified by the
12766 // ']' location) and the index expression are both from macro expansions
12767 // within a system header.
12768 if (ASE) {
12769 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12770 ASE->getRBracketLoc());
12771 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012772 SourceLocation IndexLoc =
12773 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000012774 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012775 return;
12776 }
12777 }
12778
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012779 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012780 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012781 DiagID = diag::warn_array_index_exceeds_bounds;
12782
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012783 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012784 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012785 << size.toString(10, true)
12786 << (unsigned)size.getLimitedValue(~0U)
12787 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012788 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012789 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012790 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012791 DiagID = diag::warn_ptr_arith_precedes_bounds;
12792 if (index.isNegative()) index = -index;
12793 }
12794
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012795 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012796 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012797 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000012798 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000012799
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012800 if (!ND) {
12801 // Try harder to find a NamedDecl to point at in the note.
12802 while (const ArraySubscriptExpr *ASE =
12803 dyn_cast<ArraySubscriptExpr>(BaseExpr))
12804 BaseExpr = ASE->getBase()->IgnoreParenCasts();
12805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012806 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012807 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012808 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012809 }
12810
Chandler Carruth1af88f12011-02-17 21:10:52 +000012811 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012812 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012813 PDiag(diag::note_array_index_out_of_bounds)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012814 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000012815}
12816
Ted Kremenekdf26df72011-03-01 18:41:00 +000012817void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012818 int AllowOnePastEnd = 0;
12819 while (expr) {
12820 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000012821 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012822 case Stmt::ArraySubscriptExprClass: {
12823 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012824 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012825 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000012826 expr = ASE->getBase();
12827 break;
12828 }
12829 case Stmt::MemberExprClass: {
12830 expr = cast<MemberExpr>(expr)->getBase();
12831 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012832 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012833 case Stmt::OMPArraySectionExprClass: {
12834 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12835 if (ASE->getLowerBound())
12836 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12837 /*ASE=*/nullptr, AllowOnePastEnd > 0);
12838 return;
12839 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012840 case Stmt::UnaryOperatorClass: {
12841 // Only unwrap the * and & unary operators
12842 const UnaryOperator *UO = cast<UnaryOperator>(expr);
12843 expr = UO->getSubExpr();
12844 switch (UO->getOpcode()) {
12845 case UO_AddrOf:
12846 AllowOnePastEnd++;
12847 break;
12848 case UO_Deref:
12849 AllowOnePastEnd--;
12850 break;
12851 default:
12852 return;
12853 }
12854 break;
12855 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012856 case Stmt::ConditionalOperatorClass: {
12857 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12858 if (const Expr *lhs = cond->getLHS())
12859 CheckArrayAccess(lhs);
12860 if (const Expr *rhs = cond->getRHS())
12861 CheckArrayAccess(rhs);
12862 return;
12863 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000012864 case Stmt::CXXOperatorCallExprClass: {
12865 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12866 for (const auto *Arg : OCE->arguments())
12867 CheckArrayAccess(Arg);
12868 return;
12869 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012870 default:
12871 return;
12872 }
Peter Collingbourne91147592011-04-15 00:35:48 +000012873 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012874}
John McCall31168b02011-06-15 23:02:42 +000012875
12876//===--- CHECK: Objective-C retain cycles ----------------------------------//
12877
12878namespace {
John McCall31168b02011-06-15 23:02:42 +000012879
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012880struct RetainCycleOwner {
12881 VarDecl *Variable = nullptr;
12882 SourceRange Range;
12883 SourceLocation Loc;
12884 bool Indirect = false;
12885
12886 RetainCycleOwner() = default;
12887
12888 void setLocsFrom(Expr *e) {
12889 Loc = e->getExprLoc();
12890 Range = e->getSourceRange();
12891 }
12892};
12893
12894} // namespace
John McCall31168b02011-06-15 23:02:42 +000012895
12896/// Consider whether capturing the given variable can possibly lead to
12897/// a retain cycle.
12898static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000012899 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000012900 // lifetime. In MRR, it's captured strongly if the variable is
12901 // __block and has an appropriate type.
12902 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12903 return false;
12904
12905 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012906 if (ref)
12907 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000012908 return true;
12909}
12910
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012911static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000012912 while (true) {
12913 e = e->IgnoreParens();
12914 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12915 switch (cast->getCastKind()) {
12916 case CK_BitCast:
12917 case CK_LValueBitCast:
12918 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000012919 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000012920 e = cast->getSubExpr();
12921 continue;
12922
John McCall31168b02011-06-15 23:02:42 +000012923 default:
12924 return false;
12925 }
12926 }
12927
12928 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12929 ObjCIvarDecl *ivar = ref->getDecl();
12930 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12931 return false;
12932
12933 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012934 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000012935 return false;
12936
12937 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12938 owner.Indirect = true;
12939 return true;
12940 }
12941
12942 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12943 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12944 if (!var) return false;
12945 return considerVariable(var, ref, owner);
12946 }
12947
John McCall31168b02011-06-15 23:02:42 +000012948 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12949 if (member->isArrow()) return false;
12950
12951 // Don't count this as an indirect ownership.
12952 e = member->getBase();
12953 continue;
12954 }
12955
John McCallfe96e0b2011-11-06 09:01:30 +000012956 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12957 // Only pay attention to pseudo-objects on property references.
12958 ObjCPropertyRefExpr *pre
12959 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12960 ->IgnoreParens());
12961 if (!pre) return false;
12962 if (pre->isImplicitProperty()) return false;
12963 ObjCPropertyDecl *property = pre->getExplicitProperty();
12964 if (!property->isRetaining() &&
12965 !(property->getPropertyIvarDecl() &&
12966 property->getPropertyIvarDecl()->getType()
12967 .getObjCLifetime() == Qualifiers::OCL_Strong))
12968 return false;
12969
12970 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012971 if (pre->isSuperReceiver()) {
12972 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12973 if (!owner.Variable)
12974 return false;
12975 owner.Loc = pre->getLocation();
12976 owner.Range = pre->getSourceRange();
12977 return true;
12978 }
John McCallfe96e0b2011-11-06 09:01:30 +000012979 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12980 ->getSourceExpr());
12981 continue;
12982 }
12983
John McCall31168b02011-06-15 23:02:42 +000012984 // Array ivars?
12985
12986 return false;
12987 }
12988}
12989
12990namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012991
John McCall31168b02011-06-15 23:02:42 +000012992 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012993 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000012994 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012995 Expr *Capturer = nullptr;
12996 bool VarWillBeReased = false;
12997
12998 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12999 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13000 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000013001
13002 void VisitDeclRefExpr(DeclRefExpr *ref) {
13003 if (ref->getDecl() == Variable && !Capturer)
13004 Capturer = ref;
13005 }
13006
John McCall31168b02011-06-15 23:02:42 +000013007 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13008 if (Capturer) return;
13009 Visit(ref->getBase());
13010 if (Capturer && ref->isFreeIvar())
13011 Capturer = ref;
13012 }
13013
13014 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000013015 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000013016 if (block->getBlockDecl()->capturesVariable(Variable))
13017 Visit(block->getBlockDecl()->getBody());
13018 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013019
Fariborz Jahanian0e337542012-08-31 20:04:47 +000013020 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13021 if (Capturer) return;
13022 if (OVE->getSourceExpr())
13023 Visit(OVE->getSourceExpr());
13024 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013025
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013026 void VisitBinaryOperator(BinaryOperator *BinOp) {
13027 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13028 return;
13029 Expr *LHS = BinOp->getLHS();
13030 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13031 if (DRE->getDecl() != Variable)
13032 return;
13033 if (Expr *RHS = BinOp->getRHS()) {
13034 RHS = RHS->IgnoreParenCasts();
13035 llvm::APSInt Value;
13036 VarWillBeReased =
13037 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13038 }
13039 }
13040 }
John McCall31168b02011-06-15 23:02:42 +000013041 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013042
13043} // namespace
John McCall31168b02011-06-15 23:02:42 +000013044
13045/// Check whether the given argument is a block which captures a
13046/// variable.
13047static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13048 assert(owner.Variable && owner.Loc.isValid());
13049
13050 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000013051
13052 // Look through [^{...} copy] and Block_copy(^{...}).
13053 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13054 Selector Cmd = ME->getSelector();
13055 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13056 e = ME->getInstanceReceiver();
13057 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000013058 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000013059 e = e->IgnoreParenCasts();
13060 }
13061 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13062 if (CE->getNumArgs() == 1) {
13063 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000013064 if (Fn) {
13065 const IdentifierInfo *FnI = Fn->getIdentifier();
13066 if (FnI && FnI->isStr("_Block_copy")) {
13067 e = CE->getArg(0)->IgnoreParenCasts();
13068 }
13069 }
Jordan Rose67e887c2012-09-17 17:54:30 +000013070 }
13071 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013072
John McCall31168b02011-06-15 23:02:42 +000013073 BlockExpr *block = dyn_cast<BlockExpr>(e);
13074 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000013075 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000013076
13077 FindCaptureVisitor visitor(S.Context, owner.Variable);
13078 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013079 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000013080}
13081
13082static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13083 RetainCycleOwner &owner) {
13084 assert(capturer);
13085 assert(owner.Variable && owner.Loc.isValid());
13086
13087 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13088 << owner.Variable << capturer->getSourceRange();
13089 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13090 << owner.Indirect << owner.Range;
13091}
13092
13093/// Check for a keyword selector that starts with the word 'add' or
13094/// 'set'.
13095static bool isSetterLikeSelector(Selector sel) {
13096 if (sel.isUnarySelector()) return false;
13097
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013098 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000013099 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013100 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000013101 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013102 else if (str.startswith("add")) {
13103 // Specially whitelist 'addOperationWithBlock:'.
13104 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13105 return false;
13106 str = str.substr(3);
13107 }
John McCall31168b02011-06-15 23:02:42 +000013108 else
13109 return false;
13110
13111 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000013112 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000013113}
13114
Benjamin Kramer3a743452015-03-09 15:03:32 +000013115static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13116 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013117 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13118 Message->getReceiverInterface(),
13119 NSAPI::ClassId_NSMutableArray);
13120 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013121 return None;
13122 }
13123
13124 Selector Sel = Message->getSelector();
13125
13126 Optional<NSAPI::NSArrayMethodKind> MKOpt =
13127 S.NSAPIObj->getNSArrayMethodKind(Sel);
13128 if (!MKOpt) {
13129 return None;
13130 }
13131
13132 NSAPI::NSArrayMethodKind MK = *MKOpt;
13133
13134 switch (MK) {
13135 case NSAPI::NSMutableArr_addObject:
13136 case NSAPI::NSMutableArr_insertObjectAtIndex:
13137 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13138 return 0;
13139 case NSAPI::NSMutableArr_replaceObjectAtIndex:
13140 return 1;
13141
13142 default:
13143 return None;
13144 }
13145
13146 return None;
13147}
13148
13149static
13150Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13151 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013152 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13153 Message->getReceiverInterface(),
13154 NSAPI::ClassId_NSMutableDictionary);
13155 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013156 return None;
13157 }
13158
13159 Selector Sel = Message->getSelector();
13160
13161 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13162 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13163 if (!MKOpt) {
13164 return None;
13165 }
13166
13167 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13168
13169 switch (MK) {
13170 case NSAPI::NSMutableDict_setObjectForKey:
13171 case NSAPI::NSMutableDict_setValueForKey:
13172 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13173 return 0;
13174
13175 default:
13176 return None;
13177 }
13178
13179 return None;
13180}
13181
13182static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013183 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13184 Message->getReceiverInterface(),
13185 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000013186
Alex Denisov5dfac812015-08-06 04:51:14 +000013187 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13188 Message->getReceiverInterface(),
13189 NSAPI::ClassId_NSMutableOrderedSet);
13190 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013191 return None;
13192 }
13193
13194 Selector Sel = Message->getSelector();
13195
13196 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13197 if (!MKOpt) {
13198 return None;
13199 }
13200
13201 NSAPI::NSSetMethodKind MK = *MKOpt;
13202
13203 switch (MK) {
13204 case NSAPI::NSMutableSet_addObject:
13205 case NSAPI::NSOrderedSet_setObjectAtIndex:
13206 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13207 case NSAPI::NSOrderedSet_insertObjectAtIndex:
13208 return 0;
13209 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13210 return 1;
13211 }
13212
13213 return None;
13214}
13215
13216void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13217 if (!Message->isInstanceMessage()) {
13218 return;
13219 }
13220
13221 Optional<int> ArgOpt;
13222
13223 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13224 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13225 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13226 return;
13227 }
13228
13229 int ArgIndex = *ArgOpt;
13230
Alex Denisove1d882c2015-03-04 17:55:52 +000013231 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13232 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13233 Arg = OE->getSourceExpr()->IgnoreImpCasts();
13234 }
13235
Alex Denisov5dfac812015-08-06 04:51:14 +000013236 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013237 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013238 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013239 Diag(Message->getSourceRange().getBegin(),
13240 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013241 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000013242 }
13243 }
Alex Denisov5dfac812015-08-06 04:51:14 +000013244 } else {
13245 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13246
13247 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13248 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13249 }
13250
13251 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13252 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13253 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13254 ValueDecl *Decl = ReceiverRE->getDecl();
13255 Diag(Message->getSourceRange().getBegin(),
13256 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013257 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013258 if (!ArgRE->isObjCSelfExpr()) {
13259 Diag(Decl->getLocation(),
13260 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013261 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013262 }
13263 }
13264 }
13265 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13266 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13267 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13268 ObjCIvarDecl *Decl = IvarRE->getDecl();
13269 Diag(Message->getSourceRange().getBegin(),
13270 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013271 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013272 Diag(Decl->getLocation(),
13273 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013274 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013275 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013276 }
13277 }
13278 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013279}
13280
John McCall31168b02011-06-15 23:02:42 +000013281/// Check a message send to see if it's likely to cause a retain cycle.
13282void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13283 // Only check instance methods whose selector looks like a setter.
13284 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13285 return;
13286
13287 // Try to find a variable that the receiver is strongly owned by.
13288 RetainCycleOwner owner;
13289 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013290 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000013291 return;
13292 } else {
13293 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13294 owner.Variable = getCurMethodDecl()->getSelfDecl();
13295 owner.Loc = msg->getSuperLoc();
13296 owner.Range = msg->getSuperLoc();
13297 }
13298
13299 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000013300 const ObjCMethodDecl *MD = msg->getMethodDecl();
13301 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13302 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13303 // noescape blocks should not be retained by the method.
13304 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13305 continue;
John McCall31168b02011-06-15 23:02:42 +000013306 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000013307 }
13308 }
John McCall31168b02011-06-15 23:02:42 +000013309}
13310
13311/// Check a property assign to see if it's likely to cause a retain cycle.
13312void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13313 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013314 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000013315 return;
13316
13317 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13318 diagnoseRetainCycle(*this, capturer, owner);
13319}
13320
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013321void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13322 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000013323 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013324 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013325
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013326 // Because we don't have an expression for the variable, we have to set the
13327 // location explicitly here.
13328 Owner.Loc = Var->getLocation();
13329 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000013330
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013331 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13332 diagnoseRetainCycle(*this, Capturer, Owner);
13333}
13334
Ted Kremenek9304da92012-12-21 08:04:28 +000013335static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13336 Expr *RHS, bool isProperty) {
13337 // Check if RHS is an Objective-C object literal, which also can get
13338 // immediately zapped in a weak reference. Note that we explicitly
13339 // allow ObjCStringLiterals, since those are designed to never really die.
13340 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013341
Ted Kremenek64873352012-12-21 22:46:35 +000013342 // This enum needs to match with the 'select' in
13343 // warn_objc_arc_literal_assign (off-by-1).
13344 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13345 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13346 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013347
13348 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000013349 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000013350 << (isProperty ? 0 : 1)
13351 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013352
13353 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000013354}
13355
Ted Kremenekc1f014a2012-12-21 19:45:30 +000013356static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13357 Qualifiers::ObjCLifetime LT,
13358 Expr *RHS, bool isProperty) {
13359 // Strip off any implicit cast added to get to the one ARC-specific.
13360 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13361 if (cast->getCastKind() == CK_ARCConsumeObject) {
13362 S.Diag(Loc, diag::warn_arc_retained_assign)
13363 << (LT == Qualifiers::OCL_ExplicitNone)
13364 << (isProperty ? 0 : 1)
13365 << RHS->getSourceRange();
13366 return true;
13367 }
13368 RHS = cast->getSubExpr();
13369 }
13370
13371 if (LT == Qualifiers::OCL_Weak &&
13372 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13373 return true;
13374
13375 return false;
13376}
13377
Ted Kremenekb36234d2012-12-21 08:04:20 +000013378bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13379 QualType LHS, Expr *RHS) {
13380 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13381
13382 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13383 return false;
13384
13385 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13386 return true;
13387
13388 return false;
13389}
13390
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013391void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13392 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013393 QualType LHSType;
13394 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000013395 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013396 ObjCPropertyRefExpr *PRE
13397 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13398 if (PRE && !PRE->isImplicitProperty()) {
13399 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13400 if (PD)
13401 LHSType = PD->getType();
13402 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013403
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013404 if (LHSType.isNull())
13405 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000013406
13407 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13408
13409 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013410 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000013411 getCurFunction()->markSafeWeakUse(LHS);
13412 }
13413
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013414 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13415 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000013416
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013417 // FIXME. Check for other life times.
13418 if (LT != Qualifiers::OCL_None)
13419 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013420
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013421 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013422 if (PRE->isImplicitProperty())
13423 return;
13424 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13425 if (!PD)
13426 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013427
Bill Wendling44426052012-12-20 19:22:21 +000013428 unsigned Attributes = PD->getPropertyAttributes();
13429 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013430 // when 'assign' attribute was not explicitly specified
13431 // by user, ignore it and rely on property type itself
13432 // for lifetime info.
13433 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13434 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13435 LHSType->isObjCRetainableType())
13436 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013437
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013438 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000013439 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013440 Diag(Loc, diag::warn_arc_retained_property_assign)
13441 << RHS->getSourceRange();
13442 return;
13443 }
13444 RHS = cast->getSubExpr();
13445 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013446 }
Bill Wendling44426052012-12-20 19:22:21 +000013447 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000013448 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13449 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000013450 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013451 }
13452}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013453
13454//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13455
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013456static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13457 SourceLocation StmtLoc,
13458 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013459 // Do not warn if the body is a macro that expands to nothing, e.g:
13460 //
13461 // #define CALL(x)
13462 // if (condition)
13463 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013464 if (Body->hasLeadingEmptyMacro())
13465 return false;
13466
13467 // Get line numbers of statement and body.
13468 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000013469 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013470 &StmtLineInvalid);
13471 if (StmtLineInvalid)
13472 return false;
13473
13474 bool BodyLineInvalid;
13475 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13476 &BodyLineInvalid);
13477 if (BodyLineInvalid)
13478 return false;
13479
13480 // Warn if null statement and body are on the same line.
13481 if (StmtLine != BodyLine)
13482 return false;
13483
13484 return true;
13485}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013486
13487void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13488 const Stmt *Body,
13489 unsigned DiagID) {
13490 // Since this is a syntactic check, don't emit diagnostic for template
13491 // instantiations, this just adds noise.
13492 if (CurrentInstantiationScope)
13493 return;
13494
13495 // The body should be a null statement.
13496 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13497 if (!NBody)
13498 return;
13499
13500 // Do the usual checks.
13501 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13502 return;
13503
13504 Diag(NBody->getSemiLoc(), DiagID);
13505 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13506}
13507
13508void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13509 const Stmt *PossibleBody) {
13510 assert(!CurrentInstantiationScope); // Ensured by caller
13511
13512 SourceLocation StmtLoc;
13513 const Stmt *Body;
13514 unsigned DiagID;
13515 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13516 StmtLoc = FS->getRParenLoc();
13517 Body = FS->getBody();
13518 DiagID = diag::warn_empty_for_body;
13519 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13520 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13521 Body = WS->getBody();
13522 DiagID = diag::warn_empty_while_body;
13523 } else
13524 return; // Neither `for' nor `while'.
13525
13526 // The body should be a null statement.
13527 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13528 if (!NBody)
13529 return;
13530
13531 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013532 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013533 return;
13534
13535 // Do the usual checks.
13536 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13537 return;
13538
13539 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13540 // noise level low, emit diagnostics only if for/while is followed by a
13541 // CompoundStmt, e.g.:
13542 // for (int i = 0; i < n; i++);
13543 // {
13544 // a(i);
13545 // }
13546 // or if for/while is followed by a statement with more indentation
13547 // than for/while itself:
13548 // for (int i = 0; i < n; i++);
13549 // a(i);
13550 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13551 if (!ProbableTypo) {
13552 bool BodyColInvalid;
13553 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013554 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013555 if (BodyColInvalid)
13556 return;
13557
13558 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013559 unsigned StmtCol =
13560 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013561 if (StmtColInvalid)
13562 return;
13563
13564 if (BodyCol > StmtCol)
13565 ProbableTypo = true;
13566 }
13567
13568 if (ProbableTypo) {
13569 Diag(NBody->getSemiLoc(), DiagID);
13570 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13571 }
13572}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013573
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013574//===--- CHECK: Warn on self move with std::move. -------------------------===//
13575
13576/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13577void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13578 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013579 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13580 return;
13581
Richard Smith51ec0cf2017-02-21 01:17:38 +000013582 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013583 return;
13584
13585 // Strip parens and casts away.
13586 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13587 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13588
13589 // Check for a call expression
13590 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13591 if (!CE || CE->getNumArgs() != 1)
13592 return;
13593
13594 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000013595 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013596 return;
13597
13598 // Get argument from std::move
13599 RHSExpr = CE->getArg(0);
13600
13601 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13602 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13603
13604 // Two DeclRefExpr's, check that the decls are the same.
13605 if (LHSDeclRef && RHSDeclRef) {
13606 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13607 return;
13608 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13609 RHSDeclRef->getDecl()->getCanonicalDecl())
13610 return;
13611
13612 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13613 << LHSExpr->getSourceRange()
13614 << RHSExpr->getSourceRange();
13615 return;
13616 }
13617
13618 // Member variables require a different approach to check for self moves.
13619 // MemberExpr's are the same if every nested MemberExpr refers to the same
13620 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13621 // the base Expr's are CXXThisExpr's.
13622 const Expr *LHSBase = LHSExpr;
13623 const Expr *RHSBase = RHSExpr;
13624 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13625 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13626 if (!LHSME || !RHSME)
13627 return;
13628
13629 while (LHSME && RHSME) {
13630 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13631 RHSME->getMemberDecl()->getCanonicalDecl())
13632 return;
13633
13634 LHSBase = LHSME->getBase();
13635 RHSBase = RHSME->getBase();
13636 LHSME = dyn_cast<MemberExpr>(LHSBase);
13637 RHSME = dyn_cast<MemberExpr>(RHSBase);
13638 }
13639
13640 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13641 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13642 if (LHSDeclRef && RHSDeclRef) {
13643 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13644 return;
13645 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13646 RHSDeclRef->getDecl()->getCanonicalDecl())
13647 return;
13648
13649 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13650 << LHSExpr->getSourceRange()
13651 << RHSExpr->getSourceRange();
13652 return;
13653 }
13654
13655 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13656 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13657 << LHSExpr->getSourceRange()
13658 << RHSExpr->getSourceRange();
13659}
13660
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013661//===--- Layout compatibility ----------------------------------------------//
13662
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013663static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013665/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013666static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013667 // C++11 [dcl.enum] p8:
13668 // Two enumeration types are layout-compatible if they have the same
13669 // underlying type.
13670 return ED1->isComplete() && ED2->isComplete() &&
13671 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13672}
13673
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013674/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013675static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13676 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013677 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13678 return false;
13679
13680 if (Field1->isBitField() != Field2->isBitField())
13681 return false;
13682
13683 if (Field1->isBitField()) {
13684 // Make sure that the bit-fields are the same length.
13685 unsigned Bits1 = Field1->getBitWidthValue(C);
13686 unsigned Bits2 = Field2->getBitWidthValue(C);
13687
13688 if (Bits1 != Bits2)
13689 return false;
13690 }
13691
13692 return true;
13693}
13694
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013695/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013696/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013697static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13698 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013699 // If both records are C++ classes, check that base classes match.
13700 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13701 // If one of records is a CXXRecordDecl we are in C++ mode,
13702 // thus the other one is a CXXRecordDecl, too.
13703 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13704 // Check number of base classes.
13705 if (D1CXX->getNumBases() != D2CXX->getNumBases())
13706 return false;
13707
13708 // Check the base classes.
13709 for (CXXRecordDecl::base_class_const_iterator
13710 Base1 = D1CXX->bases_begin(),
13711 BaseEnd1 = D1CXX->bases_end(),
13712 Base2 = D2CXX->bases_begin();
13713 Base1 != BaseEnd1;
13714 ++Base1, ++Base2) {
13715 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13716 return false;
13717 }
13718 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13719 // If only RD2 is a C++ class, it should have zero base classes.
13720 if (D2CXX->getNumBases() > 0)
13721 return false;
13722 }
13723
13724 // Check the fields.
13725 RecordDecl::field_iterator Field2 = RD2->field_begin(),
13726 Field2End = RD2->field_end(),
13727 Field1 = RD1->field_begin(),
13728 Field1End = RD1->field_end();
13729 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13730 if (!isLayoutCompatible(C, *Field1, *Field2))
13731 return false;
13732 }
13733 if (Field1 != Field1End || Field2 != Field2End)
13734 return false;
13735
13736 return true;
13737}
13738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013739/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013740/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013741static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13742 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013743 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013744 for (auto *Field2 : RD2->fields())
13745 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013746
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013747 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013748 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13749 I = UnmatchedFields.begin(),
13750 E = UnmatchedFields.end();
13751
13752 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013753 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013754 bool Result = UnmatchedFields.erase(*I);
13755 (void) Result;
13756 assert(Result);
13757 break;
13758 }
13759 }
13760 if (I == E)
13761 return false;
13762 }
13763
13764 return UnmatchedFields.empty();
13765}
13766
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013767static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13768 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013769 if (RD1->isUnion() != RD2->isUnion())
13770 return false;
13771
13772 if (RD1->isUnion())
13773 return isLayoutCompatibleUnion(C, RD1, RD2);
13774 else
13775 return isLayoutCompatibleStruct(C, RD1, RD2);
13776}
13777
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013778/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013779static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013780 if (T1.isNull() || T2.isNull())
13781 return false;
13782
13783 // C++11 [basic.types] p11:
13784 // If two types T1 and T2 are the same type, then T1 and T2 are
13785 // layout-compatible types.
13786 if (C.hasSameType(T1, T2))
13787 return true;
13788
13789 T1 = T1.getCanonicalType().getUnqualifiedType();
13790 T2 = T2.getCanonicalType().getUnqualifiedType();
13791
13792 const Type::TypeClass TC1 = T1->getTypeClass();
13793 const Type::TypeClass TC2 = T2->getTypeClass();
13794
13795 if (TC1 != TC2)
13796 return false;
13797
13798 if (TC1 == Type::Enum) {
13799 return isLayoutCompatible(C,
13800 cast<EnumType>(T1)->getDecl(),
13801 cast<EnumType>(T2)->getDecl());
13802 } else if (TC1 == Type::Record) {
13803 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13804 return false;
13805
13806 return isLayoutCompatible(C,
13807 cast<RecordType>(T1)->getDecl(),
13808 cast<RecordType>(T2)->getDecl());
13809 }
13810
13811 return false;
13812}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013813
13814//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013816/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013817///
13818/// \param TypeExpr Type tag expression, as it appears in user's code.
13819///
13820/// \param VD Declaration of an identifier that appears in a type tag.
13821///
13822/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013823static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13824 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013825 while(true) {
13826 if (!TypeExpr)
13827 return false;
13828
13829 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13830
13831 switch (TypeExpr->getStmtClass()) {
13832 case Stmt::UnaryOperatorClass: {
13833 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13834 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13835 TypeExpr = UO->getSubExpr();
13836 continue;
13837 }
13838 return false;
13839 }
13840
13841 case Stmt::DeclRefExprClass: {
13842 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13843 *VD = DRE->getDecl();
13844 return true;
13845 }
13846
13847 case Stmt::IntegerLiteralClass: {
13848 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13849 llvm::APInt MagicValueAPInt = IL->getValue();
13850 if (MagicValueAPInt.getActiveBits() <= 64) {
13851 *MagicValue = MagicValueAPInt.getZExtValue();
13852 return true;
13853 } else
13854 return false;
13855 }
13856
13857 case Stmt::BinaryConditionalOperatorClass:
13858 case Stmt::ConditionalOperatorClass: {
13859 const AbstractConditionalOperator *ACO =
13860 cast<AbstractConditionalOperator>(TypeExpr);
13861 bool Result;
13862 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13863 if (Result)
13864 TypeExpr = ACO->getTrueExpr();
13865 else
13866 TypeExpr = ACO->getFalseExpr();
13867 continue;
13868 }
13869 return false;
13870 }
13871
13872 case Stmt::BinaryOperatorClass: {
13873 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13874 if (BO->getOpcode() == BO_Comma) {
13875 TypeExpr = BO->getRHS();
13876 continue;
13877 }
13878 return false;
13879 }
13880
13881 default:
13882 return false;
13883 }
13884 }
13885}
13886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013887/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013888///
13889/// \param TypeExpr Expression that specifies a type tag.
13890///
13891/// \param MagicValues Registered magic values.
13892///
13893/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13894/// kind.
13895///
13896/// \param TypeInfo Information about the corresponding C type.
13897///
13898/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013899static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013900 const IdentifierInfo *ArgumentKind,
13901 const Expr *TypeExpr, const ASTContext &Ctx,
13902 const llvm::DenseMap<Sema::TypeTagMagicValue,
13903 Sema::TypeTagData> *MagicValues,
13904 bool &FoundWrongKind,
13905 Sema::TypeTagData &TypeInfo) {
13906 FoundWrongKind = false;
13907
13908 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000013909 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013910
13911 uint64_t MagicValue;
13912
13913 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13914 return false;
13915
13916 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000013917 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013918 if (I->getArgumentKind() != ArgumentKind) {
13919 FoundWrongKind = true;
13920 return false;
13921 }
13922 TypeInfo.Type = I->getMatchingCType();
13923 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13924 TypeInfo.MustBeNull = I->getMustBeNull();
13925 return true;
13926 }
13927 return false;
13928 }
13929
13930 if (!MagicValues)
13931 return false;
13932
13933 llvm::DenseMap<Sema::TypeTagMagicValue,
13934 Sema::TypeTagData>::const_iterator I =
13935 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13936 if (I == MagicValues->end())
13937 return false;
13938
13939 TypeInfo = I->second;
13940 return true;
13941}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013942
13943void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13944 uint64_t MagicValue, QualType Type,
13945 bool LayoutCompatible,
13946 bool MustBeNull) {
13947 if (!TypeTagForDatatypeMagicValues)
13948 TypeTagForDatatypeMagicValues.reset(
13949 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13950
13951 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13952 (*TypeTagForDatatypeMagicValues)[Magic] =
13953 TypeTagData(Type, LayoutCompatible, MustBeNull);
13954}
13955
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013956static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013957 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13958 if (!BT1)
13959 return false;
13960
13961 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13962 if (!BT2)
13963 return false;
13964
13965 BuiltinType::Kind T1Kind = BT1->getKind();
13966 BuiltinType::Kind T2Kind = BT2->getKind();
13967
13968 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
13969 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
13970 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13971 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13972}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013973
13974void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013975 const ArrayRef<const Expr *> ExprArgs,
13976 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013977 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13978 bool IsPointerAttr = Attr->getIsPointer();
13979
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013980 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000013981 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13982 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013983 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013984 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013985 return;
13986 }
Joel E. Denny81508102018-03-13 14:51:22 +000013987 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013988 bool FoundWrongKind;
13989 TypeTagData TypeInfo;
13990 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13991 TypeTagForDatatypeMagicValues.get(),
13992 FoundWrongKind, TypeInfo)) {
13993 if (FoundWrongKind)
13994 Diag(TypeTagExpr->getExprLoc(),
13995 diag::warn_type_tag_for_datatype_wrong_kind)
13996 << TypeTagExpr->getSourceRange();
13997 return;
13998 }
13999
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014000 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000014001 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14002 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014003 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000014004 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014005 return;
14006 }
Joel E. Denny81508102018-03-13 14:51:22 +000014007 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014008 if (IsPointerAttr) {
14009 // Skip implicit cast of pointer to `void *' (as a function argument).
14010 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000014011 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000014012 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014013 ArgumentExpr = ICE->getSubExpr();
14014 }
14015 QualType ArgumentType = ArgumentExpr->getType();
14016
14017 // Passing a `void*' pointer shouldn't trigger a warning.
14018 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14019 return;
14020
14021 if (TypeInfo.MustBeNull) {
14022 // Type tag with matching void type requires a null pointer.
14023 if (!ArgumentExpr->isNullPointerConstant(Context,
14024 Expr::NPC_ValueDependentIsNotNull)) {
14025 Diag(ArgumentExpr->getExprLoc(),
14026 diag::warn_type_safety_null_pointer_required)
14027 << ArgumentKind->getName()
14028 << ArgumentExpr->getSourceRange()
14029 << TypeTagExpr->getSourceRange();
14030 }
14031 return;
14032 }
14033
14034 QualType RequiredType = TypeInfo.Type;
14035 if (IsPointerAttr)
14036 RequiredType = Context.getPointerType(RequiredType);
14037
14038 bool mismatch = false;
14039 if (!TypeInfo.LayoutCompatible) {
14040 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14041
14042 // C++11 [basic.fundamental] p1:
14043 // Plain char, signed char, and unsigned char are three distinct types.
14044 //
14045 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14046 // char' depending on the current char signedness mode.
14047 if (mismatch)
14048 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14049 RequiredType->getPointeeType())) ||
14050 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14051 mismatch = false;
14052 } else
14053 if (IsPointerAttr)
14054 mismatch = !isLayoutCompatible(Context,
14055 ArgumentType->getPointeeType(),
14056 RequiredType->getPointeeType());
14057 else
14058 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14059
14060 if (mismatch)
14061 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000014062 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014063 << TypeInfo.LayoutCompatible << RequiredType
14064 << ArgumentExpr->getSourceRange()
14065 << TypeTagExpr->getSourceRange();
14066}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014067
14068void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14069 CharUnits Alignment) {
14070 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14071}
14072
14073void Sema::DiagnoseMisalignedMembers() {
14074 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000014075 const NamedDecl *ND = m.RD;
14076 if (ND->getName().empty()) {
14077 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14078 ND = TD;
14079 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014080 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000014081 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014082 }
14083 MisalignedMembers.clear();
14084}
14085
14086void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014087 E = E->IgnoreParens();
14088 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014089 return;
14090 if (isa<UnaryOperator>(E) &&
14091 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14092 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14093 if (isa<MemberExpr>(Op)) {
Fangrui Song75e74e02019-03-31 08:48:19 +000014094 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014095 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014096 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000014097 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14098 Context.getTypeAlignInChars(
14099 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014100 MisalignedMembers.erase(MA);
14101 }
14102 }
14103}
14104
14105void Sema::RefersToMemberWithReducedAlignment(
14106 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000014107 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14108 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014109 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014110 if (!ME)
14111 return;
14112
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000014113 // No need to check expressions with an __unaligned-qualified type.
14114 if (E->getType().getQualifiers().hasUnaligned())
14115 return;
14116
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014117 // For a chain of MemberExpr like "a.b.c.d" this list
14118 // will keep FieldDecl's like [d, c, b].
14119 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14120 const MemberExpr *TopME = nullptr;
14121 bool AnyIsPacked = false;
14122 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014123 QualType BaseType = ME->getBase()->getType();
14124 if (ME->isArrow())
14125 BaseType = BaseType->getPointeeType();
14126 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000014127 if (RD->isInvalidDecl())
14128 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014129
14130 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014131 auto *FD = dyn_cast<FieldDecl>(MD);
14132 // We do not care about non-data members.
14133 if (!FD || FD->isInvalidDecl())
14134 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014135
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014136 AnyIsPacked =
14137 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14138 ReverseMemberChain.push_back(FD);
14139
14140 TopME = ME;
14141 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14142 } while (ME);
14143 assert(TopME && "We did not compute a topmost MemberExpr!");
14144
14145 // Not the scope of this diagnostic.
14146 if (!AnyIsPacked)
14147 return;
14148
14149 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14150 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14151 // TODO: The innermost base of the member expression may be too complicated.
14152 // For now, just disregard these cases. This is left for future
14153 // improvement.
14154 if (!DRE && !isa<CXXThisExpr>(TopBase))
14155 return;
14156
14157 // Alignment expected by the whole expression.
14158 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14159
14160 // No need to do anything else with this case.
14161 if (ExpectedAlignment.isOne())
14162 return;
14163
14164 // Synthesize offset of the whole access.
14165 CharUnits Offset;
14166 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14167 I++) {
14168 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14169 }
14170
14171 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14172 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14173 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14174
14175 // The base expression of the innermost MemberExpr may give
14176 // stronger guarantees than the class containing the member.
14177 if (DRE && !TopME->isArrow()) {
14178 const ValueDecl *VD = DRE->getDecl();
14179 if (!VD->getType()->isReferenceType())
14180 CompleteObjectAlignment =
14181 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14182 }
14183
14184 // Check if the synthesized offset fulfills the alignment.
14185 if (Offset % ExpectedAlignment != 0 ||
14186 // It may fulfill the offset it but the effective alignment may still be
14187 // lower than the expected expression alignment.
14188 CompleteObjectAlignment < ExpectedAlignment) {
14189 // If this happens, we want to determine a sensible culprit of this.
14190 // Intuitively, watching the chain of member expressions from right to
14191 // left, we start with the required alignment (as required by the field
14192 // type) but some packed attribute in that chain has reduced the alignment.
14193 // It may happen that another packed structure increases it again. But if
14194 // we are here such increase has not been enough. So pointing the first
14195 // FieldDecl that either is packed or else its RecordDecl is,
14196 // seems reasonable.
14197 FieldDecl *FD = nullptr;
14198 CharUnits Alignment;
14199 for (FieldDecl *FDI : ReverseMemberChain) {
14200 if (FDI->hasAttr<PackedAttr>() ||
14201 FDI->getParent()->hasAttr<PackedAttr>()) {
14202 FD = FDI;
14203 Alignment = std::min(
14204 Context.getTypeAlignInChars(FD->getType()),
14205 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14206 break;
14207 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014208 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014209 assert(FD && "We did not find a packed FieldDecl!");
14210 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014211 }
14212}
14213
14214void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14215 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014216
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014217 RefersToMemberWithReducedAlignment(
14218 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14219 _2, _3, _4));
14220}